commons-collections4-4.0-src/default.properties100664 5465 12243235515 17770 0ustartntn 0 0 # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # $Id: default.properties 1495867 2013-06-23 18:27:46Z tn $ # The location of the "junit.jar" JAR file junit.jar = ${junit.home}/junit-4.11.jar # The location of the "junit.jar" JAR file hamcrest.jar = ${hamcrest.home}/hamcrest-core-1.3.jar # The location of the Easymock jar easymock.jar = ${easymock.home}/easymock-3.1.jar # Whether or not to fork tests junit.fork = true # The name of this component component.name = commons-collections4 # The primary package name of this component component.package = org.apache.commons.collections4 # The title of this component component.title = Commons Collections # The current version number of this component component.version = 4.0-SNAPSHOT # The name that is used to create the jar file final.name = ${component.name}-${component.version} # The base directory for compilation targets build.home = target # The base directory for component configuration files conf.home = src/conf # The base directory for component sources source.home = src/main/java # The base directory for unit test sources test.home = src/test/java # Should Java compilations set the 'debug' compiler option? compile.debug = true # Should Java compilations set the 'deprecation' compiler option? compile.deprecation = true # Should Java compilations set the 'optimize' compiler option? compile.optimize = true # 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). compile.target = 1.5 # 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. compile.source = 1.5 # Specifies the source encoding. compile.encoding = ISO-8859-1 # Should all tests fail if one does? test.failonerror = true # The test runner to execute test.runner = junit.textui.TestRunner commons-collections4-4.0-src/build.properties.sample100664 2640 12243235517 20715 0ustartntn 0 0 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ########################################################################## # Sample Ant build.properties file # # This setup assumes dependent jars are in a local maven 2 repository. # However the jars are located, the properties ending in ".jar" need # expand to full paths to the jars. ########################################################################## # Repository base path - unnecessary if full jar paths are provided below repository=${user.home}/.m2/repository junit.home=${repository}/junit/junit/4.11/ hamcrest.home=${repository}/org/hamcrest/hamcrest-core/1.3/ easymock.home=${repository}/org/easymock/easymock/3.2/ commons-collections4-4.0-src/PROPOSAL.html100664 7343 12243235515 16350 0ustartntn 0 0 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

(4) Initial Committers

commons-collections4-4.0-src/pom.xml100664 47302 12243235517 15561 0ustartntn 0 0 org.apache.commons commons-parent 32 4.0.0 org.apache.commons commons-collections4 4.0 Apache Commons Collections 2001 The Apache Commons Collections package contains types that extend and augment the Java Collections Framework. http://commons.apache.org/proper/commons-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 Matt Benson mbenson James Carman jcarman Stephen Colebourne scolebourne Robert Burrell Donkin rdonkin Morgan Delagrange morgand Gary D. Gregory ggregory Matthew Hawthorne matth Geir Magnusson geirm Luc Maisonobe luc Craig McClanahan craigmcc Adrian Nistor adriannistor Phil Steitz psteitz Arun M. Thomas amamment Rodney Waldhoff rwaldhoff Henri Yandell bayard Thomas Neidhart tn Rafael U. C. Afonso Max Rydahl Andersen Avalon Federico Barbieri Jeffrey Barnes Nicola Ken Barozzi Arron Bates Sebastian Bazley Benjamin Bentmann Ola Berg Sam Berlin Christopher Berry Nathan Beyer Rune Peter Bjørnstad Janek Bogucki Maarten Brak Dave Bryson Chuck Burdick Julien Buret Josh Cain Jonathan Carlson Ram Chidambaram Steve Clark Benoit Corne Eric Crampton Dimiter Dimitrov Peter Donald Steve Downey Rich Dougherty Tom Dunham Stefano Fornari Andrew Freeman Gerhard Froehlich Goran Hacek David Hay Mario Ivankovits Paul Jack Eric Johnson Kent Johnson Marc Johnson Roger Kapsi Nissim Karpenstein Shinobu Kawai Stephen Kestle 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 David Meikle 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 Joerg Schmuecker Howard Lewis Ship Joe Raysa Jeff Rodriguez Ashwin S Jordane Sarda 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 Thomas Vahrst Jeff Varszegi Ralph Wagner Hollis Waite David Weinrich Dieter Wimberger Serhiy Yevtushenko Sai Zhang Jason van Zyl junit junit 4.11 test org.easymock easymock 3.2 test apache.website Apache Commons Site ${commons.deployment.protocol}://people.apache.org/www/commons.apache.org/${commons.componentid} UTF-8 UTF-8 1.5 1.5 collections4 4.0 (Java 5.0+) 3.2.1 (Requires Java 1.2 or later) commons-collections-${commons.release.2.version} COLLECTIONS 12310465 RC5 2.9.1 collections https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-collections site-content 2.9.1 org.apache.maven.plugins maven-surefire-plugin **/*Test.java **/*$* **/TestUtils.java **/Abstract*.java **/BulkTest.java maven-assembly-plugin src/main/assembly/bin.xml src/main/assembly/src.xml gnu maven-checkstyle-plugin ${checkstyle.version} ${basedir}/src/conf/checkstyle.xml false org.apache.maven.plugins maven-scm-publish-plugin javadocs org.apache.maven.plugins maven-changes-plugin ${commons.changes.version} %URL%/%ISSUE% false Fix Version,Key,Summary,Type,Resolution,Status Key DESC,Type,Fix Version DESC Fixed Resolved,Closed Bug,New Feature,Task,Improvement,Wish,Test ${commons.release.version} 500 changes-report jira-report maven-checkstyle-plugin ${checkstyle.version} ${basedir}/src/conf/checkstyle.xml false ${basedir}/src/conf/checkstyle-suppressions.xml checkstyle org.codehaus.mojo clirr-maven-plugin ${commons.clirr.version} ${minSeverity} org.codehaus.mojo findbugs-maven-plugin 2.5.2 Normal Default ${basedir}/src/conf/findbugs-exclude-filter.xml org.codehaus.mojo cobertura-maven-plugin 2.5.2 maven-pmd-plugin 2.7.1 ${maven.compiler.target} pmd cpd org.apache.rat apache-rat-plugin site-content/**/* maven-eclipse.xml setup-checkout site-content org.apache.maven.plugins maven-antrun-plugin 1.7 prepare-checkout pre-site run commons-collections4-4.0-src/build.xml100664 31607 12243235515 16064 0ustartntn 0 0 commons-collections4-4.0-src/NOTICE.txt100664 264 12243235515 15720 0ustartntn 0 0 Apache Commons Collections Copyright 2001-2013 The Apache Software Foundation This product includes software developed at The Apache Software Foundation (http://www.apache.org/). commons-collections4-4.0-src/README.txt100664 3144 12243235515 15714 0ustartntn 0 0 Apache Commons Collections =========================== Welcome to the Collections component of the Apache Commons project. This component contains many new collections and collection utilities. Two jar files (apart from sources and javadocs) are produced by this component. The first, commons-collections4-x.y.jar is the main jar used by applications. The second, commons-collections4-x.y-tests.jar is an extension to junit for testing new collection implementations and is not normally used by applications. Building from source =-=-=-=-=-=-=-=-=-=- Maven2 ------ Collections is usually built using Maven2. It can be found here : http://maven.apache.org/ Once installed, the major goals are: mvn package - build jars mvn install - place jars in local maven repository mvn assembly:assembly - build tar.gz/zips Ant --- It may also be built using Ant. 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 test-jar - create the testframework jar file ant javadoc - build the javadoc ant dist - create folders as per a distribution commons-collections4-4.0-src/RELEASE-NOTES.txt100664 73554 12243235515 16761 0ustartntn 0 0 Apache Commons Collections Version 4.0 RELEASE NOTES INTRODUCTION: Commons collections is a project to develop and maintain collection classes based on and inspired by the JDK collection framework. This version uses the generics features of Java 5 and is not compatible with earlier JDK versions. The process of generifying an API is complex. For commons-collections, we have chosen to break the API in various ways. The aim behind this is to provide an API design that better suits generics. We have also removed all deprecated classes and fixed oddities in the previous API that we couldn't fix due to backwards compatibility restrictions. As such, this release can not be considered to be a simple, drop-in, replacement for commons-collections. To help with the migration to this new version, the package has changed to "org.apache.commons.collections4", thus it is possible to have both commons-collections versions in the classpath. These release notes will try to guide you in the process of upgrading, however you should remember that this is a new API based on the original, so some concepts have changed. Compatibility ------------- o Java 5 or later is required. o This release is not source or binary compatible with previous releases of Commons Collections. This includes releases from the 3.x branch as well as preceding alpha releases for 4.0 (see details of changes below). o some unit tests are disabled when executed with an IBM JDK 6 due to a faulty java.util.TreeMap implementation. Major changes since 3.2.1 ------------------------- o Use of generics and other language features introduced in Java 5 (varargs, Iterable) o Removed deprecated classes / methods and features which are now supported by the JDK o Replaced Buffer interface with java.util.Queue o Added concept of split maps with respective interfaces Put / Get (see also package splitmap) o Added new Trie interface together with an implementation of a Patricia Trie Changes since 4.0-alpha1 ------------------------ o [COLLECTIONS-502] Resolved generic parameter inconsistency for various static fields, e.g. BagUtils.EMPTY_BAG, TruePredicate.INSTANCE and many others. All accessible static fields use raw types so that they can be used directly without explicit casting. To avoid compiler warnings about unchecked conversion and/or rawtypes use the corresponding factory methods, e.g. BagUtils.emptyBag(). o [COLLECTIONS-501] Renamed methods "V MultiKeyMap#remove(Object, Object, ...)" to "V MultiKeyMap#removeMultiKey(Object, Object, ...)" to avoid future conflicts with a default method of the Map interface in Java 8. o [COLLECTIONS-500] Renamed "V MultiMap#remove(K, V)" to "boolean MultiMap#removeMapping(K, V)" to avoid future conflicts with a default method of the Map interface in Java 8. o [COLLECTIONS-499] Refactored the test framework for Bag implementations to extend from "AbstractCollectionTest" by decorating the concrete Bag instance with a CollectionBag or CollectionSortedBag. o [COLLECTIONS-498] "CollectionBag" will now also respect the contract of the decorated bag in case a null argument is provided to either removeAll or retainAll. o [COLLECTIONS-497] Added bag decorator "CollectionSortedBag" which decorates a SortedBag to make it comply with the Collection contract. o [COLLECTIONS-496] "UnmodifiableBoundedCollection" does now also implement the marker interface "Unmodifiable" similar as all other unmodifiable decorators. o [COLLECTIONS-495] "UnmodifiableTrie#unmodifiableTrie(Trie)" will not decorate again an already unmodifiable Trie. Also the return type has been changed to "Trie" to be consistent with other Unmodifiable decorators. o [COLLECTIONS-494] Moved "Equator" interface to base package for consistency. Thanks to Emmanuel Bourg. o [COLLECTIONS-488] Added "CollectionsUtils#matchesAll(Iterable, Predicate)" to test if all elements of a collection match a given predicate. Thanks to Josh Cain. o [COLLECTIONS-485] Accept wildcard input where possible, e.g. in copy-constructors, Unmodifiable* decorators and iterators. Thanks to Hollis Waite. o [COLLECTIONS-481] No collision detection/resolution was performed when calling "CompositeSet#addComposited(...)" with more than one Set as argument. Additionally use varargs parameters instead of arrays in CompositeSet and CompositeCollection constructor and addComposited method. Thanks to Hollis Waite. o [COLLECTIONS-480] Narrow return type of "BidiMap#values()" to Set as the values are required to be unique. Thanks to Hollis Waite. o [COLLECTIONS-468] Renamed CompliantBag to CollectionBag. o [COLLECTIONS-475] Fixed conversion of timeout parameters in "PassiveExpiringMap". Removed classes --------------- o [COLLECTIONS-458] Removed unused class "AbstractUntypedCollectionDecorator" o [COLLECTIONS-432] Removed "Buffer" interface and all its implementations and related classes. Replaced by "java.util.Queue", see also section [New classes] - PriorityBuffer: use either java.util.PriorityQueue or java.util.concurrent.PriorityBlockingQueue - SynchronizedBuffer: use the corresponding *BlockingQueue classes in java.util.concurrent - BoundedBuffer: use either ArrayBlockingBuffer(capacity) or LinkedBlockingBuffer(capacity) in java.util.concurrent - UnboundedFifoBuffer: use either java.util.LinkedList or java.util.concurrent.LinkedBlockingBuffer o [COLLECTIONS-351] Removed features now supported by the JDK or other Apache Commons libraries - FastArrayList: use java.util.concurrent.CopyOnWriteArrayList - FastHashMap: use java.util.concurrent.ConcurrentHashMap, but beware of null keys and values - FastTreeSet: no direct replacement, use ConcurrentHashMap or a synchronized TreeMap - IdentityMap: use java.util.IdentityHashMap - ExtendedProperties: use commons-configuration - Synchronized[List,Set,SortedSet]: use java.util.Collections.synchronized*() - Typed* decorators: use generics for type safety, or java.util.Collections.checked*() - [List,Set,Map]Utils.EMPTY_*: use the corresponding fields in java.util.Collections o [COLLECTIONS-229] Removed deprecated collection classes and methods New classes ----------- o [COLLECTIONS-497] CollectionSortedBag - decorates a SortedBag to make it comply with the Collection contract. o [COLLECTIONS-468] CollectionBag - decorates another Bag to make it comply with the Collection contract. o [COLLECTIONS-463] PushbackIterator - supports pushback of elements during iteration. Thanks to Andy Seaborne, Claude Warren. o [COLLECTIONS-462] PeekingIterator - supports one-element lookahead during iteration. Thanks to Andy Seaborne, Claude Warren. o [COLLECTIONS-432] CircularFifoQueue - analogous class to CircularFifoBuffer for the Queue interface PredicatedQueue - analogous class to PredicatedBuffer TransformedQueue - analogous class to TransformedBuffer UnmodifiableQueue - analogous class to UnmodifiableBuffer QueueUtils - analogous class to BufferUtils o [COLLECTIONS-422] PermutationIterator - generates unordered permutations of a collection. Thanks to Benoit Corne. o [COLLECTIONS-404] SequencesComparator - an implementation of Eugene Myers difference algorithm in package o.a.c.c.sequence. Thanks to Jordane Sarda. o [COLLECTIONS-396] LazyIteratorChain - a variant of IteratorChain which supports lazy initialization. Thanks to Jeff Rodriguez. o [COLLECTIONS-322] NodeListIterator - supports iteration over a org.w3c.dom.NodeList. Thanks to Thomas Vahrst. o [COLLECTIONS-313] CatchAndRethrowClosure - re-throws any checked exception as unchecked "FunctorException". Thanks to David J. M. Karlsen. o [COLLECTIONS-275] IndexedCollection - collection decorator which provides a map-like view on an existing collection. Thanks to Stephen Kestle. o [COLLECTIONS-258] DualLinkedHashBidiMap - bidi map implementation using LinkedHashMap instances. Thanks to Nathan Blomquist. o [COLLECTIONS-242] Equator - interface for testing object equality. o [COLLECTIONS-241] PassiveExpiringMap - map decorator which passively expires entries. Thanks to Elifarley Callado Coelho. o [COLLECTIONS-225] PatriciaTrie - PATRICIA trie implementation for the new Trie interface, together with Unmodifiable and Synchronized decorators. Thanks to Sam Berlin and Roger Kapsi. o [COLLECTIONS-8 ] ComparatorPredicate - predicate to compare objects against a fixed instance. Thanks to Rune Peter Bjørnstad. o [None ] Put / Get - interfaces for split maps o [None ] SplitMapUtils / splitmap.TransformedSplitMap - utilities and implementation for split maps New methods in *Utils --------------------- o [COLLECTIONS-488] Added "CollectionsUtils#matchesAll(Iterable, Predicate)" to test if all elements of a collection match a given predicate. Thanks to Josh Cain. o [COLLECTIONS-456] ListUtils#longestCommonSubsequence(...) to get the longest common subsequence of arbitrary lists or CharSequences. o [COLLECTIONS-450] CollectionUtils#forAllButLastDo(Collection, Closure) and forAllButLastDo(Iterator, Closure). Thanks to J. Moldawski. o [COLLECTIONS-446] CollectionUtils#isEqualCollection(Collection, Collection, Equator). Thanks to Matt Lachman. o [COLLECTIONS-436] *Utils#emptyIfNull(*) methods in classes CollectionUtils, ListUtils, SetUtils and MapUtils. Thanks to Arman Sharif. o [COLLECTIONS-429] CollectionUtils#containsAll(Collection, Collection) with guaranteed runtime complexity of O(n + m) +COLLECTIONS-434] and space complexity of O(n). This method may yield much better performance than Collection.containsAll(Collection) depending on the use-case and type of collection used. Thanks to Adrian Nistor, Mert Guldur. o [COLLECTIONS-422] CollectionUtils#permutations(Collection) to generate all permutations of a collection. Thanks to Benoit Corne. o [COLLECTIONS-405] ListUtils#select() and ListUtils#selectRejected() methods. Thanks to Adam Dyga. o [COLLECTIONS-393] ListUtils#partition() to split a List into consecutive sublists. Thanks to Chris Shayan. o [COLLECTIONS-383] CollectionUtils#forAllDo(Iterator, Closure). Thanks to Adrian Cumiskey. o [COLLECTIONS-375] ListUtils#defaultIfNull(List, List). Thanks to Ivan Hristov. o [COLLECTIONS-361] CollectionUtils#filterInverse(Iterable, Predicate). Thanks to Jean-Noel Rouvignac. o [COLLECTIONS-306] CollectionUtils#subtract(Iterable, Iterable, Predicate). Thanks to Chris Shayan. o [COLLECTIONS-296] CollectionUtils#collate(...) to merge two sorted Collections using the standard O(n) merge algorithm. Thanks to Julius Davies. o [COLLECTIONS-286] CollectionUtils#extractSingleton(Collection). Thanks to Geoffrey De Smet. o [COLLECTIONS-263] MapUtils#populateMap(MultiMap, ...) to support also "MultiMap" instances as input. Thanks to John Hunsley. o [COLLECTIONS-235] ListUtils#indexOf(List, Predicate). Thanks to Nathan Egge. o [COLLECTIONS-194] MapUtils#populateMap(Map, Iterable, Transformer, ...). Thanks to Dave Meikle. New features ------------ o [COLLECTIONS-399] Added new method "get(int)" to "CircularFifoQueue". Thanks to Sebb. o [COLLECTIONS-327] Added serialVersionUID fields for "CompositeCollection", "CompositeSet", "EmptyMapMutator", "EmptySetMutator". Thanks to sebb. o [COLLECTIONS-293] Added support for using custom "Equator" objects in "EqualPredicate". Thanks to Stephen Kestle. o [COLLECTIONS-289] Added method "CollatingIterator#getIteratorIndex()". Thanks to Fredrik Kjellberg. o [COLLECTIONS-285] Added serialization support for "TreeBidiMap". Thanks to Christian Gruenberg. o [COLLECTIONS-272] Added serialization support for "FixedOrderComparator" and "TransformingComparator". Thanks to Chaitanya Mutyala. o [COLLECTIONS-260] Added constructor "TransformingComparator(Transformer)". Thanks to Stephen Kestle. o [COLLECTIONS-237] Added method "MultiValueMap#iterator()" to return a flattened version of "entrySet().iterator()". Clarified javadoc for "entrySet()" that the returned Entry objects are unflattened, i.e. the Entry object for a given key contains all values mapped to this key. Thanks to Nils Kaiser, Alan Mehlo. o [COLLECTIONS-226] Added method "ListOrderedMap#putAll(int, Map)". Thanks to Vasily Ivanov. o [COLLECTIONS-213] Added support for resettable iterators in "IteratorIterable". Thanks to Dusan Chromy. Changed classes / methods ------------------------- o [COLLECTIONS-502] Resolved generic parameter inconsistency for various static fields, e.g. BagUtils.EMPTY_BAG, TruePredicate.INSTANCE and many others. All accessible static fields use raw types so that they can be used directly without explicit casting. To avoid compiler warnings about unchecked conversion and/or rawtypes use the corresponding factory methods, e.g. BagUtils.emptyBag(). o [COLLECTIONS-501] Renamed methods "V MultiKeyMap#remove(Object, Object, ...)" to "V MultiKeyMap#removeMultiKey(Object, Object, ...)" to avoid future conflicts with a default method of the Map interface in Java 8. o [COLLECTIONS-500] Renamed "V MultiMap#remove(K, V)" to "boolean MultiMap#removeMapping(K, V)" to avoid future conflicts with a default method of the Map interface in Java 8. o [COLLECTIONS-499] Refactored the test framework for Bag implementations to extend from "AbstractCollectionTest" by decorating the concrete Bag instance with a CollectionBag or CollectionSortedBag. o [COLLECTIONS-496] "UnmodifiableBoundedCollection" does now also implement the marker interface "Unmodifiable" similar as all other unmodifiable decorators. o [COLLECTIONS-495] "UnmodifiableTrie#unmodifiableTrie(Trie)" will not decorate again an already unmodifiable Trie. Also the return type has been changed to "Trie" to be consistent with other Unmodifiable decorators. o [COLLECTIONS-494] Moved "Equator" interface to base package for consistency. Thanks to Emmanuel Bourg. o [COLLECTIONS-485] Accept wildcard input where possible, e.g. in copy-constructors, Unmodifiable* decorators and iterators. Thanks to Hollis Waite. o [COLLECTIONS-480] Narrow return type of "BidiMap#values()" to Set as the values are required to be unique. Thanks to Hollis Waite. o [COLLECTIONS-473] Made field "collection" in class "AbstractCollectionDecorator" private and added setter "setCollection(Collection)" with scope protected to set the decorated collection during de-serialization. o [COLLECTIONS-466] Replaced "Collection" with "Iterable" for method arguments where applicable. o [COLLECTIONS-460] Changed "IteratorChain" to use internally a "Queue" instead of a "List". Iterators are removed from the queue once used and can be garbage collected after being exhausted. Additionally removed the methods "setIterator(Iterator)" and "getIterators()". o [COLLECTIONS-459] Removed method "setArray(Object)" in class ArrayIterator and method "setArray(Object[])" in class ObjectArrayIterator and made fields array, startIndex and endIndex final and package private. o [COLLECTIONS-455] Changed scope of various fields to private / package private where appropriate. o [COLLECTIONS-454] An iterator over a "Flat3Map#entrySet()" will now return independent Map.Entry objects that will not change anymore when the iterator progresses. o [COLLECTIONS-453] Several closure and transformer implementations in the functor package will now copy an array as input parameter to their constructor (e.g. ChainedClosure). o [COLLECTIONS-452] Change base package to "org.apache.commons.collections4". o [COLLECTIONS-451] The constructors for all *Utils classes are now private to prevent instantiation. o [COLLECTIONS-424] "CompositeSet" does not inherit from "CompositeCollection" anymore. The inner class "SetMutator" has been updated accordingly. Thanks to Michael Pradel. o [COLLECTIONS-382] Change maven coordinates to "org.apache.commons.commons-collections4". Thanks to Olivier Lamy. o [COLLECTIONS-381] Move the project structure to a standard maven layout. Thanks to Olivier Lamy. o [COLLECTIONS-372] TransformingComparator now supports different types for its input/output values. o [COLLECTIONS-362] "CollectionUtils#filter(Iterable, Predicate)" will now return whether the collection has been modified. Thanks to Jean-Noel Rouvignac. o [COLLECTIONS-341] "NOPClosure" is now a final class. Thanks to Goran Hacek. o [COLLECTIONS-324] Fields transformer and decorated in class "TransformingComparator" are now final. Thanks to sebb. o [COLLECTIONS-307] "SetUniqueList#subList()" will now return an unmodifiable list as changes to it may invalidate the parent list. Thanks to Christian Semrau, Thomas Vahrst. o [COLLECTIONS-298] Calling "CollectionUtils#sizeIsEmpty(null)" will now return true. Thanks to Benjamin Bentmann. o [COLLECTIONS-280] The predicate that rejected an object to be added to a "PredicatedCollection" is now contained in the respective exception message. Thanks to Chris Lewis. o [COLLECTIONS-265] "TreeBag" will now only accept "Comparable" objects as input when used with natural ordering. Thanks to David Saff. o [COLLECTIONS-251] The static factory methods have been renamed from "getInstance()" to a camel-case version of the class name, +COLLECTIONS-321] e.g. "truePredicate()" for class "TruePredicate". Thanks to Stephen Kestle. o [COLLECTIONS-240] "MultiValueMap" is now serializable. Thanks to Wouter de Vaal. o [COLLECTIONS-231] Return concrete class in static factory methods instead of base class interface (except for Unmodifiable decorators). Thanks to Torsten Curdt. o [COLLECTIONS-230] "CollectionUtils#size(Collection)" now returns 0 when called with null as input. Thanks to Stepan Koltsov,sebb. +COLLECTIONS-297] +COLLECTIONS-318] o [COLLECTIONS-223] "CollectionUtils#addAll(...)" methods now return if the collection has been changed by this operation. Thanks to Vasily Ivanov. o [COLLECTIONS-221] "CompositeCollection", "CompositeMap" and "CompositeSet" are now serializable. Thanks to Pal Denes. o [COLLECTIONS-218] The "CollectionUtils#select(Collection, Predicate, Collection)" method will now return the output collection. o [COLLECTIONS-182] "CollectionUtils#forAllDo(Collection, Closure)" now returns the provided closure. Thanks to Jim Cakalic. o [COLLECTIONS-110] Make generic versions of all classes in collections. +COLLECTIONS-243] +COLLECTIONS-245] +COLLECTIONS-247] +COLLECTIONS-253] +COLLECTIONS-273] +COLLECTIONS-282] o [None ] Switch Abstract*Decorator classes to expose decorated() protected method instead of the decorated collection directly. Each class overrides decorated() to add its type covariantly, thus getList()/getSet() etc. methods are removed o [None ] ArrayStack is now deprecated and will be removed in the next major release. It is replaced by the java.util.Deque interface available from Java 6. Fixed Bugs ---------- o [COLLECTIONS-498] "CollectionBag" will now also respect the contract of the decorated bag in case a null argument is provided to either removeAll or retainAll. o [COLLECTIONS-481] No collision detection/resolution was performed when calling "CompositeSet#addComposited(...)" with more than one Set as argument. Additionally use varargs parameters instead of arrays in CompositeSet and CompositeCollection constructor and addComposited method. Thanks to Hollis Waite. o [COLLECTIONS-475] Fixed conversion of timeout parameters in "PassiveExpiringMap". o [COLLECTIONS-474] ListOrderedMap#putAll(index, Object, Object) does not throw an exception anymore if the map contains null values. Additionally added javadoc clarification on the supported bounds for the index parameter. Thanks to Ning Chen. o [COLLECTIONS-472] Improved performance of "AbstractMapBag#containsAll(Collection)" by returning immediately after a difference has been found. Thanks to Adrian Nistor. o [COLLECTIONS-461] Added additional clarification to javadoc of interface "Put" wrt return type of "put(Object, Object)" method. Thanks to Matt Benson, sebb. o [COLLECTIONS-447] Tree traversal with a TreeListIterator will not be affected anymore by the removal of an element directly after a call to previous(). Thanks to Jeffrey Barnes. o [COLLECTIONS-445] Adapt and/or ignore several unit tests when run on a IBM J9 VM (specification version 1.6.0) due to a faulty "java.util.TreeMap" implementation. o [COLLECTIONS-444] SetUniqueList.set(int, E) now works correctly if the object to be inserted is already placed at the given position. Thanks to Thomas Vahrst, John Vasileff. o [COLLECTIONS-441] MultiKeyMap.clone() now correctly calls super.clone(). Thanks to Thomas Vahrst. o [COLLECTIONS-433] Improve performance of "TreeList#addAll" and "TreeList(Collection)" by converting the input collection into an AVL tree and efficiently merge it into the existing tree. Thanks to Jeffrey Barnes. o [COLLECTIONS-427] Fixed performance issue in "SetUniqueList#retainAll" method for large collections. Thanks to Mert Guldur. o [COLLECTIONS-426] Fixed performance issue in "ListOrderedSet#retainAll" method for large collections. Thanks to Adrian Nistor. o [COLLECTIONS-425] Improved performance of "ListOrderedMap#remove(Object)" method. Thanks to Adrian Nistor. o [COLLECTIONS-421] Update javadoc for "ListUtils#lazyList()" and "ListUtils#fixedSizeList()". Thanks to Benedikt Ritter. o [COLLECTIONS-419] Added clarifying javadoc wrt runtime complexity of "AbstractDualBidiMap#retainAll". Thanks to Adrian Nistor. o [COLLECTIONS-417] Added clarifying javadoc wrt runtime complexity of "AbstractLinkedList#retainAll". Thanks to Adrian Nistor. o [COLLECTIONS-415] Added clarifying javadoc wrt runtime complexity of "AbstractLinkedList#removeAll". Thanks to Adrian Nistor. o [COLLECTIONS-414] Fixed several compilation issues with older Java 1.6 compilers. o [COLLECTIONS-413] Improved performance of "removeAll()" method for sets returned by "DualHashBidiMap#entrySet()". Thanks to Adrian Nistor. o [COLLECTIONS-412] Improved performance of "CollectionUtils#subtract" methods. Thanks to Adrian Nistor. o [COLLECTIONS-411] Fixed possible "IndexOutOfBoundsException" in "ListOrderedMap#putAll". Thanks to Adrian Nistor. o [COLLECTIONS-410] Improved performance of "SetUniqueList#addAll" method. Thanks to Adrian Nistor. o [COLLECTIONS-409] Improved performance of "ListOrderedSet#addAll" method. Thanks to Adrian Nistor. o [COLLECTIONS-408] Improved performance of "SetUniqueList#removeAll". Thanks to Adrian Nistor. o [COLLECTIONS-407] Improved performance of "ListOrderedSet#remove(Object)" in case the object is not contained in the Set. Thanks to Adrian Nistor. o [COLLECTIONS-406] Improved performance of "ListUtils#subtract" method. Thanks to Adrian Nistor. o [COLLECTIONS-400] Added missing null check in "CollectionUtils#addIgnoreNull(Collection, Object)". Thanks to Shin Hwei Tan. o [COLLECTIONS-391] Fixed javadoc for "MapUtils#toProperties(Map)". Thanks to Shin Hwei Tan. o [COLLECTIONS-389] Clarified javadoc for "TransformerUtils#mapTransformer" for null input. Thanks to Shin Hwei Tan. o [COLLECTIONS-388] Clarified javadoc for "FactoryUtils#prototypeFactory" for null input. Thanks to Shin Hwei Tan. o [COLLECTIONS-384] Fixed inconsistent javadoc for "MapUtils#synchronizedMap(Map)". Thanks to Shin Hwei Tan. o [COLLECTIONS-380] Fixed infinite loop when calling "UnmodifiableBoundedCollection#unmodifiableBoundedCollection()". Thanks to Dave Brosius. o [COLLECTIONS-379] Fixed javadoc for several methods wrt expected NullPointerExceptions. Thanks to Shin Hwei Tan. o [COLLECTIONS-364] "DualTreeBidiMap" now uses the correct comparator for the reverse map during de-serialization. o [COLLECTIONS-363] "TransformedMap" in the package "splitmap" can now be serialized. o [COLLECTIONS-360] "FilterListIterator#hasNext" does not throw a NullPointerException anymore to comply to the Java iterator specification. Thanks to Sai Zhang. o [COLLECTIONS-359] "ListUtils#intersection(List, List)" will now also work correctly if there are duplicate elements in the provided lists. Thanks to Mark Shead. o [COLLECTIONS-352] "AbstractCollectionDecorator" will now use internally "decorated()" to access the decorated collection. Thanks to Adam Gent. o [COLLECTIONS-350] Removed debug output in "MapUtils#getNumber(Map)". Thanks to Michael Akerman. o [COLLECTIONS-348] Fixed javadoc for all "transformedXXX(XXX)" methods in the respective Utils classes to clarify that existing objects in the list are not transformed. Thanks to Paul Benedict. o [COLLECTIONS-343] Singleton classes in package "functors" are now correctly de-serialized. Thanks to Goran Hacek. o [COLLECTIONS-340] Removed broken methods "equals(Object)" and "hashCode()" in class "NOPClosure". Thanks to Goran Hacek. o [COLLECTIONS-336] Simplified exceptions as the cause is available from the parent. Thanks to sebb. o [COLLECTIONS-335] Fixed cache assignment for "TreeBidiMap#entrySet". Thanks to sebb. o [COLLECTIONS-334] Synchronized access to lock in "StaticBucketMap#size()". Thanks to sebb. o [COLLECTIONS-332] Added clarification to javadoc of "ListOrderedMap" that "IdentityMap" and "CaseInsensitiveMap" are not supported. Thanks to Tom Parker. o [COLLECTIONS-331] Improve javadoc of "CollatingIterator" wrt the used "Comparator" and throw a NullPointerException in "CollatingIterator#least" if no comparator is set. Thanks to Michael Krkoska. o [COLLECTIONS-330] "LRUMap#keySet()#remove(Object)" will not throw a "ConcurrentModificationException" anymore. Thanks to Joerg Schaible. o [COLLECTIONS-328] Improved performance of "ListUtils#intersection(List, List)". Thanks to Thomas Rogan, Jilles van Gurp. o [COLLECTIONS-323] Changed behavior of "CaseInsensitiveMap" constructor to be compliant with "HashMap" in case the initial capacity is set to zero. Thanks to Maarten Brak. o [COLLECTIONS-320] Improved performance of "StaticBucketMap#putAll(Map)" by iterating over the entry set. Thanks to sebb. o [COLLECTIONS-319] Avoid redundant null check in "IteratorUtils#getIterator(Object)". Thanks to sebb. o [COLLECTIONS-317] Use a private method to populate the object in "AbstractHashedMap(Map)". Thanks to sebb. o [COLLECTIONS-316] Fixed javadoc of "LRUMap" wrt to the maxSize parameter of the constructor. Thanks to ori. o [COLLECTIONS-312] Use of final keyword where applicable, minor performance improvements by properly initializing the capacity of newly created collections when known in advance. Thanks to Peter Lawrey, Gary Gregory. o [COLLECTIONS-307] "SetUniqueList#subList()#contains(Object)" will now correctly check the subList rather than the parent list. Thanks to Christian Semrau. o [COLLECTIONS-304] "SetUniqueList#set(int, Object)" will now correctly enforce the uniqueness constraint. Thanks to Rafał Figas,Bjorn Townsend. o [COLLECTIONS-303] Improved javadoc for "Unmodifiable*" classes wrt behavior when the users tries to modify the collection. Thanks to Emmanuel Bourg. o [COLLECTIONS-294] "CaseInsensitiveMap" will now convert input strings to lower-case in a locale-independant manner. Thanks to Benjamin Bentmann. o [COLLECTIONS-256] Fixed javadoc for "ListUtils#transformedList(List)" to clarify that existing objects in the list are not transformed. +COLLECTIONS-288] Thanks to Paul Benedict. o [COLLECTIONS-266] "MultiKey" will now be correctly serialized/de-serialized. Thanks to Joerg Schaible. o [COLLECTIONS-262] Fixed javadoc for methods "firstKey()" and "lastKey()" in class "AbstractLinkedMap". Thanks to Lisen Mu. o [COLLECTIONS-261] "Flat3Map#remove(Object)" will now return the correct value mapped to the removed key if the size of the map is less or equal 3. Thanks to ori. o [COLLECTIONS-255] Removed unused variables in "TreeBidiMap". Thanks to Henri Yandell. o [COLLECTIONS-249] "SetUniqueList.addAll(int, Collection)" now correctly add the collection at the provided index. Thanks to Joe Kelly. o [COLLECTIONS-232] Fixed several unit tests which were using parameters to "assertEquals(...)" in wrong order. Thanks to Mark Hindess. o [COLLECTIONS-228] "MultiValueMap#put(Object, Object)" and "MultiValueMap#putAll(Object, Collection)" now correctly return if the map has changed by this operation. o [COLLECTIONS-219] "CollectionUtils#removeAll" wrongly called "ListUtils#retainAll". Thanks to Tom Leccese. o [COLLECTIONS-217] Calling "setValue(Object)" on any Entry returned by a "Flat3Map" will now correctly set the value for the current entry. Thanks to Matt Bishop. o [COLLECTIONS-216] "MultiKey#toString()" will now use "Arrays#toString(List)". Thanks to Hendrik Maryns. For complete information on Commons Collections, including instructions on how to submit bug reports, patches, or suggestions for improvement, see the Apache Commons Collections website: http://commons.apache.org/proper/commons-collections/ commons-collections4-4.0-src/LICENSE.txt100664 26136 12243235515 16067 0ustartntn 0 0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS 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. commons-collections4-4.0-src/DEVELOPERS-GUIDE.html100664 12076 12243235515 17433 0ustartntn 0 0 Developers guide for Apache Commons "Collections" Package

The Apache Commons Collections Package

Developers Guide

$Id: DEVELOPERS-GUIDE.html 1353152 2012-06-23 15:49:16Z tn $
[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:

3. COLLECTION IMPLEMENTATIONS

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

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:

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:

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

commons-collections4-4.0-src/src/ 40755 0 0 0 12243235517 14042 5ustar 0 0 commons-collections4-4.0-src/src/site/ 40775 0 12243235517 15654 5ustartntn 0 0 commons-collections4-4.0-src/src/site/resources/ 40775 0 12243235517 17666 5ustartntn 0 0 commons-collections4-4.0-src/src/site/resources/images/ 40775 0 12243235517 21133 5ustartntn 0 0 commons-collections4-4.0-src/src/site/xdoc/ 40775 0 12243235517 16611 5ustartntn 0 0 commons-collections4-4.0-src/src/media/ 40775 0 12243235515 15765 5ustartntn 0 0 commons-collections4-4.0-src/src/test/ 40775 0 12243235515 15665 5ustartntn 0 0 commons-collections4-4.0-src/src/test/resources/ 40775 0 12243235515 17677 5ustartntn 0 0 commons-collections4-4.0-src/src/test/resources/data/ 40775 0 12243235515 20610 5ustartntn 0 0 commons-collections4-4.0-src/src/test/resources/data/test/ 40775 0 12243235515 21567 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/ 40775 0 12243235515 16606 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/ 40775 0 12243235515 17375 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/ 40775 0 12243235515 20616 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/ 40775 0 12243235515 22271 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/ 40775 0 12243235516 24674 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/ 40775 0 12243235516 26521 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/ 40775 0 12243235516 25425 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/ 40775 0 12243235516 25451 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/ 40775 0 12243235516 26301 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/ 40775 0 12243235516 25647 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/ 40775 0 12243235516 27226 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/splitmap/ 40775 0 12243235516 26525 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/ 40775 0 12243235516 26020 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/sequence/ 40775 0 12243235516 26504 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/trie/ 40775 0 12243235516 25637 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/ 40775 0 12243235516 27027 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ 40775 0 12243235516 26710 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/ 40775 0 12243235516 25467 5ustartntn 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/ 40775 0 12243235516 26537 5ustartntn 0 0 commons-collections4-4.0-src/src/main/ 40775 0 12243235516 15633 5ustartntn 0 0 commons-collections4-4.0-src/src/main/assembly/ 40775 0 12243235516 17452 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/ 40775 0 12243235516 16554 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/ 40775 0 12243235516 17343 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/ 40775 0 12243235516 20564 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/ 40775 0 12243235516 22237 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/ 40775 0 12243235517 24642 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/ 40775 0 12243235516 26466 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/ 40775 0 12243235516 25372 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/ 40775 0 12243235516 25416 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/ 40775 0 12243235516 26246 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/ 40775 0 12243235516 25614 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/ 40775 0 12243235516 27173 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/splitmap/ 40775 0 12243235516 26472 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/ 40775 0 12243235516 25765 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/ 40775 0 12243235516 26451 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/ 40775 0 12243235516 25604 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/analyzer/ 40775 0 12243235516 27431 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/ 40775 0 12243235516 26774 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ 40775 0 12243235516 26655 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/ 40775 0 12243235516 25434 5ustartntn 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ 40775 0 12243235517 26505 5ustartntn 0 0 commons-collections4-4.0-src/src/conf/ 40775 0 12243235517 15635 5ustartntn 0 0 commons-collections4-4.0-src/src/changes/ 40775 0 12243235517 16320 5ustartntn 0 0 commons-collections4-4.0-src/src/site/resources/images/logo.png100664 35137 12243235517 22727 0ustartntn 0 0 PNG  IHDR,d< sRGBbKGD pHYs  tIME 9I!iTXtCommentCreated with The GIMPm IDATxyTG?~n $,8I&'FTpI4LbT3IL$:1h4K\\5&:E,j]?UO=Mh&o{N{nݺuˋ1 2g@dA`dAeAeAdAdXdXdA`dAeAeAdAdXdXdAd[@xyy6F;Ckھ??//~ ѣG!77jBLL Āj̒mMŐ#ۈҺ[ӎflxx}rrss8V+(ۖΆ<())iuYws W*fLL p~0Ɣml68z0״l[+OFe&%%E)+i'77rrr`Ȑ!-l#kJJִu1!q_{5HOOo!edd0'))]t566&t:b.6ϟQV+g577{֭[YJJ kp&̎9bbbtێb/^dml+6|?MMMBݶ4(..fSNu;ze=\(̗_~)%^=zM:U{VVs8p+W)S233YCCFQZZ ,99EGG ߱?ˠ̀+ɓZV]];k׳ZТgggٳYHH 6:]*))aHƍYMM eG nݺjjjXCC;|G@B}eiii^SSjjj؅ %q={6}6t0aPNJJJGGGM6:VSSn߾֭["##5m%&&rQzvv62d\oذUWWC)eEYnfpSjef\Fo߾<Wuu5x ŋݼy]vUTTp0Yݼy2+##C(ɪmv6p@M; ֭[v\.KKKc)))zjVXX"""8 6uֱ_~YYnƌ[-99eff 6>?떽u@+&&Vee%[z57**͙3?ڵk|qA+533_]V9luu5khhU:yqKJJb555֭[묪Jʕ+5m+UV:CBBؤI>xv;~:h6KAmUUU7n C`eZYmm-y&bό3PVVƮ]dmW7nJMl,>>^րXUU}FНN'kjjbsՔc؞={XUUW.l6;zba~!omUU+//gȑ#bh^rvvMV__/dEEEiڍe򗿰SNk׮boܘ1c͞=[8ߥիlʲŬUWW+DVneii)[t 9>6o 555 s;P6?/^}ªU ((crtfСTWWCaa0}All,,_:vȿ N\.t\.|WBh s|v;/[^^#GAy ??`ل___hllfwp-8y$/[]] '8đwynjjj`ܹ0qDر#;rA.]49N}YAF}||xDžsb2BBBo .@jj*e$|pS֐!CϩЩS'~~~_ """4uACC; {p₀ʕ+5m;PWW@!uѽ{w={6444p f2l6e}>>QQQ%%% )S੧p8œbf5e駟z^3<<\(WQQc6c!UBB<\fʼYfAPP}૯u455sɓ'SO=HW0iœ477cIDž1x86___*z*% СCݻ#+}:t?98 oU|AL&m\Q+:XV~<,X |766V///Ae^àA4mΚ5K}:w˗/sk1SBykڴId0J~n19Fza'^?pQ6mn2xga˖-BAw~;Zdg~OWݻBK$:$<]4TT-HJDJΝ;bz1m_z{{Æ 43.\‚JJJZbٓMyy^.^4V9___vM:T2-,oooHIIk~-[F#F? .a94SRR`ժUBgϞSj9;;cHHݻz!~ٖ%*%@[[>֐,okҭ<裰~MQFAIIʦеkBllpὼc9vXSXii)n5d^&66F Z"99Y$ի_~BN*dnJJ ޽[>p<d(**₞ ?8 6 ~RgA@@&/(~BaՋb)VTT?O˟ Mٳg궋?2!deei@R^ك`` <}t =oѣG"tnl6Z~zFZtRѓQJO>xXZ1x>Ae˄؆OCbx ҥKK/ U4n87n Ls i;tRXnTTTm+::̙BB:r}wRضm.=zo ~~~p ˃ݲ}kxꩧرcn> ХKڵ+:u ?۶mӵu Æ :l;v6@߾}!::x ڵ+zT[nпxG'7<khh:8r̚5 Μ9㖗V&M&L!677skCNcǎ ּj|榢ϩ ȩ)66᷿-dÇCII X,p:w^@GFFClV+L8?Cmm-444̝B,C]]|9$=z +]QhvIjc[\P1ĉPXXgΜ ** BBB3WdlFsP&L'|`ɒ%|I٨(:u*ҥK[U6::z +VG.G/L&裏C#i\>>>0qDx'yY߫v'MO<`bvF˫W©SB޴(~Lib=___XxL/E}h"a|(Ǐ'|ʱcb<uuup8ɓ?3gn7XVDhnniSSv H7s%+ #64 " ӜF`t^Rŗ(PWW\1C#ZXrt-ɺ:MYblrEQ4*%* emҲ8VL]M>#h!/邢J<'o4 LJ}ѠNynpNq7q>bJ$///p:|N(Mꃑj=z<eLJ2x ۡax,,;-N4x$G#gOb,Pp!uQ1 oooMt9ҕۤ%bhlrH .\}lZ偾>CSo9T9rHTn!hRwYD~K&*' i[sa;UJٲkIc[~!GMW^zJ*iW~AeSsҢS*dzb۪vU4*^GF5> >`2o2qxm2v|Zrq9FIXFOh1^vOr8 ʩiyU^&:~WK-y, NzUKۓ4в"m%Ny)S|sQ򄏴^U<-%4Ztk+ }`cs9 .[fb\dAӋHV;kQ+K0ZJ#Ɲ.3Ш_*Mjvwa]z:>-;>vB_俩d=,=)ޝfGhijm[zvP|)+[yzWVo.< ]C~CoЫ5Uڹ T.NDڛܥ7n<^m^nn.cx4͛ 便/,AQQoWO<A {;(ȽTƟl{7tPS^77o>o߮ N7,&wO9гn= xc BΆ#G-[4Ct@NMM_g*Kd///xW>;ɤkAhZ0d3iaaa t:!))IX'&ύN"^`dddhW5͸XM1MMM<1G7`M9z]旐REgYe j (f7 {nMUvw , !!!ש]ّ3J`2,,ܐjkGIL p Lxx石Spc|ww#qа~0wtWAAA<|%`ted,wf4 b*[=獞zrInM{l9۳gOR6 rss9# V%KC?'bQJHHPfŐ3 P +884 G %%%ޝFw??c`Zֹ`e>׌1HHHPuر4bH/~N+^o4Ѕ~aM1mGNw'۶mV˻Xrss!##mVbbb` >LsUn.(yyyřɓ'ɓ~^9F-꿊PQYUrfgg!RRRWcbb ++KP0qPh Ç׭s۶ms_uxp (--Ǐf(HHHP^999HȎ|>|q | ttt4>|XqBxWyT<.tWf]G,&&}W9p8KJJb544Fp8XSSknnft2ϟM2E%''ߍOIDATf/^lɓ'2v;z*p;<;{,;|XXV\xωꓚjkkYmm-й߲e ~JJ0ߗ.]bIIIuS2.* -[ Df}`:t԰V[["6oެֲj^/ *ꍈ`eeeʕ+cϟgΝc_5x"+..fvB ;w;2۷/s 'o1~vjœ9s2p@|_۹s'ހ}Z\.IIC<|||{۷o^x9Qz_CBBW^p8`̘1+W///\P#9'' xOQ>J5,^ڗб c;@XXWێ6M(8q.6# N hTN|gOk_9nXV0qD ;}t7n,Ra~{=«"`` 88ÅDr}Z<|f. F(|`sU&wܠ7p_`ŋ9P!7wn ,^4/\a|G8p///$W_忧rš Icp~̆ 'tЯ_?u 8#Px 41]KI~ZWrhXXB3]eee6lؠy r ˗/[lH1]B0nE ++mhh&*~dK_۷B%/*]vɓ'a֭ب (((łf`Dy|x7a'voTej54jI&iӊ0a*/ʁDCA8pB}W*"", 8`ə3g c4ij|Q3g΄UVq_ҥK!44TPQW^-9k,ֲ9}%04\#((zG**;Zo2`aիW s?qD圴7::l:u&=Ǔ'OByy9~~}ҝN'CddXwd}rj!O.}N. Of٤ ӂ VVV3g^Q<ם%U;_v;XBhg/_V^=n8x뭷m^ZؖM>ePB_:Vj)]L&طox3/Z_,:x?~<nݺ >AǓ'O OZ傏>u&4i| Z<<7 )| B:UIcw^VuDlD;@WjwGUFs(b[7 ;vݻw F qqq,]`߾}RPe}[H$TtO~zϞ=tR7""Ͻ"j K-! @'OF t|uv(ڵkaرߟ{9ذa 2jN$G GI^3]d,2d?JXX߲Q+t©S ݋z*}gϞpBٳ'X,///ASɯiӭܖleDDD(O=嗠0PaΩˀV9~_+//[IVXX(Xmzo(Dصkv7ơ7Ooh{Xd]b/PGd{T9]}].dE>8]. VJhhΝJfҠȱO1hnn!qS򂊊 j9y*ph@n O:%(/[t@RZϭ/%رc! @k dkG~o0vXa=pr_$3-]7Gt햃 eŽ+5 i.wPyy_ 'xYeN俢+6G1 4@n]9:f3f0L^z gT9yê g}&1zh5 (@,Dy-멀duə66VJӒ2VUV`ʴn+Չ%RPU^ UU}r,}ݺus*gϞUokȑ=t\0uT۷/w{yyi5QYY իW e6Gpcr bsNxꩧt0;vlw}ԩs .ωw_///$ 66Vi))[d M4U桏 [^*zݑX@VUZk֬}CBBcv,tU1ckɀ (A~׿Wv˅-F\.ddGzWZ֭Cdd$YF8Ce_ `ذak)˽T۵+8 @˾Ai5k`ʔ)-$J˗/|!۰SN 'OVӥf#bM/._v Ν 탈XnO+ ( BeeeгgOHOOIxz_|Q8 r"M&d (z+VGyD>F0`ǎ0f|= O?A{>E+,ZHӧ8_|Qy}s[Z<?~ h+'O,D^rEsqa6:wGFF<}|?K٬5rqɁ%KhܑƍǏG}b+:r۷oK:{ PQQO8x!&&E߾cPP y^_F)ܤGBA`iӠSN RRXrȑ#!.."##VPX?^zO [3fc=&GU߱co&Ӈ.aTt___(,,.a믿< {:{\oz.]%KhR10Xp!tԉ=[`ZaϞ=PPP7K/qࡇVʈ?2`a2py, saBً  ??_ȥEDF{^z<خnuߟGJ\.ի@Kɖ:Np8u , W:?*iGpXn׮]Qyll,;>t:466 օeeecq8@`9 Xh-CAA_,_9lF>CmAAl6a (t;wDFFm- BBBI2b]Ժ%v$d>22*n7NMkA9e KnC(IhJi9.1QΑ`2P DB>b_֎naC\RsI`s  @KUH9뢠//*2!ۨSe"6|o - (l NSDrhH 2 ȁzMQe/44<=Ȑ {9t n.,SĴ*']EAu#c{̝CUѫW]XZz`EAG%=&(ȩPnW`x!**`AT,*rzzsXUs947So2d@.0:˪2"= b FǠZ d+]E#:Tv(hYU`%Т+*eޝ0YO8iy9[.*,,d#㑷T ҭ*\weI6Vu]>| YVvy;OAX2y.inW[M^h(A/@te`evPQQСCiM/S@e)*VwYP)Bt,QYizjFUmSMo)`!hNtOϧ&NWYJ2,>٭' i&۷i&򂂂k´i`<]aaВ }BZnTB-Q 5]IU 0TeTUTUyR͹7>6Y5`M Z@JO+d '<,9O +(RsAd%kOT|&I1cѣĉk.º[CY)B2ի'"**sP+}Kw'zdkXeѪry2'2VYUw_fC sbb"t ?-XuR*sc}.]x'gݴ46 zcGϧNcNdy8r;w_DN3p-%[ί?E0G"OE%-ͻ5뗻v<*knOKsQA{%Gٓ~x,'uKUVadz'mx b2ނh7Xd)2adA`dAeAeAdAdXdXdAs6i5IENDB`commons-collections4-4.0-src/src/site/xdoc/issue-tracking.xml100664 13327 12243235517 22406 0ustartntn 0 0 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:

commons-collections4-4.0-src/src/site/xdoc/release_3_2.xml100664 20130 12243235517 21527 0ustartntn 0 0 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]
commons-collections4-4.0-src/src/site/xdoc/mail-lists.xml100664 22350 12243235517 21530 0ustartntn 0 0 Commons Collections Mailing Lists Commons Documentation Team

Commons Collections shares mailing lists with all the other Commons Components. To make it easier for people to only read messages related to components they are interested in, the convention in Commons is to prefix the subject line of messages with the component's name, for example:

  • [collections] Problem with the ...

Questions related to the usage of Commons Collections should be posted to the User List.
The Developer List is for questions and discussion related to the development of Commons Collections.
Please do not cross-post; developers are also subscribed to the user list.

Note: please don't send patches or attachments to any of the mailing lists. Patches are best handled via the Issue Tracking system. Otherwise, please upload the file to a public server and include the URL in the mail.

Please prefix the subject line of any messages for Commons Collections with [collections] - thanks!

Name Subscribe Unsubscribe Post Archive Other Archives
Commons User List

Questions on using Commons Collections.

Subscribe Unsubscribe Post mail-archives.apache.org markmail.org
www.mail-archive.com
news.gmane.org
Commons Developer List

Discussion of development of Commons Collections.

Subscribe Unsubscribe Post mail-archives.apache.org markmail.org
www.mail-archive.com
news.gmane.org
Commons Issues List

Only for e-mails automatically generated by the issue tracking system.

Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
www.mail-archive.com
Commons Commits List

Only for e-mails automatically generated by the source control sytem.

Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
www.mail-archive.com

Other mailing lists which you may find useful include:

Name Subscribe Unsubscribe Post Archive Other Archives
Apache Announce List

General announcements of Apache project releases.

Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
old.nabble.com
www.mail-archive.com
news.gmane.org
commons-collections4-4.0-src/src/site/xdoc/pick.xml100664 31231 12243235517 20376 0ustartntn 0 0 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'.

commons-collections4-4.0-src/src/site/xdoc/compatibility.xml100664 7500 12243235517 22303 0ustartntn 0 0 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 further 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 compatibility 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.

commons-collections4-4.0-src/src/site/xdoc/history.xml100664 11046 12243235517 21153 0ustartntn 0 0 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.

Collections 4.0 represented a major revamp of collections by supporting new language features introduced with Java 1.5, mainly support for generics.

New interfaces Put, Get and Trie were added, whereas the Buffer interface has been replaced by java.util.Queue. Also added were several new Iterators as well as an implementation of a Patricia Trie.

commons-collections4-4.0-src/src/site/xdoc/release_4_0.xml100664 60414 12243235517 21537 0ustartntn 0 0 Release notes for v4.0 Commons Documentation Team

These are the release notes for Commons Collections v4.0:


Commons collections is a project to develop and maintain collection classes based on and inspired by the JDK collection framework. This version uses the generics features of Java 5 and is not compatible with earlier JDK versions.

The process of generifying an API is complex. For commons-collections, we have chosen to break the API in various ways. The aim behind this is to provide an API design that better suits generics. We have also removed all deprecated classes and fixed oddities in the previous API that we couldn't fix due to backwards compatibility restrictions.

As such, this release can not be considered to be a simple, drop-in, replacement for commons-collections. To help with the migration to this new version, the package has changed to "org.apache.commons.collections4", thus it is possible to have both commons-collections versions in the classpath.

These release notes will try to guide you in the process of upgrading, however you should remember that this is a new API based on the original, so some concepts have changed.


Compatibility

  • Java 5 or later is required
  • This release is not source or binary compatible with previous releases of Commons Collections. This includes releases from the 3.x branch as well as preceding alpha releases for 4.0 (see details of changes below)

Major changes since 3.2.1

  • Use of generics and other language features introduced in Java 5 (varargs, Iterable)
  • Removed deprecated classes / methods and features which are now supported by the JDK
  • Replaced Buffer interface with java.util.Queue
  • Added concept of split maps with respective interfaces Put / Get (see also package splitmap)
  • Added new Trie interface together with an implementation of a Patricia Trie

Removed Classes

  • Removed unused class "AbstractUntypedCollectionDecorator"
  • Removed "Buffer" interface and all its implementations and related classes. Replaced by "java.util.Queue", see also section [New classes]
    • PriorityBuffer: use either java.util.PriorityQueue or java.util.concurrent.PriorityBlockingQueue
    • SynchronizedBuffer: use the corresponding *BlockingQueue classes in java.util.concurrent
    • BoundedBuffer: use either ArrayBlockingBuffer(capacity) or LinkedBlockingBuffer(capacity) in java.util.concurrent
    • UnboundedFifoBuffer: use either java.util.LinkedList or java.util.concurrent.LinkedBlockingBuffer
  • Removed features now supported by the JDK or other Apache Commons libraries
    • FastArrayList: use java.util.concurrent.CopyOnWriteArrayList
    • FastHashMap: use java.util.concurrent.ConcurrentHashMap, but beware of null keys and values
    • FastTreeSet: no direct replacement, use ConcurrentHashMap or a synchronized TreeMap
    • IdentityMap: use java.util.IdentityHashMap
    • ExtendedProperties: use commons-configuration
    • Synchronized[List,Set,SortedSet]: use java.util.Collections.synchronized*()
    • Typed* decorators: use generics for type safety, or java.util.Collections.checked*()
    • [List,Set,Map]Utils.EMPTY_*: use the corresponding fields in java.util.Collections
  • Removed deprecated collection classes and methods

New Classes

  • CollectionSortedBag - decorates a SortedBag to make it comply with the Collection contract.
  • CollectionBag - decorates another Bag to make it comply with the Collection contract.
  • PushbackIterator - supports pushback of elements during iteration. Thanks to Andy Seaborne, Claude Warren.
  • PeekingIterator - supports one-element lookahead during iteration. Thanks to Andy Seaborne, Claude Warren.
  • CircularFifoQueue - analogous class to CircularFifoBuffer for the Queue interface
  • PredicatedQueue - analogous class to PredicatedBuffer
  • TransformedQueue - analogous class to TransformedBuffer
  • UnmodifiableQueue - analogous class to UnmodifiableBuffer
  • QueueUtils - analogous class to BufferUtils
  • PermutationIterator - generates unordered permutations of a collection. Thanks to Benoit Corne.
  • SequencesComparator - an implementation of Eugene Myers difference algorithm in package o.a.c.c.sequence. Thanks to Jordane Sarda.
  • LazyIteratorChain - a variant of IteratorChain which supports lazy initialization. Thanks to Jeff Rodriguez.
  • NodeListIterator - supports iteration over a org.w3c.dom.NodeList. Thanks to Thomas Vahrst.
  • CatchAndRethrowClosure - re-throws any checked exception as unchecked "FunctorException". Thanks to David J. M. Karlsen.
  • IndexedCollection - collection decorator which provides a map-like view on an existing collection. Thanks to Stephen Kestle.
  • DualLinkedHashBidiMap - bidi map implementation using LinkedHashMap instances. Thanks to Nathan Blomquist.
  • Equator - interface for testing object equality.
  • PassiveExpiringMap - map decorator which passively expires entries. Thanks to Elifarley Callado Coelho.
  • PatriciaTrie - PATRICIA trie implementation for the new Trie interface, together with Unmodifiable and Synchronized decorators. Thanks to Sam Berlin and Roger Kapsi.
  • ComparatorPredicate - predicate to compare objects against a fixed instance. Thanks to Rune Peter Bjørnstad.
  • Put / Get - interfaces for split maps
  • SplitMapUtils / splitmap.TransformedSplitMap - utilities and implementation for split maps

Enhancements

  • Added CollectionsUtils#matchesAll(Iterable, Predicate) to test if all elements of a collection match a given predicate.
  • ListUtils#longestCommonSubsequence(...) to get the longest common subsequence of arbitrary lists or CharSequences.
  • CollectionUtils#forAllButLastDo(Collection, Closure) and forAllButLastDo(Iterator, Closure). Thanks to J. Moldawski.
  • CollectionUtils#isEqualCollection(Collection, Collection, Equator). Thanks to Matt Lachman.
  • *Utils#emptyIfNull(*) methods in classes CollectionUtils, ListUtils, SetUtils and MapUtils. Thanks to Arman Sharif.
  • CollectionUtils#containsAll(Collection, Collection) with guaranteed runtime complexity of O(n + m) and space complexity of O(n). This method may yield much better performance than Collection.containsAll(Collection) depending on the use-case and type of collection used. Thanks to Adrian Nistor, Mert Guldur.
  • CollectionUtils#permutations(Collection) to generate all permutations of a collection. Thanks to Benoit Corne.
  • ListUtils#select() and ListUtils#selectRejected() methods. Thanks to Adam Dyga.
  • ListUtils#partition() to split a List into consecutive sublists. Thanks to Chris Shayan.
  • CollectionUtils#forAllDo(Iterator, Closure). Thanks to Adrian Cumiskey.
  • ListUtils#defaultIfNull(List, List). Thanks to Ivan Hristov.
  • CollectionUtils#filterInverse(Iterable, Predicate). Thanks to Jean-Noel Rouvignac.
  • CollectionUtils#subtract(Iterable, Iterable, Predicate). Thanks to Chris Shayan.
  • CollectionUtils#collate(...) to merge two sorted Collections using the standard O(n) merge algorithm. Thanks to Julius Davies.
  • CollectionUtils#extractSingleton(Collection). Thanks to Geoffrey De Smet.
  • MapUtils#populateMap(MultiMap, ...) to support also "MultiMap" instances as input. Thanks to John Hunsley.
  • ListUtils#indexOf(List, Predicate). Thanks to Nathan Egge.
  • MapUtils#populateMap(Map, Iterable, Transformer, ...). Thanks to Dave Meikle.
  • Added new method "get(int)" to "CircularFifoQueue". Thanks to Sebb.
  • Added serialVersionUID fields for "CompositeCollection", "CompositeSet", "EmptyMapMutator", "EmptySetMutator". Thanks to sebb.
  • Added support for using custom "Equator" objects in "EqualPredicate". Thanks to Stephen Kestle.
  • Added method "CollatingIterator#getIteratorIndex()". Thanks to Fredrik Kjellberg.
  • Added serialization support for "TreeBidiMap". Thanks to Christian Gruenberg.
  • Added serialization support for "FixedOrderComparator" and "TransformingComparator". Thanks to Chaitanya Mutyala.
  • Added constructor "TransformingComparator(Transformer)". Thanks to Stephen Kestle.
  • Added method "MultiValueMap#iterator()" to return a flattened version of "entrySet().iterator()". Clarified javadoc for "entrySet()" that the returned Entry objects are unflattened, i.e. the Entry object for a given key contains all values mapped to this key. Thanks to Nils Kaiser, Alan Mehlo.
  • Added method "ListOrderedMap#putAll(int, Map)". Thanks to Vasily Ivanov.
  • Added support for resettable iterators in "IteratorIterable". Thanks to Dusan Chromy.

Changed classes / methods

  • Resolved generic parameter inconsistency for various static fields, e.g. BagUtils.EMPTY_BAG, TruePredicate.INSTANCE and many others. All accessible static fields use raw types so that they can be used directly without explicit casting. To avoid compiler warnings about unchecked conversion and/or rawtypes use the corresponding factory methods, e.g. BagUtils.emptyBag().
  • Renamed methods "V MultiKeyMap#remove(Object, Object, ...)" to "V MultiKeyMap#removeMultiKey(Object, Object, ...)" to avoid future conflicts with a default method of the Map interface in Java 8.
  • Renamed "V MultiMap#remove(K, V)" to "boolean MultiMap#removeMapping(K, V)" to avoid future conflicts with a default method of the Map interface in Java 8.
  • Refactored the test framework for Bag implementations to extend from "AbstractCollectionTest" by decorating the concrete Bag instance with a CollectionBag or CollectionSortedBag.
  • "UnmodifiableBoundedCollection" does now also implement the marker interface "Unmodifiable" similar as all other unmodifiable decorators.
  • "UnmodifiableTrie#unmodifiableTrie(Trie)" will not decorate again an already unmodifiable Trie. Also the return type has been changed to "Trie" to be consistent with other Unmodifiable decorators.
  • Moved "Equator" interface to base package for consistency.
  • Accept wildcard input where possible, e.g. in copy-constructors, Unmodifiable* decorators and iterators.
  • Narrow return type of "BidiMap#values()" to Set as the values are required to be unique.
  • Made field "collection" in class "AbstractCollectionDecorator" private and added setter "setCollection(Collection)" with scope protected to set the decorated collection during de-serialization.
  • Replaced "Collection" with "Iterable" for method arguments where applicable.
  • Changed "IteratorChain" to use internally a "Queue" instead of a "List". Iterators are removed from the queue once used and can be garbage collected after being exhausted. Additionally removed the methods "setIterator(Iterator)" and "getIterators()".
  • Removed method "setArray(Object)" in class ArrayIterator and method "setArray(Object[])" in class ObjectArrayIterator and made fields array, startIndex and endIndex final and package private.
  • Changed scope of various fields to private / package private where appropriate.
  • An iterator over a "Flat3Map#entrySet()" will now return independent Map.Entry objects that will not change anymore when the iterator progresses.
  • Several closure and transformer implementations in the functor package will now copy an array as input parameter to their constructor (e.g. ChainedClosure).
  • Change base package to "org.apache.commons.collections4".
  • The constructors for all *Utils classes are now private to prevent instantiation.
  • "CompositeSet" does not inherit from "CompositeCollection" anymore. The inner class "SetMutator" has been updated accordingly. Thanks to Michael Pradel.
  • Change maven coordinates to "org.apache.commons.commons-collections4". Thanks to Olivier Lamy.
  • Move the project structure to a standard maven layout. Thanks to Olivier Lamy.
  • TransformingComparator now supports different types for its input/output values.
  • "CollectionUtils#filter(Iterable, Predicate)" will now return whether the collection has been modified. Thanks to Jean-Noel Rouvignac.
  • "NOPClosure" is now a final class. Thanks to Goran Hacek.
  • Fields transformer and decorated in class "TransformingComparator" are now final. Thanks to sebb.
  • "SetUniqueList#subList()" will now return an unmodifiable list as changes to it may invalidate the parent list. Thanks to Christian Semrau, Thomas Vahrst.
  • Calling "CollectionUtils#sizeIsEmpty(null)" will now return true. Thanks to Benjamin Bentmann.
  • The predicate that rejected an object to be added to a "PredicatedCollection" is now contained in the respective exception message. Thanks to Chris Lewis.
  • "TreeBag" will now only accept "Comparable" objects as input when used with natural ordering. Thanks to David Saff.
  • The static factory methods have been renamed from "getInstance()" to a camel-case version of the class name, e.g. "truePredicate()" for class "TruePredicate". Thanks to Stephen Kestle.
  • "MultiValueMap" is now serializable. Thanks to Wouter de Vaal.
  • Return concrete class in static factory methods instead of base class interface (except for Unmodifiable decorators). Thanks to Torsten Curdt.
  • "CollectionUtils#size(Collection)" now returns 0 when called with null as input. Thanks to Stepan Koltsov,sebb.
  • "CollectionUtils#addAll(...)" methods now return if the collection has been changed by this operation. Thanks to Vasily Ivanov.
  • "CompositeCollection", "CompositeMap" and "CompositeSet" are now serializable. Thanks to Pal Denes.
  • The "CollectionUtils#select(Collection, Predicate, Collection)" method will now return the output collection.
  • "CollectionUtils#forAllDo(Collection, Closure)" now returns the provided closure. Thanks to Jim Cakalic.
  • Make generic versions of all classes in collections.
  • Switch Abstract*Decorator classes to expose decorated() protected method instead of the decorated collection directly. Each class overrides decorated() to add its type covariantly, thus getList()/getSet() etc. methods are removed
  • ArrayStack is now deprecated and will be removed in the next major release. It is replaced by the java.util.Deque interface available from Java 6.

Bugfixes

  • "CollectionBag" will now also respect the contract of the decorated bag in case a null argument is provided to either removeAll or retainAll.
  • Fixed collision detection/resolution when calling "CompositeSet#addComposited(...)" with more than one Set as argument.
  • Fixed conversion of timeout parameters in "PassiveExpiringMap".
  • ListOrderedMap#putAll(index, Object, Object) does not throw an exception anymore if the map contains null values. Additionally added javadoc clarification on the supported bounds for the index parameter. Thanks to Ning Chen.
  • Improved performance of "AbstractMapBag#containsAll(Collection)" by returning immediately after a difference has been found. Thanks to Adrian Nistor.
  • Added additional clarification to javadoc of interface "Put" wrt return type of "put(Object, Object)" method. Thanks to Matt Benson, sebb.
  • Tree traversal with a TreeListIterator will not be affected anymore by the removal of an element directly after a call to previous(). Thanks to Jeffrey Barnes.
  • Adapt and/or ignore several unit tests when run on a IBM J9 VM (specification version 1.6.0) due to a faulty "java.util.TreeMap" implementation.
  • SetUniqueList.set(int, E) now works correctly if the object to be inserted is already placed at the given position. Thanks to Thomas Vahrst, John Vasileff.
  • MultiKeyMap.clone() now correctly calls super.clone(). Thanks to Thomas Vahrst.
  • Improve performance of "TreeList#addAll" and "TreeList(Collection)" by converting the input collection into an AVL tree and efficiently merge it into the existing tree. Thanks to Jeffrey Barnes.
  • Fixed performance issue in "SetUniqueList#retainAll" method for large collections. Thanks to Mert Guldur.
  • Fixed performance issue in "ListOrderedSet#retainAll" method for large collections. Thanks to Adrian Nistor.
  • Improved performance of "ListOrderedMap#remove(Object)" method. Thanks to Adrian Nistor.
  • Update javadoc for "ListUtils#lazyList()" and "ListUtils#fixedSizeList()". Thanks to Benedikt Ritter.
  • Added clarifying javadoc wrt runtime complexity of "AbstractDualBidiMap#retainAll". Thanks to Adrian Nistor.
  • Added clarifying javadoc wrt runtime complexity of "AbstractLinkedList#retainAll". Thanks to Adrian Nistor.
  • Added clarifying javadoc wrt runtime complexity of "AbstractLinkedList#removeAll". Thanks to Adrian Nistor.
  • Fixed several compilation issues with older Java 1.6 compilers.
  • Improved performance of "removeAll()" method for sets returned by "DualHashBidiMap#entrySet()". Thanks to Adrian Nistor.
  • Improved performance of "CollectionUtils#subtract" methods. Thanks to Adrian Nistor.
  • Fixed possible "IndexOutOfBoundsException" in "ListOrderedMap#putAll". Thanks to Adrian Nistor.
  • Improved performance of "SetUniqueList#addAll" method. Thanks to Adrian Nistor.
  • Improved performance of "ListOrderedSet#addAll" method. Thanks to Adrian Nistor.
  • Improved performance of "SetUniqueList#removeAll". Thanks to Adrian Nistor.
  • Improved performance of "ListOrderedSet#remove(Object)" in case the object is not contained in the Set. Thanks to Adrian Nistor.
  • Improved performance of "ListUtils#subtract" method. Thanks to Adrian Nistor.
  • Added missing null check in "CollectionUtils#addIgnoreNull(Collection, Object)". Thanks to Shin Hwei Tan.
  • Fixed javadoc for "MapUtils#toProperties(Map)". Thanks to Shin Hwei Tan.
  • Clarified javadoc for "TransformerUtils#mapTransformer" for null input. Thanks to Shin Hwei Tan.
  • Clarified javadoc for "FactoryUtils#prototypeFactory" for null input. Thanks to Shin Hwei Tan.
  • Fixed inconsistent javadoc for "MapUtils#synchronizedMap(Map)". Thanks to Shin Hwei Tan.
  • Fixed infinite loop when calling "UnmodifiableBoundedCollection#unmodifiableBoundedCollection()". Thanks to Dave Brosius.
  • Fixed javadoc for several methods wrt expected NullPointerExceptions. Thanks to Shin Hwei Tan.
  • "DualTreeBidiMap" now uses the correct comparator for the reverse map during de-serialization.
  • "TransformedMap" in the package "splitmap" can now be serialized.
  • "FilterListIterator#hasNext" does not throw a NullPointerException anymore to comply to the Java iterator specification. Thanks to Sai Zhang.
  • "ListUtils#intersection(List, List)" will now also work correctly if there are duplicate elements in the provided lists. Thanks to Mark Shead.
  • "AbstractCollectionDecorator" will now use internally "decorated()" to access the decorated collection. Thanks to Adam Gent.
  • Removed debug output in "MapUtils#getNumber(Map)". Thanks to Michael Akerman.
  • Fixed javadoc for all "transformedXXX(XXX)" methods in the respective Utils classes to clarify that existing objects in the list are not transformed. Thanks to Paul Benedict.
  • Singleton classes in package "functors" are now correctly de-serialized. Thanks to Goran Hacek.
  • Removed broken methods "equals(Object)" and "hashCode()" in class "NOPClosure". Thanks to Goran Hacek.
  • Simplified exceptions as the cause is available from the parent. Thanks to sebb.
  • Fixed cache assignment for "TreeBidiMap#entrySet". Thanks to sebb.
  • Synchronized access to lock in "StaticBucketMap#size()". Thanks to sebb.
  • Added clarification to javadoc of "ListOrderedMap" that "IdentityMap" and "CaseInsensitiveMap" are not supported. Thanks to Tom Parker.
  • Improve javadoc of "CollatingIterator" wrt the used "Comparator" and throw a NullPointerException in "CollatingIterator#least" if no comparator is set. Thanks to Michael Krkoska.
  • "LRUMap#keySet()#remove(Object)" will not throw a "ConcurrentModificationException" anymore. Thanks to Joerg Schaible.
  • Improved performance of "ListUtils#intersection(List, List)". Thanks to Thomas Rogan, Jilles van Gurp.
  • Changed behavior of "CaseInsensitiveMap" constructor to be compliant with "HashMap" in case the initial capacity is set to zero. Thanks to Maarten Brak.
  • Improved performance of "StaticBucketMap#putAll(Map)" by iterating over the entry set. Thanks to sebb.
  • Avoid redundant null check in "IteratorUtils#getIterator(Object)". Thanks to sebb.
  • Use a private method to populate the object in "AbstractHashedMap(Map)". Thanks to sebb.
  • Fixed javadoc of "LRUMap" wrt to the maxSize parameter of the constructor. Thanks to ori.
  • Use of final keyword where applicable, minor performance improvements by properly initializing the capacity of newly created collections when known in advance. Thanks to Peter Lawrey, Gary Gregory.
  • "SetUniqueList#subList()#contains(Object)" will now correctly check the subList rather than the parent list. Thanks to Christian Semrau.
  • "SetUniqueList#set(int, Object)" will now correctly enforce the uniqueness constraint. Thanks to Rafał Figas,Bjorn Townsend.
  • Improved javadoc for "Unmodifiable*" classes wrt behavior when the users tries to modify the collection. Thanks to Emmanuel Bourg.
  • "CaseInsensitiveMap" will now convert input strings to lower-case in a locale-independant manner. Thanks to Benjamin Bentmann.
  • Fixed javadoc for "ListUtils#transformedList(List)" to clarify that existing objects in the list are not transformed. Thanks to Paul Benedict.
  • "MultiKey" will now be correctly serialized/de-serialized. Thanks to Joerg Schaible.
  • Fixed javadoc for methods "firstKey()" and "lastKey()" in class "AbstractLinkedMap". Thanks to Lisen Mu.
  • "Flat3Map#remove(Object)" will now return the correct value mapped to the removed key if the size of the map is less or equal 3. Thanks to ori.
  • Removed unused variables in "TreeBidiMap". Thanks to Henri Yandell.
  • "SetUniqueList.addAll(int, Collection)" now correctly add the collection at the provided index. Thanks to Joe Kelly.
  • Fixed several unit tests which were using parameters to "assertEquals(...)" in wrong order. Thanks to Mark Hindess.
  • "MultiValueMap#put(Object, Object)" and "MultiValueMap#putAll(Object, Collection)" now correctly return if the map has changed by this operation.
  • "CollectionUtils#removeAll" wrongly called "ListUtils#retainAll". Thanks to Tom Leccese.
  • Calling "setValue(Object)" on any Entry returned by a "Flat3Map" will now correctly set the value for the current entry. Thanks to Matt Bishop.
  • "MultiKey#toString()" will now use "Arrays#toString(List)". Thanks to Hendrik Maryns.

For complete information on all changes for this release, please refer to the Changelog.

commons-collections4-4.0-src/src/site/xdoc/release_3_2_1.xml100664 3173 12243235517 21737 0ustartntn 0 0 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.

commons-collections4-4.0-src/src/site/xdoc/proposal.xml100664 7512 12243235517 21274 0ustartntn 0 0 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
commons-collections4-4.0-src/src/site/xdoc/userguide.xml100664 13011 12243235517 21440 0ustartntn 0 0 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 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.

commons-collections4-4.0-src/src/site/xdoc/download_collections.xml100664 21740 12243235517 23661 0ustartntn 0 0 Download Apache 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.

commons-collections4-4.0-bin.tar.gz md5 pgp
commons-collections4-4.0-bin.zip md5 pgp
commons-collections4-4.0-src.tar.gz md5 pgp
commons-collections4-4.0-src.zip md5 pgp
commons-collections-3.2.1-bin.tar.gz md5 pgp
commons-collections-3.2.1-bin.zip md5 pgp
commons-collections-3.2.1-src.tar.gz md5 pgp
commons-collections-3.2.1-src.zip md5 pgp

Older releases can be obtained from the archives.

commons-collections4-4.0-src/src/site/xdoc/index.xml100664 10467 12243235517 20567 0ustartntn 0 0 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
  • 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
  • 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
  • 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 v4.0 - Download now!
It is built for Java 1.5+ and 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.

commons-collections4-4.0-src/src/site/xdoc/building.xml100664 4664 12243235517 21237 0ustartntn 0 0 Building Commons Documentation Team

Commons Collections uses Maven 2 as its primary build system, however an Ant build is also available.

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 site 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 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
commons-collections4-4.0-src/src/site/site.xml100664 4035 12243235517 17441 0ustartntn 0 0 Commons Collections /images/logo.png /index.html commons-collections4-4.0-src/src/media/logo.xcf100664 61626 12243235515 17557 0ustartntn 0 0 gimp xcf file,dBBK gimp-commentCreated with The GIMPgimp-image-grid(style solid) (fgcolor (color-rgba 0.000000 0.000000 0.000000 1.000000)) (bgcolor (color-rgba 1.000000 1.000000 1.000000 1.000000)) (xspacing 10.000000) (yspacing 10.000000) (spacing-unit inches) (xoffset 0.000000) (yoffset 0.000000) (offset-unit inches) 04D a TM     Q8gimp-text-layer(text "TM") (font "Sans") (font-size 8.000000) (font-size-unit pixels) (hinting yes) (antialias yes) (language "en-us") (base-direction ltr) (color (color-rgb 0.000000 0.000000 0.000000)) (justify left) (box-mode fixed) (box-width 12.000000) (box-height 11.000000) (box-unit pixels)   #ɰ->8x88w8P8?8" Text Layer#2     Q/"" U 48U6qq1U89;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*6446&0j   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      55CD59=Bj8qU8Uq8q8q 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       D$Daa$DLUJ]   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     b,dbcrc~c,dbcccc*c6cBcNcZcf               0002K% ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/PredicatedList.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/PredicatedList.emptyCollection.version4.ob100664 710 12243235515 32005 0ustartntn 0 0 sr3org.apache.commons.collections4.list.PredicatedList;|&xr?org.apache.commons.collections4.collection.PredicatedCollectionpvL predicatet+Lorg/apache/commons/collections4/Predicate;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpw xsr6org.apache.commons.collections4.functors.TruePredicate.ՔQ&,xp././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableBag.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableBag.emptyCollection.version4.o100664 523 12243235515 31755 0ustartntn 0 0 sr3org.apache.commons.collections4.bag.UnmodifiableBagٴxr8org.apache.commons.collections4.bag.AbstractBagDecorator˴)fk7xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.HashBagujxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpw xq~x././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableList.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableList.emptyCollection.version4.100664 637 12243235515 32026 0ustartntn 0 0 sr5org.apache.commons.collections4.list.UnmodifiableList[<}xrForg.apache.commons.collections4.list.AbstractSerializableListDecorator%B){kxr:org.apache.commons.collections4.list.AbstractListDecorator>ujxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpw xq~x././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableTrie.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableTrie.fullCollection.version4.o100664 1400 12243235515 32006 0ustartntn 0 0 sr9org.apache.commons.collections4.map.UnmodifiableSortedMapPXxpsr1org.apache.commons.collections4.trie.PatriciaTrie=Ye xr9org.apache.commons.collections4.trie.AbstractPatriciaTrieG#U1Oxr8org.apache.commons.collections4.trie.AbstractBitwiseTriePݝܐԐL keyAnalyzert2Lorg/apache/commons/collections4/trie/KeyAnalyzer;xpsr?org.apache.commons.collections4.trie.analyzer.StringKeyAnalyzergr|Bxr0org.apache.commons.collections4.trie.KeyAnalyzer- xpwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~"tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxx././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/SynchronizedBag.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/SynchronizedBag.fullCollection.version4.ob100664 1437 12243235515 32031 0ustartntn 0 0 sr3org.apache.commons.collections4.bag.SynchronizedBagp2 j5xrAorg.apache.commons.collections4.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsr+org.apache.commons.collections4.bag.HashBagorg.apache.commons.collections4.collection.CompositeCollectiontV}qLalltLjava/util/List;LmutatortRLorg/apache/commons/collections4/collection/CompositeCollection$CollectionMutator;xpsrjava.util.ArrayListxaIsizexpw xpcommons-collections4-4.0-src/src/test/resources/data/test/ArrayStack.emptyCollection.version4.obj100664 163 12243235515 31325 0ustartntn 0 0 sr*org.apache.commons.collections4.ArrayStack/Gxrjava.util.ArrayListxaIsizexpw xcommons-collections4-4.0-src/src/test/resources/data/test/CompositeSet.fullCollection.version4.obj100664 1407 12243235515 31525 0ustartntn 0 0 sr0org.apache.commons.collections4.set.CompositeSetGr <LalltLjava/util/List;Lmutatort=Lorg/apache/commons/collections4/set/CompositeSet$SetMutator;xpsrjava.util.ArrayListxaIsizexpw srjava.util.HashSetD4xpw ?@tpsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~ tSevent15sq~ srjava.lang.ShorthM74`RSvaluexq~ tThreesrjava.lang.Long;̏#Jvaluexq~ t14tEightsrjava.lang.ByteN`PBvaluexq~ tNinetOnesrjava.lang.Floatɢ<Fvaluexq~ @tThirteensrjava.lang.DoubleJ)kDvaluexq~ @xxsr3org.apache.commons.collections4.set.EmptySetMutatorIحr\ j>L containedtLjava/util/Set;xpq~././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedQueue.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedQueue.emptyCollection.version4.100664 707 12243235515 32063 0ustartntn 0 0 sr6org.apache.commons.collections4.queue.TransformedQueueYN赿xr@org.apache.commons.collections4.collection.TransformedCollectionx@sL transformert-Lorg/apache/commons/collections4/Transformer;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.LinkedList )S]J`"xpwxsr7org.apache.commons.collections4.functors.NOPTransformer=?wxp././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/FixedSizeSortedMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/FixedSizeSortedMap.emptyCollection.version100664 234 12243235515 32134 0ustartntn 0 0 sr6org.apache.commons.collections4.map.FixedSizeSortedMap+aI?-%jL comparatortLjava/util/Comparator;xppwxx././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/PredicatedCollection.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/PredicatedCollection.emptyCollection.versi100664 606 12243235515 32151 0ustartntn 0 0 sr?org.apache.commons.collections4.collection.PredicatedCollectionpvL predicatet+Lorg/apache/commons/collections4/Predicate;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpw xsr6org.apache.commons.collections4.functors.TruePredicate.ՔQ&,xp././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/CircularFifoQueue.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/CircularFifoQueue.emptyCollection.version4100664 145 12243235515 32065 0ustartntn 0 0 sr7org.apache.commons.collections4.queue.CircularFifoQueueEZI maxElementsxpdwx././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/ListOrderedSet.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/ListOrderedSet.emptyCollection.version4.ob100664 747 12243235515 32013 0ustartntn 0 0 sr2org.apache.commons.collections4.set.ListOrderedSetӞSLsetOrdertLjava/util/List;xrDorg.apache.commons.collections4.set.AbstractSerializableSetDecoratorkxr8org.apache.commons.collections4.set.AbstractSetDecorator ɽxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.HashSetD4xpw ?@xq~xsrjava.util.ArrayListxaIsizexpwxcommons-collections4-4.0-src/src/test/resources/data/test/TransformingComparator.version4.obj100664 533 12243235515 30612 0ustartntn 0 0 srBorg.apache.commons.collections4.comparators.TransformingComparator/+L decoratedtLjava/util/Comparator;L transformert-Lorg/apache/commons/collections4/Transformer;xpsr@org.apache.commons.collections4.comparators.ComparableComparator%n7xpsr?org.apache.commons.collections4.functors.StringValueTransformerh-%jL comparatortLjava/util/Comparator;xppwxx././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/CaseInsensitiveMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/CaseInsensitiveMap.emptyCollection.version100664 132 12243235515 32152 0ustartntn 0 0 sr6org.apache.commons.collections4.map.CaseInsensitiveMap!nxpw ?@x././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/DualTreeBidiMap.fullCollection.version4.Test2.objcommons-collections4-4.0-src/src/test/resources/data/test/DualTreeBidiMap.fullCollection.version4.Te100664 1237 12243235515 31641 0ustartntn 0 0 sr7org.apache.commons.collections4.bidimap.DualTreeBidiMap[QL comparatortLjava/util/Comparator;LvalueComparatorq~xpsr=org.apache.commons.collections4.comparators.ReverseComparator'̲݁L comparatorq~xpsr@org.apache.commons.collections4.comparators.ComparableComparator%n7xpsq~q~srjava.util.TreeMap >-%jL comparatorq~xpq~wtyoutyouvtwe'lltwe'llvttmpttmpvtseetseevt nonnullkeytvalue2tkey2tvaluetkeyt nonnullvaluethellothellovtgoshtgoshvtgoodbyetgoodbyevtgollytgollyvtgeetgeevtfootfoovtblahtblahvtbaztbazvtbartbarvtalltallvtagaintagainvxx././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/PredicatedQueue.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/PredicatedQueue.emptyCollection.version4.o100664 700 12243235515 32013 0ustartntn 0 0 sr5org.apache.commons.collections4.queue.PredicatedQueue F(rxr?org.apache.commons.collections4.collection.PredicatedCollectionpvL predicatet+Lorg/apache/commons/collections4/Predicate;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.LinkedList )S]J`"xpwxsr6org.apache.commons.collections4.functors.TruePredicate.ՔQ&,xpcommons-collections4-4.0-src/src/test/resources/data/test/HashedMap.fullCollection.version4.obj100664 514 12243235515 30717 0ustartntn 0 0 sr-org.apache.commons.collections4.map.HashedMap/ FOsxpw ?@ tfootfoovtwe'lltwe'llvtseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2tvaluepq~tgoodbyetgoodbyevtkeyptyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxcommons-collections4-4.0-src/src/test/resources/data/test/CompositeMap.fullCollection.version4.obj100664 1140 12243235515 31501 0ustartntn 0 0 sr0org.apache.commons.collections4.map.CompositeMapcYMժ[ compositet[Ljava/util/Map;Lmutatort=Lorg/apache/commons/collections4/map/CompositeMap$MapMutator;xpur[Ljava.util.Map;ఆGL xpsrjava.util.HashMap`F loadFactorI thresholdxp?@w ptvaluetkey2q~twe'lltwe'llvtgoodbyetgoodbyevtagaintagainvtfootfoovtyoutyouvthellothellovtgoshtgoshvtbaztbazvtgeetgeevtseetseevttmpttmpvtbartbarvtkeyptalltallvtblahtblahvtgollytgollyvxsr3org.apache.commons.collections4.map.EmptyMapMutator Oxp././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/PredicatedCollection.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/PredicatedCollection.fullCollection.versio100664 642 12243235515 32134 0ustartntn 0 0 sr?org.apache.commons.collections4.collection.PredicatedCollectionpvL predicatet+Lorg/apache/commons/collections4/Predicate;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpw t1t3t5t7t2t4t6xsr6org.apache.commons.collections4.functors.TruePredicate.ՔQ&,xp././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableList.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableList.fullCollection.version4.o100664 1466 12243235515 32032 0ustartntn 0 0 sr5org.apache.commons.collections4.list.UnmodifiableList[<}xrForg.apache.commons.collections4.list.AbstractSerializableListDecorator%B){kxr:org.apache.commons.collections4.list.AbstractListDecorator>ujxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsq~ tOnesrjava.lang.DoubleJ)kDvaluexq~ @srjava.lang.Floatɢ<Fvaluexq~ @tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~ xq~x././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableQueue.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableQueue.fullCollection.version4.100664 1332 12243235515 32014 0ustartntn 0 0 sr7org.apache.commons.collections4.queue.UnmodifiableQueueoi?Mxr-%jL comparatortLjava/util/Comparator;xppwxx././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedSortedMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedSortedMap.fullCollection.versio100664 1214 12243235515 32173 0ustartntn 0 0 sr8org.apache.commons.collections4.map.TransformedSortedMapvx;xr2org.apache.commons.collections4.map.TransformedMapaw?]ZpLkeyTransformert-Lorg/apache/commons/collections4/Transformer;LvalueTransformerq~xpsr7org.apache.commons.collections4.functors.NOPTransformer=?wxpq~srjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~!tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxx././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/DualLinkedHashBidiMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/DualLinkedHashBidiMap.fullCollection.versi100664 725 12243235515 31745 0ustartntn 0 0 sr=org.apache.commons.collections4.bidimap.DualLinkedHashBidiMap[Rxpsrjava.util.LinkedHashMap4N\lZ accessOrderxrjava.util.HashMap`F loadFactorI thresholdxp?@w tblahtblahvtfootfoovtbartbarvtbaztbazvttmpttmpvtgoshtgoshvtgollytgollyvtgeetgeevthellothellovtgoodbyetgoodbyevtwe'lltwe'llvtseetseevtyoutyouvtalltallvtagaintagainvtkeyptkey2tvalueptvalue2xx././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/CollectionBag.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/CollectionBag.emptyCollection.version4.obj100664 521 12243235515 31764 0ustartntn 0 0 sr1org.apache.commons.collections4.bag.CollectionBagx潘xr8org.apache.commons.collections4.bag.AbstractBagDecorator˴)fk7xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.HashBag-%jL comparatorq~xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyt nonnullvaluetkey2tvaluet nonnullkeytvalue2tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxx././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableBag.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableBag.fullCollection.version4.ob100664 1511 12243235515 31741 0ustartntn 0 0 sr3org.apache.commons.collections4.bag.UnmodifiableBagٴxr8org.apache.commons.collections4.bag.AbstractBagDecorator˴)fk7xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.HashBagujxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpw xq~xsrjava.util.HashSetD4xpw ?@x././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/DualLinkedHashBidiMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/DualLinkedHashBidiMap.emptyCollection.vers100664 326 12243235515 31765 0ustartntn 0 0 sr=org.apache.commons.collections4.bidimap.DualLinkedHashBidiMap[Rxpsrjava.util.LinkedHashMap4N\lZ accessOrderxrjava.util.HashMap`F loadFactorI thresholdxp?@ wxxcommons-collections4-4.0-src/src/test/resources/data/test/FixedSizeMap.emptyCollection.version4.obj100664 224 12243235515 31607 0ustartntn 0 0 sr0org.apache.commons.collections4.map.FixedSizeMapggѯtxpsrjava.util.HashMap`F loadFactorI thresholdxp?@ wxx././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/ReferenceIdentityMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/ReferenceIdentityMap.emptyCollection.versi100664 142 12243235515 32132 0ustartntn 0 0 sr8org.apache.commons.collections4.map.ReferenceIdentityMapmxpw?@px././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/SynchronizedCollection.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/SynchronizedCollection.fullCollection.vers100664 1152 12243235515 32234 0ustartntn 0 0 srAorg.apache.commons.collections4.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsrjava.util.ArrayListxaIsizexpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsq~tOnesrjava.lang.DoubleJ)kDvaluexq~ @srjava.lang.Floatɢ<Fvaluexq~ @tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~ xq~commons-collections4-4.0-src/src/test/resources/data/test/SingletonMap.fullCollection.version4.obj100664 304 12243235515 31462 0ustartntn 0 0 sr0org.apache.commons.collections4.map.SingletonMap <ʐACLkeytLjava/lang/Object;Lvalueq~xpsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/PredicatedSortedMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/PredicatedSortedMap.fullCollection.version100664 1203 12243235515 32127 0ustartntn 0 0 sr7org.apache.commons.collections4.map.PredicatedSortedMap.Kxr1org.apache.commons.collections4.map.PredicatedMapfٟ%L keyPredicatet+Lorg/apache/commons/collections4/Predicate;LvaluePredicateq~xpsr6org.apache.commons.collections4.functors.TruePredicate.ՔQ&,xpq~srjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~!tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxx././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableOrderedMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableOrderedMap.fullCollection.vers100664 1212 12243235515 32077 0ustartntn 0 0 sr:org.apache.commons.collections4.map.UnmodifiableOrderedMappfM%xpsr2org.apache.commons.collections4.map.ListOrderedMap%o53fL insertOrdertLjava/util/List;xpsrjava.util.ArrayListxaIsizexpwtagaintalltbartbaztblahtfootgeetgollytgoodbyetgoshthellotkeytkey2tseettmptwe'lltyoupxsrjava.util.HashMap`F loadFactorI thresholdxp?@w ptvalueq~pq~tyouvq~thellovq~tblahvq~q~q~ tgoshvq~twe'llvq~tgoodbyevq~tallvq~ tbazvq~ tgollyvq~tagainvq~ tbarvq~tfoovq~ ttmpvq~tgeevq~tseevxxxcommons-collections4-4.0-src/src/test/resources/data/test/MultiKeyMap.emptyCollection.version4.obj100664 222 12243235515 31456 0ustartntn 0 0 sr/org.apache.commons.collections4.map.MultiKeyMap/ FOsxpsr-org.apache.commons.collections4.map.HashedMap/ FOsxpw ?@xx././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/CompositeCollection.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/CompositeCollection.fullCollection.version100664 602 12243235515 32204 0ustartntn 0 0 sr>org.apache.commons.collections4.collection.CompositeCollectiontV}qLalltLjava/util/List;LmutatortRLorg/apache/commons/collections4/collection/CompositeCollection$CollectionMutator;xpsrjava.util.ArrayListxaIsizexpw srjava.util.HashSetD4xpw ?@t1xsq~w ?@t2xsq~w ?@t3xsq~w ?@t4xxpcommons-collections4-4.0-src/src/test/resources/data/test/LazyMap.fullCollection.version4.obj100664 1262 12243235515 30463 0ustartntn 0 0 sr+org.apache.commons.collections4.map.LazyMapn唂yLfactoryt-Lorg/apache/commons/collections4/Transformer;xpsr;org.apache.commons.collections4.functors.FactoryTransformerb)]LiFactoryt)Lorg/apache/commons/collections4/Factory;xpsr8org.apache.commons.collections4.functors.ConstantFactory$ m[*L iConstanttLjava/lang/Object;xppsrjava.util.HashMap`F loadFactorI thresholdxp?@w ptvaluetkey2q~ twe'lltwe'llvtgoodbyetgoodbyevtagaintagainvtfootfoovtyoutyouvthellothellovtgoshtgoshvtbaztbazvtgeetgeevtseetseevttmpttmpvtbartbarvtkeyptalltallvtblahtblahvtgollytgollyvxxcommons-collections4-4.0-src/src/test/resources/data/test/GrowthList.fullCollection.version4.obj100664 1460 12243235515 31214 0ustartntn 0 0 sr/org.apache.commons.collections4.list.GrowthList'xrForg.apache.commons.collections4.list.AbstractSerializableListDecorator%B){kxr:org.apache.commons.collections4.list.AbstractListDecorator>ujxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsq~ tOnesrjava.lang.DoubleJ)kDvaluexq~ @srjava.lang.Floatɢ<Fvaluexq~ @tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~ xq~xcommons-collections4-4.0-src/src/test/resources/data/test/ComparableComparator.version4.obj100664 125 12243235515 30203 0ustartntn 0 0 sr@org.apache.commons.collections4.comparators.ComparableComparator%n7xp././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/ListOrderedMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/ListOrderedMap.emptyCollection.version4.ob100664 355 12243235515 31770 0ustartntn 0 0 sr2org.apache.commons.collections4.map.ListOrderedMap%o53fL insertOrdertLjava/util/List;xpsrjava.util.ArrayListxaIsizexpw xsrjava.util.HashMap`F loadFactorI thresholdxp?@ wxxcommons-collections4-4.0-src/src/test/resources/data/test/ReverseComparator.version4.obj100664 260 12243235515 27551 0ustartntn 0 0 sr=org.apache.commons.collections4.comparators.ReverseComparator'̲݁L comparatortLjava/util/Comparator;xpsr'java.util.Collections$ReverseComparatordSNJxp././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableTrie.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableTrie.emptyCollection.version4.100664 771 12243235515 32015 0ustartntn 0 0 sr9org.apache.commons.collections4.map.UnmodifiableSortedMapPXxpsr1org.apache.commons.collections4.trie.PatriciaTrie=Ye xr9org.apache.commons.collections4.trie.AbstractPatriciaTrieG#U1Oxr8org.apache.commons.collections4.trie.AbstractBitwiseTriePݝܐԐL keyAnalyzert2Lorg/apache/commons/collections4/trie/KeyAnalyzer;xpsr?org.apache.commons.collections4.trie.analyzer.StringKeyAnalyzergr|Bxr0org.apache.commons.collections4.trie.KeyAnalyzer- xpwxx././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/ListOrderedSet.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/ListOrderedSet.fullCollection.version4.obj100664 1716 12243235515 32006 0ustartntn 0 0 sr2org.apache.commons.collections4.set.ListOrderedSetӞSLsetOrdertLjava/util/List;xrDorg.apache.commons.collections4.set.AbstractSerializableSetDecoratorkxr8org.apache.commons.collections4.set.AbstractSetDecorator ɽxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.HashSetD4xpw ?@tpsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~ tSevent15sq~ srjava.lang.ShorthM74`RSvaluexq~ tThreesrjava.lang.Long;̏#Jvaluexq~ t14tEightsrjava.lang.ByteN`PBvaluexq~ tNinetOnesrjava.lang.Floatɢ<Fvaluexq~ @tThirteensrjava.lang.DoubleJ)kDvaluexq~ @xq~xsrjava.util.ArrayListxaIsizexpwq~ q~q~ q~pq~ q~ q~q~q~q~q~q~q~q~q~q~q~xcommons-collections4-4.0-src/src/test/resources/data/test/CollectionBag.fullCollection.version4.obj100664 1516 12243235515 31615 0ustartntn 0 0 sr1org.apache.commons.collections4.bag.CollectionBagx潘xr8org.apache.commons.collections4.bag.AbstractBagDecorator˴)fk7xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.HashBag-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~%tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxx././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/ReferenceIdentityMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/ReferenceIdentityMap.fullCollection.versio100664 567 12243235515 32130 0ustartntn 0 0 sr8org.apache.commons.collections4.map.ReferenceIdentityMapmxpw?@ tkeyt nonnullvaluetyoutyouvtbartbarvtwe'lltwe'llvt nonnullkeytvaluetgeetgeevtgoshtgoshvtseetseevthellothellovtbaztbazvttmpttmpvtalltallvtagaintagainvtgollytgollyvtblahtblahvtkey2q~ tfootfoovtgoodbyetgoodbyevpx././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/SynchronizedCollection.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/SynchronizedCollection.emptyCollection.ver100664 323 12243235515 32224 0ustartntn 0 0 srAorg.apache.commons.collections4.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsrjava.util.ArrayListxaIsizexpw xq~././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableCollection.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableCollection.fullCollection.vers100664 1236 12243235515 32156 0ustartntn 0 0 srAorg.apache.commons.collections4.collection.UnmodifiableCollection};WxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsq~tOnesrjava.lang.DoubleJ)kDvaluexq~ @srjava.lang.Floatɢ<Fvaluexq~ @tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~ x././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/CaseInsensitiveMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/CaseInsensitiveMap.fullCollection.version4100664 525 12243235515 32050 0ustartntn 0 0 sr6org.apache.commons.collections4.map.CaseInsensitiveMap!nxpw ?@ tfootfoovtwe'lltwe'llvtseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2tvaluepq~tgoodbyetgoodbyevtkeyptyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvxcommons-collections4-4.0-src/src/test/resources/data/test/DefaultedMap.emptyCollection.version4.obj100664 672 12243235515 31621 0ustartntn 0 0 sr0org.apache.commons.collections4.map.DefaultedMapqcLvaluet-Lorg/apache/commons/collections4/Transformer;xpsr;org.apache.commons.collections4.functors.FactoryTransformerb)]LiFactoryt)Lorg/apache/commons/collections4/Factory;xpsr8org.apache.commons.collections4.functors.ConstantFactory$ m[*L iConstanttLjava/lang/Object;xppsrjava.util.HashMap`F loadFactorI thresholdxp?@ wxxcommons-collections4-4.0-src/src/test/resources/data/test/LinkedMap.fullCollection.version4.obj100664 514 12243235515 30731 0ustartntn 0 0 sr-org.apache.commons.collections4.map.LinkedMap}І$vGjxpw ?@ tagaintblahvtalltfoovtbartbarvtbaztbazvtblahttmpvtfootgoshvtgeetgollyvtgollytgeevtgoodbyethellovtgoshtgoodbyevthellotwe'llvtkeytseevtkey2tyouvtseetallvttmptagainvtwe'llptyoutvaluepq~"x././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSortedSet.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSortedSet.emptyCollection.vers100664 615 12243235515 32153 0ustartntn 0 0 sr9org.apache.commons.collections4.set.UnmodifiableSortedSetzLcxr>org.apache.commons.collections4.set.AbstractSortedSetDecorator3R1xr8org.apache.commons.collections4.set.AbstractSetDecorator ɽxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.TreeSetݘP[xppwxq~x././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableOrderedMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableOrderedMap.emptyCollection.ver100664 471 12243235515 32076 0ustartntn 0 0 sr:org.apache.commons.collections4.map.UnmodifiableOrderedMappfM%xpsr2org.apache.commons.collections4.map.ListOrderedMap%o53fL insertOrdertLjava/util/List;xpsrjava.util.ArrayListxaIsizexpw xsrjava.util.HashMap`F loadFactorI thresholdxp?@ wxxx././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/SynchronizedBag.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/SynchronizedBag.emptyCollection.version4.o100664 442 12243235515 32036 0ustartntn 0 0 sr3org.apache.commons.collections4.bag.SynchronizedBagp2 j5xrAorg.apache.commons.collections4.collection.SynchronizedCollection!|rI "L collectiontLjava/util/Collection;LlocktLjava/lang/Object;xpsr+org.apache.commons.collections4.bag.HashBagujxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsq~ srjava.lang.DoubleJ)kDvaluexq~ @srjava.lang.Floatɢ<Fvaluexq~ @tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~ xq~xsrjava.util.HashSetD4xpw ?@q~ pq~ q~q~q~q~q~q~q~q~q~q~ q~q~ q~q~q~x././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedSortedSet.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedSortedSet.emptyCollection.versi100664 1010 12243235515 32220 0ustartntn 0 0 sr8org.apache.commons.collections4.set.TransformedSortedSetyGv^xr2org.apache.commons.collections4.set.TransformedSet?;xr@org.apache.commons.collections4.collection.TransformedCollectionx@sL transformert-Lorg/apache/commons/collections4/Transformer;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.TreeSetݘP[xppwxsr7org.apache.commons.collections4.functors.NOPTransformer=?wxp././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedSortedBag.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedSortedBag.fullCollection.versio100664 2105 12243235515 32147 0ustartntn 0 0 sr8org.apache.commons.collections4.bag.TransformedSortedBagXݶxr2org.apache.commons.collections4.bag.TransformedBagK;8xxr@org.apache.commons.collections4.collection.TransformedCollectionx@sL transformert-Lorg/apache/commons/collections4/Transformer;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.TreeBagylxppwsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpwsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ !wsq~ #wsq~ %wsq~ 'wsq~ )wsq~ +wsq~ -wsq~ /wsq~ 1wsq~ 3wsq~ 5wsq~ 7wsq~ 9wsq~ ;wxsr7org.apache.commons.collections4.functors.NOPTransformer=?wxpcommons-collections4-4.0-src/src/test/resources/data/test/HashBag.emptyCollection.version4.obj100664 107 12243235515 30554 0ustartntn 0 0 sr+org.apache.commons.collections4.bag.HashBagL containedtLjava/util/Set;xpq~././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/MultiValueMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/MultiValueMap.emptyCollection.version4.obj100664 560 12243235515 32007 0ustartntn 0 0 sr1org.apache.commons.collections4.map.MultiValueMapEJWILcollectionFactoryt)Lorg/apache/commons/collections4/Factory;xpsrCorg.apache.commons.collections4.map.MultiValueMap$ReflectionFactory)pP\gLclazztLjava/lang/Class;xpvrjava.util.ArrayListxaIsizexpsrjava.util.HashMap`F loadFactorI thresholdxp?@ wxx././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/PassiveExpiringMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/PassiveExpiringMap.fullCollection.version4100664 1653 12243235515 32117 0ustartntn 0 0 sr6org.apache.commons.collections4.map.PassiveExpiringMapL expirationMaptLjava/util/Map;LexpiringPolicytILorg/apache/commons/collections4/map/PassiveExpiringMap$ExpirationPolicy;xpsrjava.util.HashMap`F loadFactorI thresholdxp?@w psrjava.lang.Long;̏#Jvaluexrjava.lang.Number xptkey2q~twe'llq~tgoodbyeq~tagainq~tfooq~tyouq~thelloq~tgoshq~tbazq~tgeeq~tseeq~ttmpq~tbarq~tkeyq~tallq~tblahq~tgollyq~xsrYorg.apache.commons.collections4.map.PassiveExpiringMap$ConstantTimeToLiveExpirationPolicyJtimeToLiveMillisxpsq~?@w ptvalueq~ q~q~ twe'llvq~ tgoodbyevq~ tagainvq~ tfoovq~tyouvq~thellovq~tgoshvq~tbazvq~tgeevq~tseevq~ttmpvq~tbarvq~pq~tallvq~tblahvq~tgollyvxx././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/FixedSizeList.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/FixedSizeList.emptyCollection.version4.obj100664 634 12243235515 32012 0ustartntn 0 0 sr2org.apache.commons.collections4.list.FixedSizeList8 ;axrForg.apache.commons.collections4.list.AbstractSerializableListDecorator%B){kxr:org.apache.commons.collections4.list.AbstractListDecorator>ujxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpw xq~x././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSortedSet.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSortedSet.fullCollection.versi100664 1374 12243235515 32153 0ustartntn 0 0 sr9org.apache.commons.collections4.set.UnmodifiableSortedSetzLcxr>org.apache.commons.collections4.set.AbstractSortedSetDecorator3R1xr8org.apache.commons.collections4.set.AbstractSetDecorator ɽxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.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~;xq~xcommons-collections4-4.0-src/src/test/resources/data/test/TreeBidiMap.fullCollection.version4.obj100664 550 12243235515 31212 0ustartntn 0 0 sr3org.apache.commons.collections4.bidimap.TreeBidiMap[Oxpwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyt nonnullvaluetkey2tvaluet nonnullkeytvalue2tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxcommons-collections4-4.0-src/src/test/resources/data/test/MapBackedSet.emptyCollection.version4.obj100664 315 12243235515 31543 0ustartntn 0 0 sr0org.apache.commons.collections4.set.MapBackedSet]P"oL dummyValuetLjava/lang/Object;LmaptLjava/util/Map;xppsr-org.apache.commons.collections4.map.HashedMap/ FOsxpw ?@x././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/CircularFifoQueue.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/CircularFifoQueue.fullCollection.version4.100664 773 12243235515 31756 0ustartntn 0 0 sr7org.apache.commons.collections4.queue.CircularFifoQueueEZI 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~x././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedSortedMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedSortedMap.emptyCollection.versi100664 605 12243235515 32173 0ustartntn 0 0 sr8org.apache.commons.collections4.map.TransformedSortedMapvx;xr2org.apache.commons.collections4.map.TransformedMapaw?]ZpLkeyTransformert-Lorg/apache/commons/collections4/Transformer;LvalueTransformerq~xpsr7org.apache.commons.collections4.functors.NOPTransformer=?wxpq~srjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwxx././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSet.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSet.fullCollection.version4.ob100664 1445 12243235515 32011 0ustartntn 0 0 sr3org.apache.commons.collections4.set.UnmodifiableSetZ1HaxrDorg.apache.commons.collections4.set.AbstractSerializableSetDecoratorkxr8org.apache.commons.collections4.set.AbstractSetDecorator ɽxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.HashSetD4xpw ?@tpsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~ tSevent15sq~ srjava.lang.ShorthM74`RSvaluexq~ tThreesrjava.lang.Long;̏#Jvaluexq~ t14tEightsrjava.lang.ByteN`PBvaluexq~ tNinetOnesrjava.lang.Floatɢ<Fvaluexq~ @tThirteensrjava.lang.DoubleJ)kDvaluexq~ @xq~x././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedMap.fullCollection.version4.obj100664 1067 12243235515 32033 0ustartntn 0 0 sr2org.apache.commons.collections4.map.TransformedMapaw?]ZpLkeyTransformert-Lorg/apache/commons/collections4/Transformer;LvalueTransformerq~xpsr7org.apache.commons.collections4.functors.NOPTransformer=?wxpq~srjava.util.HashMap`F loadFactorI thresholdxp?@w ptvaluetkey2q~twe'lltwe'llvtgoodbyetgoodbyevtagaintagainvtfootfoovtyoutyouvthellothellovtgoshtgoshvtbaztbazvtgeetgeevtseetseevttmpttmpvtbartbarvtkeyptalltallvtblahtblahvtgollytgollyvxx././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/CollectionSortedBag.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/CollectionSortedBag.fullCollection.version100664 1710 12243235515 32135 0ustartntn 0 0 sr7org.apache.commons.collections4.bag.CollectionSortedBagx潘xr>org.apache.commons.collections4.bag.AbstractSortedBagDecoratorZO |zxr8org.apache.commons.collections4.bag.AbstractBagDecorator˴)fk7xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.TreeBagylxppwsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpwsq~wsq~wsq~wsq~ wsq~ wsq~ wsq~wsq~wsq~wsq~wsq~wsq~wsq~wsq~wsq~wsq~!wsq~#wsq~%wsq~'wsq~)wsq~+wsq~-wsq~/wsq~1wsq~3wsq~5wsq~7wsq~9wsq~;wxq~x././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/NodeCachingLinkedList.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/NodeCachingLinkedList.emptyCollection.vers100664 155 12243235515 32044 0ustartntn 0 0 sr:org.apache.commons.collections4.list.NodeCachingLinkedList_޶;? ImaximumCacheSizexpwxcommons-collections4-4.0-src/src/test/resources/data/test/ReferenceMap.emptyCollection.version4.obj100664 132 12243235515 31611 0ustartntn 0 0 sr0org.apache.commons.collections4.map.ReferenceMapIxpw?@pxcommons-collections4-4.0-src/src/test/resources/data/test/LinkedMap.emptyCollection.version4.obj100664 121 12243235515 31117 0ustartntn 0 0 sr-org.apache.commons.collections4.map.LinkedMap}І$vGjxpw ?@x././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedSplitMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedSplitMap.fullCollection.version100664 546 12243235515 32173 0ustartntn 0 0 sr-%jL comparatorq~xpq~wxxcommons-collections4-4.0-src/src/test/resources/data/test/LRUMap.emptyCollection.version4.obj100664 150 12243235515 30355 0ustartntn 0 0 sr*org.apache.commons.collections4.map.LRUMapTZscanUntilRemovablexpwd?@xcommons-collections4-4.0-src/src/test/resources/data/test/MultiKeyMap.fullCollection.version4.obj100664 1502 12243235515 31304 0ustartntn 0 0 sr/org.apache.commons.collections4.map.MultiKeyMap/ FOsxpsr-org.apache.commons.collections4.map.HashedMap/ FOsxpw ?@ sr1org.apache.commons.collections4.keyvalue.MultiKey=uw[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~t5Jxx././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/CollectionSortedBag.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/CollectionSortedBag.emptyCollection.versio100664 645 12243235515 32141 0ustartntn 0 0 sr7org.apache.commons.collections4.bag.CollectionSortedBagx潘xr>org.apache.commons.collections4.bag.AbstractSortedBagDecoratorZO |zxr8org.apache.commons.collections4.bag.AbstractBagDecorator˴)fk7xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.TreeBagylxppwxq~x././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/FixedSizeSortedMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/FixedSizeSortedMap.fullCollection.version4100664 643 12243235515 32030 0ustartntn 0 0 sr6org.apache.commons.collections4.map.FixedSizeSortedMap+aI?-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxcommons-collections4-4.0-src/src/test/resources/data/test/ReferenceMap.fullCollection.version4.obj100664 557 12243235515 31430 0ustartntn 0 0 sr0org.apache.commons.collections4.map.ReferenceMapIxpw?@ tfootfoovtwe'lltwe'llvt nonnullkeytvaluetseetseevtbaztbazvthellothellovtbartbarvtagaintagainvtkey2q~tgoodbyetgoodbyevtkeyt nonnullvaluetyoutyouvtblahtblahvtgeetgeevttmpttmpvtgollytgollyvtgoshtgoshvtalltallvpx././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableMap.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableMap.fullCollection.version4.ob100664 622 12243235515 31747 0ustartntn 0 0 sr3org.apache.commons.collections4.map.UnmodifiableMap%NDJxpsrjava.util.HashMap`F loadFactorI thresholdxp?@w ptvaluetkey2q~twe'lltwe'llvtgoodbyetgoodbyevtagaintagainvtfootfoovtyoutyouvthellothellovtgoshtgoshvtbaztbazvtgeetgeevtseetseevttmpttmpvtbartbarvtkeyptalltallvtblahtblahvtgollytgollyvxx././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedList.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedList.fullCollection.version4.ob100664 1546 12243235515 32061 0ustartntn 0 0 sr4org.apache.commons.collections4.list.TransformedList[aUxr@org.apache.commons.collections4.collection.TransformedCollectionx@sL transformert-Lorg/apache/commons/collections4/Transformer;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsq~ tOnesrjava.lang.DoubleJ)kDvaluexq~ @srjava.lang.Floatɢ<Fvaluexq~ @tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~ xsr7org.apache.commons.collections4.functors.NOPTransformer=?wxpcommons-collections4-4.0-src/src/test/resources/data/test/NullComparator.version4.obj2100664 335 12243235515 27135 0ustartntn 0 0 sr:org.apache.commons.collections4.comparators.NullComparator8v.Y-Z nullsAreHighLnonNullComparatortLjava/util/Comparator;xpsr@org.apache.commons.collections4.comparators.ComparableComparator%n7xp././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedSortedBag.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedSortedBag.emptyCollection.versi100664 1042 12243235515 32163 0ustartntn 0 0 sr8org.apache.commons.collections4.bag.TransformedSortedBagXݶxr2org.apache.commons.collections4.bag.TransformedBagK;8xxr@org.apache.commons.collections4.collection.TransformedCollectionx@sL transformert-Lorg/apache/commons/collections4/Transformer;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.TreeBagylxppwxsr7org.apache.commons.collections4.functors.NOPTransformer=?wxp././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedSet.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedSet.emptyCollection.version4.ob100664 710 12243235515 32045 0ustartntn 0 0 sr2org.apache.commons.collections4.set.TransformedSet?;xr@org.apache.commons.collections4.collection.TransformedCollectionx@sL transformert-Lorg/apache/commons/collections4/Transformer;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.HashSetD4xpw ?@xsr7org.apache.commons.collections4.functors.NOPTransformer=?wxp././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableMap.emptyCollection.version4.o100664 227 12243235515 32002 0ustartntn 0 0 sr3org.apache.commons.collections4.map.UnmodifiableMap%NDJxpsrjava.util.HashMap`F loadFactorI thresholdxp?@ wxxcommons-collections4-4.0-src/src/test/resources/data/test/FixedSizeList.fullCollection.version4.obj100664 1463 12243235515 31637 0ustartntn 0 0 sr2org.apache.commons.collections4.list.FixedSizeList8 ;axrForg.apache.commons.collections4.list.AbstractSerializableListDecorator%B){kxr:org.apache.commons.collections4.list.AbstractListDecorator>ujxrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpwttOnesrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xptThreepsq~ tOnesrjava.lang.DoubleJ)kDvaluexq~ @srjava.lang.Floatɢ<Fvaluexq~ @tSeventEighttNinesq~ srjava.lang.ShorthM74`RSvaluexq~ srjava.lang.Long;̏#Jvaluexq~ tThirteent14t15srjava.lang.ByteN`PBvaluexq~ xq~x././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSortedBag.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSortedBag.fullCollection.versi100664 1712 12243235515 32105 0ustartntn 0 0 sr9org.apache.commons.collections4.bag.UnmodifiableSortedBagӹJ8˯xr>org.apache.commons.collections4.bag.AbstractSortedBagDecoratorZO |zxr8org.apache.commons.collections4.bag.AbstractBagDecorator˴)fk7xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.TreeBagylxppwsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpwsq~wsq~wsq~wsq~ wsq~ wsq~ wsq~wsq~wsq~wsq~wsq~wsq~wsq~wsq~wsq~wsq~!wsq~#wsq~%wsq~'wsq~)wsq~+wsq~-wsq~/wsq~1wsq~3wsq~5wsq~7wsq~9wsq~;wxq~x././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSortedMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSortedMap.emptyCollection.vers100664 237 12243235515 32135 0ustartntn 0 0 sr9org.apache.commons.collections4.map.UnmodifiableSortedMapPXxpsrjava.util.TreeMap >-%jL comparatortLjava/util/Comparator;xppwxx././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedList.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedList.emptyCollection.version4.o100664 717 12243235515 32072 0ustartntn 0 0 sr4org.apache.commons.collections4.list.TransformedList[aUxr@org.apache.commons.collections4.collection.TransformedCollectionx@sL transformert-Lorg/apache/commons/collections4/Transformer;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.ArrayListxaIsizexpw xsr7org.apache.commons.collections4.functors.NOPTransformer=?wxpcommons-collections4-4.0-src/src/test/resources/data/test/TreeBag.fullCollection.version4.obj100664 1153 12243235515 30416 0ustartntn 0 0 sr+org.apache.commons.collections4.bag.TreeBagylxppwsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpwsq~wsq~wsq~wsq~ wsq~ wsq~ wsq~wsq~wsq~wsq~wsq~wsq~wsq~wsq~wsq~wsq~!wsq~#wsq~%wsq~'wsq~)wsq~+wsq~-wsq~/wsq~1wsq~3wsq~5wsq~7wsq~9wsq~;wx././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/DualHashBidiMap.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/DualHashBidiMap.emptyCollection.version4.o100664 233 12243235515 31662 0ustartntn 0 0 sr7org.apache.commons.collections4.bidimap.DualHashBidiMap[Pxpsrjava.util.HashMap`F loadFactorI thresholdxp?@ wxx././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/PredicatedQueue.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/PredicatedQueue.fullCollection.version4.ob100664 1527 12243235515 32011 0ustartntn 0 0 sr5org.apache.commons.collections4.queue.PredicatedQueue F(rxr?org.apache.commons.collections4.collection.PredicatedCollectionpvL predicatet+Lorg/apache/commons/collections4/Predicate;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.LinkedList )S]J`"xpwttOnesrjava.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~ xsr6org.apache.commons.collections4.functors.TruePredicate.ՔQ&,xp././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/TransformedSet.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/TransformedSet.fullCollection.version4.obj100664 1531 12243235515 32045 0ustartntn 0 0 sr2org.apache.commons.collections4.set.TransformedSet?;xr@org.apache.commons.collections4.collection.TransformedCollectionx@sL transformert-Lorg/apache/commons/collections4/Transformer;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsrjava.util.HashSetD4xpw ?@tpsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpsq~ tSevent15sq~ srjava.lang.ShorthM74`RSvaluexq~ tThreesrjava.lang.Long;̏#Jvaluexq~ t14tEightsrjava.lang.ByteN`PBvaluexq~ tNinetOnesrjava.lang.Floatɢ<Fvaluexq~ @tThirteensrjava.lang.DoubleJ)kDvaluexq~ @xsr7org.apache.commons.collections4.functors.NOPTransformer=?wxp././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSortedBag.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableSortedBag.emptyCollection.vers100664 647 12243235515 32116 0ustartntn 0 0 sr9org.apache.commons.collections4.bag.UnmodifiableSortedBagӹJ8˯xr>org.apache.commons.collections4.bag.AbstractSortedBagDecoratorZO |zxr8org.apache.commons.collections4.bag.AbstractBagDecorator˴)fk7xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.TreeBagylxppwxq~x././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/PredicatedSortedBag.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/PredicatedSortedBag.fullCollection.version100664 2075 12243235515 32113 0ustartntn 0 0 sr7org.apache.commons.collections4.bag.PredicatedSortedBag/o +xr1org.apache.commons.collections4.bag.PredicatedBag@gxr?org.apache.commons.collections4.collection.PredicatedCollectionpvL predicatet+Lorg/apache/commons/collections4/Predicate;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.TreeBagylxppwsrjava.lang.Integer⠤8Ivaluexrjava.lang.Number xpwsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ wsq~ !wsq~ #wsq~ %wsq~ 'wsq~ )wsq~ +wsq~ -wsq~ /wsq~ 1wsq~ 3wsq~ 5wsq~ 7wsq~ 9wsq~ ;wxsr6org.apache.commons.collections4.functors.TruePredicate.ՔQ&,xp././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/CursorableLinkedList.fullCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/CursorableLinkedList.fullCollection.versio100664 754 12243235515 32144 0ustartntn 0 0 sr9org.apache.commons.collections4.list.CursorableLinkedListz,zxpwttOnesrjava.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~xcommons-collections4-4.0-src/src/test/resources/data/test/PredicatedBag.fullCollection.version4.obj100664 1720 12243235515 31563 0ustartntn 0 0 sr1org.apache.commons.collections4.bag.PredicatedBag@gxr?org.apache.commons.collections4.collection.PredicatedCollectionpvL predicatet+Lorg/apache/commons/collections4/Predicate;xrForg.apache.commons.collections4.collection.AbstractCollectionDecoratorV4L collectiontLjava/util/Collection;xpsr+org.apache.commons.collections4.bag.HashBag-%jL comparatorq~xppwxx././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableQueue.emptyCollection.version4.objcommons-collections4-4.0-src/src/test/resources/data/test/UnmodifiableQueue.emptyCollection.version4100664 504 12243235515 32112 0ustartntn 0 0 sr7org.apache.commons.collections4.queue.UnmodifiableQueueoi?Mxr-%jL comparatortLjava/util/Comparator;xppwtagaintagainvtalltallvtbartbarvtbaztbazvtblahtblahvtfootfoovtgeetgeevtgollytgollyvtgoodbyetgoodbyevtgoshtgoshvthellothellovtkeyptkey2tvaluet nonnullkeyq~tseetseevttmpttmpvtwe'lltwe'llvtyoutyouvxxcommons-collections4-4.0-src/src/test/resources/data/test/PatriciaTrie.fullCollection.version4.obj100664 1265 12243235515 31471 0ustartntn 0 0 sr1org.apache.commons.collections4.trie.PatriciaTrie=Ye xr9org.apache.commons.collections4.trie.AbstractPatriciaTrieG#U1Oxr8org.apache.commons.collections4.trie.AbstractBitwiseTriePݝܐԐL keyAnalyzert2Lorg/apache/commons/collections4/trie/KeyAnalyzer;xpsr?org.apache.commons.collections4.trie.analyzer.StringKeyAnalyzergr|Bxr0org.apache.commons.collections4.trie.KeyAnalyzer- xpwtagaintblahvtalltfoovtbartbarvtbaztbazvtblahttmpvtfootgoshvtgeetgollyvtgollytgeevtgoodbyethellovtgoshtgoodbyevthellotwe'llvtkeytseevtkey2tyouvt nonnullkeytallvtseetagainvttmpptwe'lltvaluetyouq~(x././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/DefaultKeyValueTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/DefaultKeyValueT100664 14246 12243235516 31746 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * Test the DefaultKeyValue class. * * @since 3.0 * @version $Id: DefaultKeyValueTest.java 1540705 2013-11-11 13:22:32Z ebourg $ */ public class DefaultKeyValueTest extends TestCase { private final String key = "name"; private final String value = "duke"; //----------------------------------------------------------------------- /** * 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(final K key, final V value) { return new DefaultKeyValue(key, value); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testAccessorsAndMutators() { final DefaultKeyValue kv = makeDefaultKeyValue(); kv.setKey((K) key); assertTrue(kv.getKey() == key); kv.setValue((V) 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); } @SuppressWarnings("unchecked") 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) final DefaultKeyValue kv = makeDefaultKeyValue(); try { kv.setKey((K) kv); fail("Should throw an IllegalArgumentException"); } catch (final IllegalArgumentException iae) { // expected to happen... // check that the KVP's state has not changed assertTrue(kv.getKey() == null && kv.getValue() == null); } try { kv.setValue((V) kv); fail("Should throw an IllegalArgumentException"); } catch (final 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. */ @SuppressWarnings("unchecked") 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((K) key, (V) value); assertTrue(kv.getKey() == key && kv.getValue() == value); // 3. test copy constructor final 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 final Map map = new HashMap(); map.put((K) key, (V) value); final Map.Entry 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); } @SuppressWarnings("unchecked") public void testEqualsAndHashCode() { // 1. test with object data DefaultKeyValue kv = makeDefaultKeyValue((K) key, (V) value); DefaultKeyValue kv2 = makeDefaultKeyValue((K) key, (V) 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()); } @SuppressWarnings("unchecked") public void testToString() { DefaultKeyValue kv = makeDefaultKeyValue((K) key, (V) value); assertTrue(kv.toString().equals(kv.getKey() + "=" + kv.getValue())); // test with nulls kv = makeDefaultKeyValue(null, null); assertTrue(kv.toString().equals(kv.getKey() + "=" + kv.getValue())); } @SuppressWarnings("unchecked") public void testToMapEntry() { final DefaultKeyValue kv = makeDefaultKeyValue((K) key, (V) value); final Map map = new HashMap(); map.put(kv.getKey(), kv.getValue()); final Map.Entry entry = map.entrySet().iterator().next(); assertTrue(entry.equals(kv.toMapEntry())); assertTrue(entry.hashCode() == kv.hashCode()); } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/DefaultMapEntryTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/DefaultMapEntryT100664 6250 12243235516 31734 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.util.Map; import org.apache.commons.collections4.KeyValue; /** * Test the DefaultMapEntry class. * * @since 3.0 * @version $Id: DefaultMapEntryTest.java 1540705 2013-11-11 13:22:32Z ebourg $ */ public class DefaultMapEntryTest extends AbstractMapEntryTest { //----------------------------------------------------------------------- /** * 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. */ @Override 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. */ @Override public Map.Entry makeMapEntry(final K key, final V value) { return new DefaultMapEntry(key, value); } //----------------------------------------------------------------------- /** * Subclasses should override this method. * */ @Override @SuppressWarnings("unchecked") public void testConstructors() { // 1. test key-value constructor final Map.Entry entry = new DefaultMapEntry((K) key, (V) value); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); // 2. test pair constructor final KeyValue pair = new DefaultKeyValue((K) key, (V) value); assertSame(key, pair.getKey()); assertSame(value, pair.getValue()); // 3. test copy constructor final 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()); } @Override @SuppressWarnings("unchecked") public void testSelfReferenceHandling() { final Map.Entry entry = makeMapEntry(); try { entry.setValue((V) entry); assertSame(entry, entry.getValue()); } catch (final Exception e) { fail("This Map.Entry implementation supports value self-reference."); } } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/AbstractMapEntryTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/AbstractMapEntry100664 12266 12243235516 32013 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 3.0 * @version $Id: AbstractMapEntryTest.java 1540705 2013-11-11 13:22:32Z ebourg $ */ public abstract class AbstractMapEntryTest extends TestCase { protected final String key = "name"; protected final String value = "duke"; //----------------------------------------------------------------------- /** * 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(K key, V 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(final K key, final V value) { final Map map = new HashMap(1); map.put(key, value); final Map.Entry entry = map.entrySet().iterator().next(); return entry; } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testAccessorsAndMutators() { Map.Entry entry = makeMapEntry((K) key, (V) value); assertTrue(entry.getKey() == key); entry.setValue((V) 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. * */ @SuppressWarnings("unchecked") public void testSelfReferenceHandling() { // test that #setValue does not permit // the MapEntry to contain itself (and thus cause infinite recursion // in #hashCode and #toString) final Map.Entry entry = makeMapEntry(); try { entry.setValue((V) entry); fail("Should throw an IllegalArgumentException"); } catch (final 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(); @SuppressWarnings("unchecked") public void testEqualsAndHashCode() { // 1. test with object data Map.Entry e1 = makeMapEntry((K) key, (V) value); Map.Entry e2 = makeKnownMapEntry((K) key, (V) 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()); } @SuppressWarnings("unchecked") public void testToString() { Map.Entry entry = makeMapEntry((K) key, (V) value); assertTrue(entry.toString().equals(entry.getKey() + "=" + entry.getValue())); // test with nulls entry = makeMapEntry(); assertTrue(entry.toString().equals(entry.getKey() + "=" + entry.getValue())); } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/TiedMapEntryTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/TiedMapEntryTest100664 5325 12243235516 31753 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.util.HashMap; import java.util.Map; /** * Test the TiedMapEntry class. * * @since 3.0 * @version $Id: TiedMapEntryTest.java 1540705 2013-11-11 13:22:32Z ebourg $ */ public class TiedMapEntryTest extends AbstractMapEntryTest { //----------------------------------------------------------------------- /** * Gets the instance to test */ @Override public Map.Entry makeMapEntry(final K key, final V value) { final Map map = new HashMap(); map.put(key, value); return new TiedMapEntry(map, key); } //----------------------------------------------------------------------- /** * Tests the constructors. */ @Override public void testConstructors() { // ignore } /** * Tests the constructors. */ @SuppressWarnings("unchecked") public void testSetValue() { final Map map = new HashMap(); map.put((K) "A", (V) "a"); map.put((K) "B", (V) "b"); map.put((K) "C", (V) "c"); Map.Entry entry = new TiedMapEntry(map, (K) "A"); assertSame("A", entry.getKey()); assertSame("a", entry.getValue()); assertSame("a", entry.setValue((V) "x")); assertSame("A", entry.getKey()); assertSame("x", entry.getValue()); entry = new TiedMapEntry(map, (K) "B"); assertSame("B", entry.getKey()); assertSame("b", entry.getValue()); assertSame("b", entry.setValue((V) "y")); assertSame("B", entry.getKey()); assertSame("y", entry.getValue()); entry = new TiedMapEntry(map, (K) "C"); assertSame("C", entry.getKey()); assertSame("c", entry.getValue()); assertSame("c", entry.setValue((V) "z")); assertSame("C", entry.getKey()); assertSame("z", entry.getValue()); } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/UnmodifiableMapEntryTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/UnmodifiableMapE100664 7114 12243235516 31705 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.util.Map; import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.Unmodifiable; /** * Test the UnmodifiableMapEntry class. * * @since 3.0 * @version $Id: UnmodifiableMapEntryTest.java 1540705 2013-11-11 13:22:32Z ebourg $ */ public class UnmodifiableMapEntryTest extends AbstractMapEntryTest { //----------------------------------------------------------------------- /** * 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. */ @Override 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. */ @Override public Map.Entry makeMapEntry(final K key, final V value) { return new UnmodifiableMapEntry(key, value); } //----------------------------------------------------------------------- /** * Subclasses should override this method. * */ @Override @SuppressWarnings("unchecked") public void testConstructors() { // 1. test key-value constructor Map.Entry entry = new UnmodifiableMapEntry((K) key, (V) value); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); // 2. test pair constructor final KeyValue pair = new DefaultKeyValue((K) key, (V) value); entry = new UnmodifiableMapEntry(pair); assertSame(key, entry.getKey()); assertSame(value, entry.getValue()); // 3. test copy constructor final Map.Entry entry2 = new UnmodifiableMapEntry(entry); assertSame(key, entry2.getKey()); assertSame(value, entry2.getValue()); assertTrue(entry instanceof Unmodifiable); } @Override @SuppressWarnings("unchecked") public void testAccessorsAndMutators() { Map.Entry entry = makeMapEntry((K) key, (V) 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()); } @Override public void testSelfReferenceHandling() { // block } public void testUnmodifiable() { final Map.Entry entry = makeMapEntry(); try { entry.setValue(null); fail(); } catch (final UnsupportedOperationException ex) {} } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.jav100664 23356 12243235516 31754 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; 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.util.Arrays; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; /** * Unit tests for {@link org.apache.commons.collections4.keyvalue.MultiKey}. * * @version $Id: MultiKeyTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class MultiKeyTest extends TestCase { Integer ONE = Integer.valueOf(1); Integer TWO = Integer.valueOf(2); Integer THREE = Integer.valueOf(3); Integer FOUR = Integer.valueOf(4); Integer FIVE = Integer.valueOf(5); @Override public void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } //----------------------------------------------------------------------- public void testConstructors() throws Exception { MultiKey mk; mk = new MultiKey(ONE, TWO); assertTrue(Arrays.equals(new Object[] { ONE, TWO }, mk.getKeys())); mk = new MultiKey(ONE, TWO, THREE); assertTrue(Arrays.equals(new Object[] { ONE, TWO, THREE }, mk.getKeys())); mk = new MultiKey(ONE, TWO, THREE, FOUR); assertTrue(Arrays.equals(new Object[] { ONE, TWO, THREE, FOUR }, mk.getKeys())); mk = new MultiKey(ONE, TWO, THREE, FOUR, FIVE); assertTrue(Arrays.equals(new Object[] { ONE, TWO, THREE, FOUR, FIVE }, mk.getKeys())); mk = new MultiKey(new Integer[] { THREE, FOUR, ONE, TWO }, false); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); } public void testConstructorsByArray() throws Exception { MultiKey mk; Integer[] keys = new Integer[] { THREE, FOUR, ONE, TWO }; mk = new MultiKey(keys); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys[3] = FIVE; // no effect assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys = new Integer[] {}; mk = new MultiKey(keys); assertTrue(Arrays.equals(new Object[] {}, mk.getKeys())); keys = new Integer[] { THREE, FOUR, ONE, TWO }; mk = new MultiKey(keys, true); assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys[3] = FIVE; // no effect assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, TWO }, mk.getKeys())); keys = new Integer[] { THREE, FOUR, ONE, TWO }; mk = new MultiKey(keys, false); 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; assertTrue(Arrays.equals(new Object[] { THREE, FOUR, ONE, FIVE }, mk.getKeys())); } public void testConstructorsByArrayNull() throws Exception { final Integer[] keys = null; try { new MultiKey(keys); fail(); } catch (final IllegalArgumentException ex) {} try { new MultiKey(keys, true); fail(); } catch (final IllegalArgumentException ex) {} try { new MultiKey(keys, false); fail(); } catch (final IllegalArgumentException ex) {} } public void testSize() { assertEquals(2, new MultiKey(ONE, TWO).size()); assertEquals(2, new MultiKey(null, null).size()); assertEquals(3, new MultiKey(ONE, TWO, THREE).size()); assertEquals(3, new MultiKey(null, null, null).size()); assertEquals(4, new MultiKey(ONE, TWO, THREE, FOUR).size()); assertEquals(4, new MultiKey(null, null, null, null).size()); assertEquals(5, new MultiKey(ONE, TWO, THREE, FOUR, FIVE).size()); assertEquals(5, new MultiKey(null, null, null, null, null).size()); assertEquals(0, new MultiKey(new Object[] {}).size()); assertEquals(1, new MultiKey(new Integer[] { ONE }).size()); assertEquals(2, new MultiKey(new Integer[] { ONE, TWO }).size()); assertEquals(7, new MultiKey(new Integer[] { ONE, TWO, ONE, TWO, ONE, TWO, ONE }).size()); } public void testGetIndexed() { final MultiKey mk = new MultiKey(ONE, TWO); assertSame(ONE, mk.getKey(0)); assertSame(TWO, mk.getKey(1)); try { mk.getKey(-1); fail(); } catch (final IndexOutOfBoundsException ex) {} try { mk.getKey(2); fail(); } catch (final IndexOutOfBoundsException ex) {} } public void testGetKeysSimpleConstructor() { final MultiKey mk = new MultiKey(ONE, TWO); final Object[] array = mk.getKeys(); assertSame(ONE, array[0]); assertSame(TWO, array[1]); assertEquals(2, array.length); } public void testGetKeysArrayConstructorCloned() { final Integer[] keys = new Integer[] { ONE, TWO }; final MultiKey mk = new MultiKey(keys, true); final Object[] array = mk.getKeys(); assertTrue(array != keys); assertTrue(Arrays.equals(array, keys)); assertSame(ONE, array[0]); assertSame(TWO, array[1]); assertEquals(2, array.length); } public void testGetKeysArrayConstructorNonCloned() { final Integer[] keys = new Integer[] { ONE, TWO }; final MultiKey mk = new MultiKey(keys, false); final Object[] array = mk.getKeys(); assertTrue(array != keys); // still not equal assertTrue(Arrays.equals(array, keys)); assertSame(ONE, array[0]); assertSame(TWO, array[1]); assertEquals(2, array.length); } public void testHashCode() { final MultiKey mk1 = new MultiKey(ONE, TWO); final MultiKey mk2 = new MultiKey(ONE, TWO); final MultiKey mk3 = new MultiKey(ONE, "TWO"); assertTrue(mk1.hashCode() == mk1.hashCode()); assertTrue(mk1.hashCode() == mk2.hashCode()); assertTrue(mk1.hashCode() != mk3.hashCode()); final int total = (0 ^ ONE.hashCode()) ^ TWO.hashCode(); assertEquals(total, mk1.hashCode()); } public void testEquals() { final MultiKey mk1 = new MultiKey(ONE, TWO); final MultiKey mk2 = new MultiKey(ONE, TWO); final MultiKey mk3 = new MultiKey(ONE, "TWO"); assertEquals(mk1, mk1); assertEquals(mk1, mk2); assertFalse(mk1.equals(mk3)); assertFalse(mk1.equals("")); assertFalse(mk1.equals(null)); } static class SystemHashCodeSimulatingKey implements Serializable { private static final long serialVersionUID = -1736147315703444603L; private final String name; private int hashCode = 1; public SystemHashCodeSimulatingKey(final String name) { this.name = name; } @Override public boolean equals(final Object obj) { return obj instanceof SystemHashCodeSimulatingKey && name.equals(((SystemHashCodeSimulatingKey)obj).name); } @Override public int hashCode() { return hashCode; } private Object readResolve() { hashCode=2; // simulate different hashCode after deserialization in another process return this; } } public void testEqualsAfterSerialization() throws IOException, ClassNotFoundException { SystemHashCodeSimulatingKey sysKey = new SystemHashCodeSimulatingKey("test"); final MultiKey mk = new MultiKey(ONE, sysKey); final Map, Integer> map = new HashMap, Integer>(); map.put(mk, TWO); // serialize final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(sysKey); out.writeObject(map); out.close(); // deserialize final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); final ObjectInputStream in = new ObjectInputStream(bais); sysKey = (SystemHashCodeSimulatingKey)in.readObject(); // simulate deserialization in another process final Map map2 = (Map) in.readObject(); in.close(); assertEquals(2, sysKey.hashCode()); // different hashCode now final MultiKey mk2 = new MultiKey(ONE, sysKey); assertEquals(TWO, map2.get(mk2)); } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/TransformerUtilsTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/TransformerUtilsTest.java100664 50452 12243235516 32045 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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 org.apache.commons.collections4.functors.CloneTransformer; import org.apache.commons.collections4.functors.ConstantTransformer; import org.apache.commons.collections4.functors.EqualPredicate; import org.apache.commons.collections4.functors.ExceptionTransformer; import org.apache.commons.collections4.functors.FalsePredicate; import org.apache.commons.collections4.functors.NOPTransformer; import org.apache.commons.collections4.functors.StringValueTransformer; import org.apache.commons.collections4.functors.TruePredicate; /** * Tests the TransformerUtils class. * * @since 3.0 * @version $Id: TransformerUtilsTest.java 1543964 2013-11-20 21:53:39Z tn $ */ public class TransformerUtilsTest extends junit.framework.TestCase { private static final Object cObject = new Object(); private static final Object cString = "Hello"; private static final Object cInteger = Integer.valueOf(6); /** * Set up instance variables required by this test case. */ @Override public void setUp() { } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { } // exceptionTransformer //------------------------------------------------------------------ public void testExceptionTransformer() { assertNotNull(TransformerUtils.exceptionTransformer()); assertSame(TransformerUtils.exceptionTransformer(), TransformerUtils.exceptionTransformer()); try { TransformerUtils.exceptionTransformer().transform(null); } catch (final FunctorException ex) { try { TransformerUtils.exceptionTransformer().transform(cString); } catch (final 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 (final IllegalArgumentException ex) { return; } fail(); } // mapTransformer //------------------------------------------------------------------ @SuppressWarnings("boxing") // OK in test code public void testMapTransformer() { final Map map = new HashMap(); map.put(null, 0); map.put(cObject, 1); map.put(cString, 2); assertEquals(Integer.valueOf(0), TransformerUtils.mapTransformer(map).transform(null)); assertEquals(Integer.valueOf(1), TransformerUtils.mapTransformer(map).transform(cObject)); assertEquals(Integer.valueOf(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 (final IllegalArgumentException ex) { return; } fail(); } // predicateTransformer //------------------------------------------------------------------ public void testPredicateTransformer() { assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(TruePredicate.truePredicate()).transform(null)); assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(TruePredicate.truePredicate()).transform(cObject)); assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(TruePredicate.truePredicate()).transform(cString)); assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(TruePredicate.truePredicate()).transform(cInteger)); try { TransformerUtils.asTransformer((Predicate) null); } catch (final 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 (final IllegalArgumentException ex) { return; } fail(); } // chainedTransformer //------------------------------------------------------------------ @SuppressWarnings("unchecked") public void testChainedTransformer() { final Transformer a = TransformerUtils.constantTransformer("A"); final Transformer b = TransformerUtils.constantTransformer((Object) "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.>emptyList())); try { TransformerUtils.chainedTransformer(null, null); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.chainedTransformer((Transformer[]) null); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.chainedTransformer((Collection>) null); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.chainedTransformer(new Transformer[] {null, null}); fail(); } catch (final IllegalArgumentException ex) {} try { coll = new ArrayList>(); coll.add(null); coll.add(null); TransformerUtils.chainedTransformer(coll); fail(); } catch (final IllegalArgumentException ex) {} } // switchTransformer //------------------------------------------------------------------ @SuppressWarnings("unchecked") public void testSwitchTransformer() { final Transformer a = TransformerUtils.constantTransformer("A"); final Transformer b = TransformerUtils.constantTransformer("B"); final Transformer c = TransformerUtils.constantTransformer("C"); assertEquals("A", TransformerUtils.switchTransformer(TruePredicate.truePredicate(), a, b).transform(null)); assertEquals("B", TransformerUtils.switchTransformer(FalsePredicate.falsePredicate(), a, b).transform(null)); assertEquals(null, TransformerUtils.switchTransformer( new Predicate[] { EqualPredicate.equalPredicate("HELLO"), EqualPredicate.equalPredicate("THERE") }, new Transformer[] { a, b }).transform("WELL")); assertEquals("A", TransformerUtils.switchTransformer( new Predicate[] { EqualPredicate.equalPredicate("HELLO"), EqualPredicate.equalPredicate("THERE") }, new Transformer[] { a, b }).transform("HELLO")); assertEquals("B", TransformerUtils.switchTransformer( new Predicate[] { EqualPredicate.equalPredicate("HELLO"), EqualPredicate.equalPredicate("THERE") }, new Transformer[] { a, b }).transform("THERE")); assertEquals("C", TransformerUtils.switchTransformer( new Predicate[] { EqualPredicate.equalPredicate("HELLO"), EqualPredicate.equalPredicate("THERE") }, new Transformer[] { a, b }, c).transform("WELL")); Map, Transformer> map = new HashMap, Transformer>(); map.put(EqualPredicate.equalPredicate("HELLO"), a); map.put(EqualPredicate.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")); assertEquals(ConstantTransformer.NULL_INSTANCE, TransformerUtils.switchTransformer(new Predicate[0], new Transformer[0])); assertEquals(ConstantTransformer.NULL_INSTANCE, TransformerUtils.switchTransformer(new HashMap, Transformer>())); map = new HashMap, Transformer>(); map.put(null, null); assertEquals(ConstantTransformer.NULL_INSTANCE, TransformerUtils.switchTransformer(map)); try { TransformerUtils.switchTransformer(null, null); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.switchTransformer((Predicate[]) null, (Transformer[]) null); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.switchTransformer((Map, Transformer>) null); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.switchTransformer(new Predicate[2], new Transformer[2]); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.switchTransformer( new Predicate[] { TruePredicate.truePredicate() }, new Transformer[] { a, b }); fail(); } catch (final IllegalArgumentException ex) {} } // switchMapTransformer //------------------------------------------------------------------ public void testSwitchMapTransformer() { final Transformer a = TransformerUtils.constantTransformer("A"); final Transformer b = TransformerUtils.constantTransformer("B"); final 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 (final IllegalArgumentException ex) {} } // invokerTransformer //------------------------------------------------------------------ public void testInvokerTransformer() { final List list = new ArrayList(); assertEquals(Integer.valueOf(0), TransformerUtils.invokerTransformer("size").transform(list)); list.add(new Object()); assertEquals(Integer.valueOf(1), TransformerUtils.invokerTransformer("size").transform(list)); assertEquals(null, TransformerUtils.invokerTransformer("size").transform(null)); try { TransformerUtils.invokerTransformer(null); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.invokerTransformer("noSuchMethod").transform(new Object()); fail(); } catch (final FunctorException ex) {} } // invokerTransformer2 //------------------------------------------------------------------ public void testInvokerTransformer2() { final 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 (final IllegalArgumentException ex) {} try { TransformerUtils.invokerTransformer("noSuchMethod", new Class[] { Object.class }, new Object[] { cString }).transform(new Object()); fail(); } catch (final FunctorException ex) {} try { TransformerUtils.invokerTransformer("badArgs", null, new Object[] { cString }); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.invokerTransformer("badArgs", new Class[] { Object.class }, null); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.invokerTransformer("badArgs", new Class[] {}, new Object[] { cString }); fail(); } catch (final 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(Integer.valueOf(6))); } // instantiateFactory //------------------------------------------------------------------ public void testInstantiateTransformerNull() { try { TransformerUtils.instantiateTransformer(null, new Object[] { "str" }); fail(); } catch (final IllegalArgumentException ex) {} try { TransformerUtils.instantiateTransformer(new Class[] {}, new Object[] { "str" }); fail(); } catch (final IllegalArgumentException ex) {} Transformer, Object> trans = TransformerUtils.instantiateTransformer(new Class[] { Long.class }, new Object[] { null }); try { trans.transform(String.class); fail(); } catch (final 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)); } // misc tests //------------------------------------------------------------------ /** * Test that all Transformer singletons hold singleton pattern in * serialization/deserialization process. */ public void testSingletonPatternInSerialization() { final Object[] singletones = new Object[] { CloneTransformer.INSTANCE, ExceptionTransformer.INSTANCE, NOPTransformer.INSTANCE, StringValueTransformer.stringValueTransformer(), }; for (final Object original : singletones) { TestUtils.assertSameAfterSerialization("Singleton pattern broken for " + original.getClass(), original); } } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/AbstractArrayListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/AbstractArrayListTest.jav100664 4207 12243235516 31734 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.ArrayList; import org.apache.commons.collections4.list.AbstractListTest; /** * Abstract test class for ArrayList. * * @version $Id: AbstractArrayListTest.java 1469004 2013-04-17 17:37:03Z tn $ */ public abstract class AbstractArrayListTest extends AbstractListTest { public AbstractArrayListTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @Override public abstract ArrayList makeObject(); //----------------------------------------------------------------------- public void testNewArrayList() { final ArrayList list = makeObject(); assertTrue("New list is empty", list.isEmpty()); assertEquals("New list has size zero", 0, list.size()); try { list.get(1); fail("get(int i) should have thrown IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException e) { // Expected result } } @SuppressWarnings("unchecked") public void testSearch() { final ArrayList list = makeObject(); list.add((E) "First Item"); list.add((E) "Last Item"); assertEquals("First item is 'First Item'", "First Item", list.get(0)); assertEquals("Last Item is 'Last Item'", "Last Item", list.get(1)); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/ArrayStackTest.java100664 10323 12243235516 30557 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.EmptyStackException; import junit.framework.Test; /** * Tests ArrayStack. * * @version $Id: ArrayStackTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("deprecation") // we test a deprecated class public class ArrayStackTest extends AbstractArrayListTest { public ArrayStackTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(ArrayStackTest.class); } @Override public ArrayStack makeObject() { return new ArrayStack(); } //----------------------------------------------------------------------- public void testNewStack() { final ArrayStack stack = makeObject(); assertTrue("New stack is empty", stack.empty()); assertEquals("New stack has size zero", 0, stack.size()); try { stack.peek(); fail("peek() should have thrown EmptyStackException"); } catch (final EmptyStackException e) { // Expected result } try { stack.pop(); fail("pop() should have thrown EmptyStackException"); } catch (final EmptyStackException e) { // Expected result } } @SuppressWarnings("unchecked") public void testPushPeekPop() { final ArrayStack stack = makeObject(); stack.push((E) "First Item"); assertTrue("Stack is not empty", !stack.empty()); assertEquals("Stack size is one", 1, stack.size()); assertEquals("Top item is 'First Item'", "First Item", (String) stack.peek()); assertEquals("Stack size is one", 1, stack.size()); stack.push((E) "Second Item"); assertEquals("Stack size is two", 2, stack.size()); assertEquals("Top item is 'Second Item'", "Second Item", (String) stack.peek()); assertEquals("Stack size is two", 2, stack.size()); assertEquals("Popped item is 'Second Item'", "Second Item", (String) stack.pop()); assertEquals("Top item is 'First Item'", "First Item", (String) stack.peek()); assertEquals("Stack size is one", 1, stack.size()); assertEquals("Popped item is 'First Item'", "First Item", (String) stack.pop()); assertEquals("Stack size is zero", 0, stack.size()); } @Override @SuppressWarnings("unchecked") public void testSearch() { final ArrayStack stack = makeObject(); stack.push((E) "First Item"); stack.push((E) "Second Item"); assertEquals("Top item is 'Second Item'", 1, stack.search("Second Item")); assertEquals("Next Item is 'First Item'", 2, stack.search("First Item")); assertEquals("Cannot find 'Missing Item'", -1, stack.search("Missing Item")); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/ArrayStack.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/ArrayStack.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/UnmodifiableSortedBagTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/UnmodifiableSortedBag100664 7046 12243235516 31645 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Arrays; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.SortedBag; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.collection.AbstractCollectionTest; /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link UnmodifiableSortedBag} implementation. * * @since 4.0 * @version $Id: UnmodifiableSortedBagTest.java 1540833 2013-11-11 20:28:22Z tn $ */ public class UnmodifiableSortedBagTest extends AbstractSortedBagTest { public UnmodifiableSortedBagTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(UnmodifiableSortedBagTest.class); } //----------------------------------------------------------------------- @Override public SortedBag makeObject() { return UnmodifiableSortedBag.unmodifiableSortedBag(new TreeBag()); } @Override public SortedBag makeFullCollection() { final SortedBag bag = new TreeBag(); bag.addAll(Arrays.asList(getFullElements())); return UnmodifiableSortedBag.unmodifiableSortedBag(bag); } @Override public SortedBag getCollection() { return super.getCollection(); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public boolean isNullSupported() { return false; } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullCollection() instanceof Unmodifiable); } public void testDecorateFactory() { final SortedBag queue = makeFullCollection(); assertSame(queue, UnmodifiableSortedBag.unmodifiableSortedBag(queue)); try { UnmodifiableSortedBag.unmodifiableSortedBag(null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // SortedBag bag = makeObject(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/UnmodifiableSortedBag.emptyCollection.version4.obj"); // bag = makeFullCollection(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/UnmodifiableSortedBag.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/TransformedSortedBagTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/TransformedSortedBagT100664 7323 12243235516 31655 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import junit.framework.Test; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.SortedBag; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.collection.TransformedCollectionTest; /** * Extension of {@link AbstractSortedBagTest} for exercising the {@link TransformedSortedBag} * implementation. * * @since 3.0 * @version $Id: TransformedSortedBagTest.java 1540833 2013-11-11 20:28:22Z tn $ */ public class TransformedSortedBagTest extends AbstractSortedBagTest { public TransformedSortedBagTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TransformedSortedBagTest.class); } //----------------------------------------------------------------------- @Override @SuppressWarnings("unchecked") public SortedBag makeObject() { return TransformedSortedBag.transformingSortedBag(new TreeBag(), (Transformer) TransformedCollectionTest.NOOP_TRANSFORMER); } @SuppressWarnings("unchecked") public void testTransformedBag() { final SortedBag bag = TransformedSortedBag.transformingSortedBag(new TreeBag(), (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, bag.size()); final Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { bag.add((T) els[i]); assertEquals(i + 1, bag.size()); assertEquals(true, bag.contains(Integer.valueOf((String) els[i]))); } assertEquals(true, bag.remove(Integer.valueOf((String) els[0]))); } public void testTransformedBag_decorateTransform() { final Bag originalBag = new TreeBag(); final Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; for (final Object el : els) { originalBag.add(el); } final Bag bag = TransformedBag.transformedBag(originalBag, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(els.length, bag.size()); for (final Object el : els) { assertEquals(true, bag.contains(Integer.valueOf((String) el))); } assertEquals(true, bag.remove(Integer.valueOf((String) els[0]))); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // Bag bag = makeObject(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/TransformedSortedBag.emptyCollection.version4.obj"); // bag = makeFullCollection(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/TransformedSortedBag.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/CollectionBagTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/CollectionBagTest.jav100664 10306 12243235516 31611 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.collection.AbstractCollectionTest; /** * Test class for {@link CollectionBag}. *

* Note: This test is mainly for serialization support, the CollectionBag decorator * is extensively used and tested in AbstractBagTest. * * @version $Id: CollectionBagTest.java 1543267 2013-11-19 00:49:24Z ggregory $ * @since 4.0 */ public class CollectionBagTest extends AbstractCollectionTest { /** * JUnit constructor. * * @param testName the test class name */ public CollectionBagTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public Bag makeObject() { return CollectionBag.collectionBag(new HashBag()); } /** * Returns an empty List for use in modification testing. * * @return a confirmed empty collection */ @Override public Collection makeConfirmedCollection() { return new ArrayList(); } /** * Returns a full Set for use in modification testing. * * @return a confirmed full collection */ @Override public Collection makeConfirmedFullCollection() { final Collection set = makeConfirmedCollection(); set.addAll(Arrays.asList(getFullElements())); return set; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CollectionBag.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CollectionBag.fullCollection.version4.obj"); // } //----------------------------------------------------------------------- /** * Compare the current serialized form of the Bag * against the canonical version in SVN. */ public void testEmptyBagCompatibility() throws IOException, ClassNotFoundException { // test to make sure the canonical form has been preserved final Bag bag = makeObject(); if (bag instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final 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 SVN. */ public void testFullBagCompatibility() throws IOException, ClassNotFoundException { // test to make sure the canonical form has been preserved final Bag bag = (Bag) makeFullCollection(); if (bag instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final Bag bag2 = (Bag) readExternalFormFromDisk(getCanonicalFullCollectionName(bag)); assertEquals("Bag is the right size",bag.size(), bag2.size()); assertEquals(bag, bag2); } } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/PredicatedSortedBagTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/PredicatedSortedBagTe100664 10125 12243235516 31614 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Comparator; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.SortedBag; import org.apache.commons.collections4.functors.TruePredicate; /** * Extension of {@link AbstractSortedBagTest} for exercising the {@link PredicatedSortedBag} * implementation. * * @since 3.0 * @version $Id: PredicatedSortedBagTest.java 1540833 2013-11-11 20:28:22Z tn $ */ public class PredicatedSortedBagTest extends AbstractSortedBagTest { private final SortedBag nullBag = null; public PredicatedSortedBagTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(PredicatedSortedBagTest.class); } //-------------------------------------------------------------------------- protected Predicate stringPredicate() { return new Predicate() { public boolean evaluate(final T o) { return o instanceof String; } }; } protected Predicate truePredicate = TruePredicate.truePredicate(); protected SortedBag decorateBag(final SortedBag bag, final Predicate predicate) { return PredicatedSortedBag.predicatedSortedBag(bag, predicate); } @Override public SortedBag makeObject() { return decorateBag(new TreeBag(), truePredicate); } protected SortedBag makeTestBag() { return decorateBag(new TreeBag(), stringPredicate()); } //-------------------------------------------------------------------------- public void testDecorate() { final SortedBag bag = decorateBag(new TreeBag(), stringPredicate()); ((PredicatedSortedBag) bag).decorated(); try { decorateBag(new TreeBag(), null); fail("Expecting IllegalArgumentException for null predicate"); } catch (final IllegalArgumentException e) {} try { decorateBag(nullBag, stringPredicate()); fail("Expecting IllegalArgumentException for null bag"); } catch (final IllegalArgumentException e) {} } @SuppressWarnings("unchecked") public void testSortOrder() { final SortedBag bag = decorateBag(new TreeBag(), stringPredicate()); final String one = "one"; final String two = "two"; final String three = "three"; bag.add((T) one); bag.add((T) two); bag.add((T) three); assertEquals("first element", bag.first(), one); assertEquals("last element", bag.last(), two); final Comparator c = bag.comparator(); assertTrue("natural order, so comparator should be null", c == null); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // Bag bag = makeObject(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/PredicatedSortedBag.emptyCollection.version4.obj"); // bag = makeFullCollection(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/PredicatedSortedBag.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/CollectionSortedBagTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/CollectionSortedBagTe100664 12530 12243235516 31645 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.SortedBag; import org.apache.commons.collections4.collection.AbstractCollectionTest; /** * Test class for {@link CollectionSortedBag}. *

* Note: This test is mainly for serialization support, the CollectionSortedBag decorator * is extensively used and tested in AbstractSortedBagTest. * * @version $Id: CollectionSortedBagTest.java 1540833 2013-11-11 20:28:22Z tn $ * @since 4.0 */ public class CollectionSortedBagTest extends AbstractCollectionTest { /** * JUnit constructor. * * @param testName the test class name */ public CollectionSortedBagTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * Overridden because SortedBags don't allow null elements (normally). * @return false */ @Override public boolean isNullSupported() { return false; } @Override public Bag makeObject() { return CollectionSortedBag.collectionSortedBag(new TreeBag()); } /** * Returns an empty List for use in modification testing. * * @return a confirmed empty collection */ @Override public Collection makeConfirmedCollection() { return new ArrayList(); } /** * Returns a full Set for use in modification testing. * * @return a confirmed full collection */ @Override public Collection makeConfirmedFullCollection() { final Collection set = makeConfirmedCollection(); set.addAll(Arrays.asList(getFullElements())); return set; } //----------------------------------------------------------------------- /** * Override to return comparable objects. */ @Override @SuppressWarnings("unchecked") public T[] getFullNonNullElements() { final Object[] elements = new Object[30]; for (int i = 0; i < 30; i++) { elements[i] = Integer.valueOf(i + i + 1); } return (T[]) elements; } /** * Override to return comparable objects. */ @Override @SuppressWarnings("unchecked") public T[] getOtherNonNullElements() { final Object[] elements = new Object[30]; for (int i = 0; i < 30; i++) { elements[i] = Integer.valueOf(i + i + 2); } return (T[]) elements; } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CollectionSortedBag.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CollectionSortedBag.fullCollection.version4.obj"); // } //----------------------------------------------------------------------- /** * Compare the current serialized form of the Bag * against the canonical version in SVN. */ public void testEmptyBagCompatibility() throws IOException, ClassNotFoundException { // test to make sure the canonical form has been preserved final Bag bag = makeObject(); if (bag instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final 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 SVN. */ public void testFullBagCompatibility() throws IOException, ClassNotFoundException { // test to make sure the canonical form has been preserved final SortedBag bag = (SortedBag) makeFullCollection(); if (bag instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final SortedBag bag2 = (SortedBag) readExternalFormFromDisk(getCanonicalFullCollectionName(bag)); assertEquals("Bag is the right size", bag.size(), bag2.size()); assertEquals(bag, bag2); } } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/AbstractBagTest.java100664 56722 12243235516 31436 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.collection.AbstractCollectionTest; import org.apache.commons.collections4.set.AbstractSetTest; /** * Abstract test class for {@link org.apache.commons.collections4.Bag Bag} methods and contracts. *

* To use, simply extend this class, and implement * the {@link #makeObject} 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. *

* Note: The Bag interface does not conform to the Collection interface * so the generic collection tests from AbstractCollectionTest would normally fail. * As a work-around since 4.0, a CollectionBag decorator can be used * to make any Bag implementation comply to the Collection contract. *

* This abstract test class does wrap the concrete bag implementation * with such a decorator, see the overridden {@link #resetEmpty()} and * {@link #resetFull()} methods. *

* In addition to the generic collection tests (prefix testCollection) inherited * from AbstractCollectionTest, there are test methods that test the "normal" Bag * interface (prefix testBag). For Bag specific tests use the {@link #makeObject()} and * {@link #makeFullCollection()} methods instead of {@link #resetEmpty()} and resetFull(), * otherwise the collection will be wrapped by a {@link CollectionBag} decorator. * * @version $Id: AbstractBagTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractBagTest extends AbstractCollectionTest { /** * JUnit constructor. * * @param testName the test class name */ public AbstractBagTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * Returns an empty {@link ArrayList}. */ @Override public Collection makeConfirmedCollection() { final ArrayList list = new ArrayList(); return list; } /** * Returns a full collection. */ @Override public Collection makeConfirmedFullCollection() { final Collection coll = makeConfirmedCollection(); coll.addAll(Arrays.asList(getFullElements())); return coll; } /** * Return a new, empty bag to used for testing. * * @return the bag to be tested */ @Override public abstract Bag makeObject(); /** * {@inheritDoc} */ @Override public Bag makeFullCollection() { final Bag bag = makeObject(); bag.addAll(Arrays.asList(getFullElements())); return bag; } //----------------------------------------------------------------------- @Override public void resetEmpty() { this.setCollection(CollectionBag.collectionBag(makeObject())); this.setConfirmed(makeConfirmedCollection()); } @Override public void resetFull() { this.setCollection(CollectionBag.collectionBag(makeFullCollection())); this.setConfirmed(makeConfirmedFullCollection()); } //----------------------------------------------------------------------- /** * Returns the {@link #collection} field cast to a {@link Bag}. * * @return the collection field as a Bag */ @Override public Bag getCollection() { return (Bag) super.getCollection(); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testBagAdd() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "A"); assertTrue("Should contain 'A'", bag.contains("A")); assertEquals("Should have count of 1", 1, bag.getCount("A")); bag.add((T) "A"); assertTrue("Should contain 'A'", bag.contains("A")); assertEquals("Should have count of 2", 2, bag.getCount("A")); bag.add((T) "B"); assertTrue(bag.contains("A")); assertTrue(bag.contains("B")); } @SuppressWarnings("unchecked") public void testBagEqualsSelf() { final Bag bag = makeObject(); assertTrue(bag.equals(bag)); if (!isAddSupported()) { return; } bag.add((T) "elt"); assertTrue(bag.equals(bag)); bag.add((T) "elt"); // again assertTrue(bag.equals(bag)); bag.add((T) "elt2"); assertTrue(bag.equals(bag)); } @SuppressWarnings("unchecked") public void testBagRemove() { if (!isRemoveSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "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((T) "A"); bag.add((T) "A"); bag.add((T) "A"); bag.add((T) "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")); } @SuppressWarnings("unchecked") public void testBagRemoveAll() { if (!isRemoveSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "A", 2); assertEquals("Should have count of 2", 2, bag.getCount("A")); bag.add((T) "B"); bag.add((T) "C"); assertEquals("Should have count of 4", 4, bag.size()); final 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()); } @SuppressWarnings("unchecked") public void testBagContains() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); 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((T) "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((T) "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((T) "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")); } @SuppressWarnings("unchecked") public void testBagContainsAll() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); final List known = new ArrayList(); final List known1A = new ArrayList(); known1A.add("A"); final List known2A = new ArrayList(); known2A.add("A"); known2A.add("A"); final List known1B = new ArrayList(); known1B.add("B"); final 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((T) "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((T) "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((T) "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((T) "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)); } @SuppressWarnings("unchecked") public void testBagSize() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); assertEquals("Should have 0 total items", 0, bag.size()); bag.add((T) "A"); assertEquals("Should have 1 total items", 1, bag.size()); bag.add((T) "A"); assertEquals("Should have 2 total items", 2, bag.size()); bag.add((T) "A"); assertEquals("Should have 3 total items", 3, bag.size()); bag.add((T) "B"); assertEquals("Should have 4 total items", 4, bag.size()); bag.add((T) "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()); } @SuppressWarnings("unchecked") public void testBagRetainAll() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "A"); bag.add((T) "A"); bag.add((T) "A"); bag.add((T) "B"); bag.add((T) "B"); bag.add((T) "C"); final List retains = new ArrayList(); retains.add("B"); retains.add("C"); bag.retainAll(retains); assertEquals("Should have 2 total items", 2, bag.size()); } @SuppressWarnings("unchecked") public void testBagIterator() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "A"); bag.add((T) "A"); bag.add((T) "B"); assertEquals("Bag should have 3 items", 3, bag.size()); final Iterator i = bag.iterator(); boolean foundA = false; while (i.hasNext()) { final String element = (String) i.next(); // ignore the first A, remove the second via Iterator.remove() if (element.equals("A")) { if (!foundA) { 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")); } @SuppressWarnings("unchecked") public void testBagIteratorFail() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "A"); bag.add((T) "A"); bag.add((T) "B"); final Iterator it = bag.iterator(); it.next(); bag.remove("A"); try { it.next(); fail("Should throw ConcurrentModificationException"); } catch (final ConcurrentModificationException e) { // expected } } @SuppressWarnings("unchecked") public void testBagIteratorFailNoMore() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "A"); bag.add((T) "A"); bag.add((T) "B"); final Iterator it = bag.iterator(); it.next(); it.next(); it.next(); try { it.next(); fail("Should throw NoSuchElementException"); } catch (final NoSuchElementException ex) { // expected } } @SuppressWarnings("unchecked") public void testBagIteratorFailDoubleRemove() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "A"); bag.add((T) "A"); bag.add((T) "B"); final 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 (final IllegalStateException ex) { // expected } assertEquals(2, bag.size()); it.next(); it.remove(); assertEquals(1, bag.size()); } @SuppressWarnings("unchecked") public void testBagIteratorRemoveProtectsInvariants() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "A"); bag.add((T) "A"); assertEquals(2, bag.size()); final 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()); final Iterator it2 = bag.iterator(); assertEquals(false, it2.hasNext()); } @SuppressWarnings("unchecked") public void testBagToArray() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "A"); bag.add((T) "A"); bag.add((T) "B"); bag.add((T) "B"); bag.add((T) "C"); final Object[] array = bag.toArray(); int a = 0, b = 0, c = 0; for (final Object element : array) { a += element.equals("A") ? 1 : 0; b += element.equals("B") ? 1 : 0; c += element.equals("C") ? 1 : 0; } assertEquals(2, a); assertEquals(2, b); assertEquals(1, c); } @SuppressWarnings("unchecked") public void testBagToArrayPopulate() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); bag.add((T) "A"); bag.add((T) "A"); bag.add((T) "B"); bag.add((T) "B"); bag.add((T) "C"); final String[] array = bag.toArray(new String[0]); int a = 0, b = 0, c = 0; for (final String element : array) { a += element.equals("A") ? 1 : 0; b += element.equals("B") ? 1 : 0; c += element.equals("C") ? 1 : 0; } assertEquals(2, a); assertEquals(2, b); assertEquals(1, c); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testBagEquals() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); final Bag bag2 = makeObject(); assertEquals(true, bag.equals(bag2)); bag.add((T) "A"); assertEquals(false, bag.equals(bag2)); bag2.add((T) "A"); assertEquals(true, bag.equals(bag2)); bag.add((T) "A"); bag.add((T) "B"); bag.add((T) "B"); bag.add((T) "C"); bag2.add((T) "A"); bag2.add((T) "B"); bag2.add((T) "B"); bag2.add((T) "C"); assertEquals(true, bag.equals(bag2)); } @SuppressWarnings("unchecked") public void testBagEqualsHashBag() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); final Bag bag2 = new HashBag(); assertEquals(true, bag.equals(bag2)); bag.add((T) "A"); assertEquals(false, bag.equals(bag2)); bag2.add((T) "A"); assertEquals(true, bag.equals(bag2)); bag.add((T) "A"); bag.add((T) "B"); bag.add((T) "B"); bag.add((T) "C"); bag2.add((T) "A"); bag2.add((T) "B"); bag2.add((T) "B"); bag2.add((T) "C"); assertEquals(true, bag.equals(bag2)); } @SuppressWarnings("unchecked") public void testBagHashCode() { if (!isAddSupported()) { return; } final Bag bag = makeObject(); final Bag bag2 = makeObject(); assertEquals(0, bag.hashCode()); assertEquals(0, bag2.hashCode()); assertEquals(bag.hashCode(), bag2.hashCode()); bag.add((T) "A"); bag.add((T) "A"); bag.add((T) "B"); bag.add((T) "B"); bag.add((T) "C"); bag2.add((T) "A"); bag2.add((T) "A"); bag2.add((T) "B"); bag2.add((T) "B"); bag2.add((T) "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()); } //----------------------------------------------------------------------- /** * Bulk test {@link Bag#uniqueSet()}. This method runs through all of * the tests in {@link AbstractSetTest}. * After modification operations, {@link #verify()} is invoked to ensure * that the bag and the other collection views are still valid. * * @return a {@link AbstractSetTest} instance for testing the bag's unique set */ public BulkTest bulkTestBagUniqueSet() { return new TestBagUniqueSet(); } public class TestBagUniqueSet extends AbstractSetTest { public TestBagUniqueSet() { super(""); } @Override public T[] getFullElements() { return AbstractBagTest.this.getFullElements(); } @Override public T[] getOtherElements() { return AbstractBagTest.this.getOtherElements(); } @Override public Set makeObject() { return AbstractBagTest.this.makeObject().uniqueSet(); } @Override public Set makeFullCollection() { return AbstractBagTest.this.makeFullCollection().uniqueSet(); } @Override public boolean isNullSupported() { return AbstractBagTest.this.isNullSupported(); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public boolean isTestSerialization() { return false; } @Override public void resetEmpty() { AbstractBagTest.this.resetEmpty(); TestBagUniqueSet.this.setCollection(AbstractBagTest.this.getCollection().uniqueSet()); TestBagUniqueSet.this.setConfirmed(new HashSet(AbstractBagTest.this.getConfirmed())); } @Override public void resetFull() { AbstractBagTest.this.resetFull(); TestBagUniqueSet.this.setCollection(AbstractBagTest.this.getCollection().uniqueSet()); TestBagUniqueSet.this.setConfirmed(new HashSet(AbstractBagTest.this.getConfirmed())); } @Override public void verify() { super.verify(); } } //----------------------------------------------------------------------- /** * Compare the current serialized form of the Bag * against the canonical version in SVN. */ public void testEmptyBagCompatibility() throws IOException, ClassNotFoundException { // test to make sure the canonical form has been preserved final Bag bag = makeObject(); if (bag instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final 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 SVN. */ public void testFullBagCompatibility() throws IOException, ClassNotFoundException { // test to make sure the canonical form has been preserved final Bag bag = makeFullCollection(); if (bag instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final Bag bag2 = (Bag) readExternalFormFromDisk(getCanonicalFullCollectionName(bag)); assertEquals("Bag is the right size",bag.size(), bag2.size()); assertEquals(bag, bag2); } } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/PredicatedBagTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/PredicatedBagTest.jav100664 11367 12243235516 31572 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Set; import junit.framework.Test; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.TruePredicate; /** * Extension of {@link AbstractBagTest} for exercising the {@link PredicatedBag} * implementation. * * @since 3.0 * @version $Id: PredicatedBagTest.java 1540833 2013-11-11 20:28:22Z tn $ */ public class PredicatedBagTest extends AbstractBagTest { public PredicatedBagTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(PredicatedBagTest.class); } //-------------------------------------------------------------------------- protected Predicate stringPredicate() { return new Predicate() { public boolean evaluate(final T o) { return o instanceof String; } }; } protected Predicate truePredicate = TruePredicate.truePredicate(); protected Bag decorateBag(final HashBag bag, final Predicate predicate) { return PredicatedBag.predicatedBag(bag, predicate); } @Override public Bag makeObject() { return decorateBag(new HashBag(), truePredicate); } protected Bag makeTestBag() { return decorateBag(new HashBag(), stringPredicate()); } //-------------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testlegalAddRemove() { final Bag bag = makeTestBag(); assertEquals(0, bag.size()); final T[] els = (T[]) 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])); } @SuppressWarnings("unchecked") public void testIllegalAdd() { final Bag bag = makeTestBag(); final Integer i = Integer.valueOf(3); try { bag.add((T) i); fail("Integer should fail string predicate."); } catch (final IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !bag.contains(i)); } @SuppressWarnings("unchecked") public void testIllegalDecorate() { final HashBag elements = new HashBag(); elements.add("one"); elements.add("two"); elements.add(Integer.valueOf(3)); elements.add("four"); try { decorateBag((HashBag) elements, stringPredicate()); fail("Bag contains an element that should fail the predicate."); } catch (final IllegalArgumentException e) { // expected } try { decorateBag(new HashBag(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (final IllegalArgumentException e) { // expected } } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // Bag bag = makeObject(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/PredicatedBag.emptyCollection.version4.obj"); // bag = makeFullCollection(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/PredicatedBag.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/UnmodifiableBagTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/UnmodifiableBagTest.j100664 6634 12243235516 31556 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Arrays; import junit.framework.Test; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.collection.AbstractCollectionTest; /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link UnmodifiableBag} implementation. * * @since 4.0 * @version $Id: UnmodifiableBagTest.java 1540833 2013-11-11 20:28:22Z tn $ */ public class UnmodifiableBagTest extends AbstractBagTest { public UnmodifiableBagTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(UnmodifiableBagTest.class); } //----------------------------------------------------------------------- @Override public Bag makeObject() { return UnmodifiableBag.unmodifiableBag(new HashBag()); } @Override public Bag makeFullCollection() { final Bag bag = new HashBag(); bag.addAll(Arrays.asList(getFullElements())); return UnmodifiableBag.unmodifiableBag(bag); } @Override public Bag getCollection() { return super.getCollection(); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public boolean isNullSupported() { return false; } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullCollection() instanceof Unmodifiable); } public void testDecorateFactory() { final Bag queue = makeFullCollection(); assertSame(queue, UnmodifiableBag.unmodifiableBag(queue)); try { UnmodifiableBag.unmodifiableBag(null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // Bag bag = makeObject(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/UnmodifiableBag.emptyCollection.version4.obj"); // bag = makeFullCollection(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/UnmodifiableBag.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/SynchronizedBagTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/SynchronizedBagTest.j100664 4125 12243235516 31630 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import junit.framework.Test; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.BulkTest; /** * Extension of {@link AbstractBagTest} for exercising the {@link SynchronizedBag} * implementation. * * @since 4.0 * @version $Id: SynchronizedBagTest.java 1540833 2013-11-11 20:28:22Z tn $ */ public class SynchronizedBagTest extends AbstractBagTest { public SynchronizedBagTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(SynchronizedBagTest.class); } //----------------------------------------------------------------------- @Override public Bag makeObject() { return SynchronizedBag.synchronizedBag(new HashBag()); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // Bag bag = makeObject(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/SynchronizedBag.emptyCollection.version4.obj"); // bag = makeFullCollection(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/SynchronizedBag.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/AbstractSortedBagTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/AbstractSortedBagTest100664 11524 12243235516 31666 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Iterator; import org.apache.commons.collections4.SortedBag; /** * Abstract test class for * {@link org.apache.commons.collections4.SortedBag SortedBag} * methods and contracts. * * @since 3.0 * @version $Id: AbstractSortedBagTest.java 1540833 2013-11-11 20:28:22Z tn $ */ public abstract class AbstractSortedBagTest extends AbstractBagTest { public AbstractSortedBagTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * Verification extension, will check the order of elements, * the sets should already be verified equal. */ @Override public void verify() { super.verify(); // Check that iterator returns elements in order and first() and last() // are consistent final Iterator colliter = getCollection().iterator(); final Iterator confiter = getConfirmed().iterator(); T first = null; T 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 (getCollection().size() > 0) { assertEquals("Incorrect element returned by first().", first, getCollection().first()); assertEquals("Incorrect element returned by last().", last, getCollection().last()); } } //----------------------------------------------------------------------- /** * Overridden because SortedBags don't allow null elements (normally). * @return false */ @Override public boolean isNullSupported() { return false; } /** * {@inheritDoc} */ @Override public abstract SortedBag makeObject(); /** * {@inheritDoc} */ @Override public SortedBag makeFullCollection() { return (SortedBag) super.makeFullCollection(); } /** * Returns an empty {@link TreeBag} for use in modification testing. * * @return a confirmed empty collection */ @Override public SortedBag makeConfirmedCollection() { return new TreeBag(); } //----------------------------------------------------------------------- @Override public void resetEmpty() { this.setCollection(CollectionSortedBag.collectionSortedBag(makeObject())); this.setConfirmed(makeConfirmedCollection()); } @Override public void resetFull() { this.setCollection(CollectionSortedBag.collectionSortedBag(makeFullCollection())); this.setConfirmed(makeConfirmedFullCollection()); } //----------------------------------------------------------------------- /** * Override to return comparable objects. */ @Override @SuppressWarnings("unchecked") public T[] getFullNonNullElements() { final Object[] elements = new Object[30]; for (int i = 0; i < 30; i++) { elements[i] = Integer.valueOf(i + i + 1); } return (T[]) elements; } /** * Override to return comparable objects. */ @Override @SuppressWarnings("unchecked") public T[] getOtherNonNullElements() { final Object[] elements = new Object[30]; for (int i = 0; i < 30; i++) { elements[i] = Integer.valueOf(i + i + 2); } return (T[]) elements; } //----------------------------------------------------------------------- /** * Returns the {@link #collection} field cast to a {@link SortedBag}. * * @return the collection field as a SortedBag */ @Override public SortedBag getCollection() { return (SortedBag) super.getCollection(); } //----------------------------------------------------------------------- // TODO: Add the SortedBag tests! } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/TreeBagTest.java100664 6071 12243235516 30542 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import junit.framework.Test; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.SortedBag; /** * Extension of {@link AbstractBagTest} for exercising the {@link TreeBag} * implementation. * * @version $Id: TreeBagTest.java 1540833 2013-11-11 20:28:22Z tn $ */ public class TreeBagTest extends AbstractSortedBagTest { public TreeBagTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TreeBagTest.class); } //----------------------------------------------------------------------- @Override public SortedBag makeObject() { return new TreeBag(); } @SuppressWarnings("unchecked") public SortedBag setupBag() { final SortedBag bag = makeObject(); bag.add((T) "C"); bag.add((T) "A"); bag.add((T) "B"); bag.add((T) "D"); return bag; } public void testCollections265() { final Bag bag = new TreeBag(); try { bag.add(new Object()); fail("IllegalArgumentException expected"); } catch(final IllegalArgumentException iae) { // expected; } } public void testOrdering() { final 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()); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // Bag bag = makeObject(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/TreeBag.emptyCollection.version4.obj"); // bag = makeFullCollection(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/TreeBag.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/TransformedBagTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/TransformedBagTest.ja100664 7625 12243235516 31606 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import junit.framework.Test; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.collection.TransformedCollectionTest; /** * Extension of {@link AbstractBagTest} for exercising the {@link TransformedBag} * implementation. * * @since 3.0 * @version $Id: TransformedBagTest.java 1540833 2013-11-11 20:28:22Z tn $ */ public class TransformedBagTest extends AbstractBagTest { public TransformedBagTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TransformedBagTest.class); } //----------------------------------------------------------------------- @Override @SuppressWarnings("unchecked") public Bag makeObject() { return TransformedBag.transformingBag(new HashBag(), (Transformer) TransformedCollectionTest.NOOP_TRANSFORMER); } @SuppressWarnings("unchecked") public void testTransformedBag() { //T had better be Object! final Bag bag = TransformedBag.transformingBag(new HashBag(), (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, bag.size()); final Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; for (int i = 0; i < els.length; i++) { bag.add((T) els[i]); assertEquals(i + 1, bag.size()); assertEquals(true, bag.contains(Integer.valueOf((String) els[i]))); assertEquals(false, bag.contains(els[i])); } assertEquals(false, bag.remove(els[0])); assertEquals(true, bag.remove(Integer.valueOf((String) els[0]))); } @SuppressWarnings("unchecked") public void testTransformedBag_decorateTransform() { final Bag originalBag = new HashBag(); final Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; for (final Object el : els) { originalBag.add((T) el); } final Bag bag = TransformedBag.transformedBag(originalBag, (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(els.length, bag.size()); for (final Object el : els) { assertEquals(true, bag.contains(Integer.valueOf((String) el))); assertEquals(false, bag.contains(el)); } assertEquals(false, bag.remove(els[0])); assertEquals(true, bag.remove(Integer.valueOf((String) els[0]))); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // Bag bag = makeObject(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/TransformedBag.emptyCollection.version4.obj"); // bag = makeFullCollection(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/TransformedBag.fullCollection.version4.obj"); // } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bag/HashBagTest.java100664 3755 12243235516 30534 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import junit.framework.Test; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.BulkTest; /** * Extension of {@link AbstractBagTest} for exercising the {@link HashBag} * implementation. * * @version $Id: HashBagTest.java 1540833 2013-11-11 20:28:22Z tn $ */ public class HashBagTest extends AbstractBagTest { public HashBagTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(HashBagTest.class); } //----------------------------------------------------------------------- @Override public Bag makeObject() { return new HashBag(); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // Bag bag = makeObject(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/HashBag.emptyCollection.version4.obj"); // bag = makeFullCollection(); // writeExternalFormToDisk((java.io.Serializable) bag, "src/test/resources/data/test/HashBag.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/MultiValueMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/MultiValueMapTest.jav100664 40632 12243235516 31662 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 org.apache.commons.collections4.AbstractObjectTest; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.collections4.MultiMap; /** * TestMultiValueMap. * * @since 3.2 * @version $Id: MultiValueMapTest.java 1543964 2013-11-20 21:53:39Z tn $ */ public class MultiValueMapTest extends AbstractObjectTest { public MultiValueMapTest(final String testName) { super(testName); } public void testNoMappingReturnsNull() { final MultiValueMap map = createTestMap(); assertNull(map.get("whatever")); } @SuppressWarnings("unchecked") public void testValueCollectionType() { final MultiValueMap map = createTestMap(LinkedList.class); assertTrue(map.get("one") instanceof LinkedList); } @SuppressWarnings("unchecked") public void testMultipleValues() { final MultiValueMap map = createTestMap(HashSet.class); final HashSet expected = new HashSet(); expected.add((V) "uno"); expected.add((V) "un"); assertEquals(expected, map.get("one")); } @SuppressWarnings("unchecked") 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")); } @SuppressWarnings("unchecked") 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")); } @SuppressWarnings("unchecked") public void testValues() { final MultiValueMap map = createTestMap(HashSet.class); final HashSet expected = new HashSet(); expected.add((V) "uno"); expected.add((V) "dos"); expected.add((V) "tres"); expected.add((V) "un"); expected.add((V) "deux"); expected.add((V) "trois"); final Collection c = map.values(); assertEquals(6, c.size()); assertEquals(expected, new HashSet(c)); } @SuppressWarnings("unchecked") private MultiValueMap createTestMap() { return createTestMap(ArrayList.class); } @SuppressWarnings("unchecked") private > MultiValueMap createTestMap(final Class collectionClass) { final MultiValueMap map = MultiValueMap.multiValueMap(new HashMap(), collectionClass); map.put((K) "one", (V) "uno"); map.put((K) "one", (V) "un"); map.put((K) "two", (V) "dos"); map.put((K) "two", (V) "deux"); map.put((K) "three", (V) "tres"); map.put((K) "three", (V) "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("uno", "un")); assertEquals(expected, actual); } public void testRemoveAllViaIterator() { final MultiValueMap map = createTestMap(); for (final 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 (final Iterator i = map.iterator("one"); i.hasNext();) { i.next(); i.remove(); } assertNull(map.get("one")); assertEquals(4, map.totalSize()); } public void testIterator() { final MultiValueMap map = createTestMap(); @SuppressWarnings("unchecked") Collection values = new ArrayList((Collection) map.values()); Iterator> iterator = map.iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); assertTrue(map.containsValue(entry.getKey(), entry.getValue())); assertTrue(values.contains(entry.getValue())); assertTrue(values.remove(entry.getValue())); } assertTrue(values.isEmpty()); } public void testRemoveAllViaEntryIterator() { final MultiValueMap map = createTestMap(); for (final Iterator i = map.iterator(); i.hasNext();) { i.next(); i.remove(); } assertNull(map.get("one")); assertEquals(0, map.totalSize()); } public void testTotalSizeA() { assertEquals(6, createTestMap().totalSize()); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testMapEquals() { final MultiValueMap one = new MultiValueMap(); final Integer value = Integer.valueOf(1); one.put((K) "One", value); one.removeMapping("One", value); final MultiValueMap two = new MultiValueMap(); assertEquals(two, one); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testGetCollection() { final MultiValueMap map = new MultiValueMap(); map.put((K) "A", "AA"); assertSame(map.get("A"), map.getCollection("A")); } @SuppressWarnings("unchecked") public void testTotalSize() { final MultiValueMap map = new MultiValueMap(); assertEquals(0, map.totalSize()); map.put((K) "A", "AA"); assertEquals(1, map.totalSize()); map.put((K) "B", "BA"); assertEquals(2, map.totalSize()); map.put((K) "B", "BB"); assertEquals(3, map.totalSize()); map.put((K) "B", "BC"); assertEquals(4, map.totalSize()); map.remove("A"); assertEquals(3, map.totalSize()); map.removeMapping("B", "BC"); assertEquals(2, map.totalSize()); } @SuppressWarnings("unchecked") public void testSize() { final MultiValueMap map = new MultiValueMap(); assertEquals(0, map.size()); map.put((K) "A", "AA"); assertEquals(1, map.size()); map.put((K) "B", "BA"); assertEquals(2, map.size()); map.put((K) "B", "BB"); assertEquals(2, map.size()); map.put((K) "B", "BC"); assertEquals(2, map.size()); map.remove("A"); assertEquals(1, map.size()); map.removeMapping("B", "BC"); assertEquals(1, map.size()); } @SuppressWarnings("unchecked") public void testSize_Key() { final MultiValueMap map = new MultiValueMap(); assertEquals(0, map.size("A")); assertEquals(0, map.size("B")); map.put((K) "A", "AA"); assertEquals(1, map.size("A")); assertEquals(0, map.size("B")); map.put((K) "B", "BA"); assertEquals(1, map.size("A")); assertEquals(1, map.size("B")); map.put((K) "B", "BB"); assertEquals(1, map.size("A")); assertEquals(2, map.size("B")); map.put((K) "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.removeMapping("B", "BC"); assertEquals(0, map.size("A")); assertEquals(2, map.size("B")); } @SuppressWarnings("unchecked") public void testIterator_Key() { final MultiValueMap map = new MultiValueMap(); assertEquals(false, map.iterator("A").hasNext()); map.put((K) "A", "AA"); final Iterator it = map.iterator("A"); assertEquals(true, it.hasNext()); it.next(); assertEquals(false, it.hasNext()); } @SuppressWarnings("unchecked") public void testContainsValue_Key() { final MultiValueMap map = new MultiValueMap(); assertEquals(false, map.containsValue("A", "AA")); assertEquals(false, map.containsValue("B", "BB")); map.put((K) "A", "AA"); assertEquals(true, map.containsValue("A", "AA")); assertEquals(false, map.containsValue("A", "AB")); } @SuppressWarnings("unchecked") public void testPutWithList() { @SuppressWarnings("rawtypes") final MultiValueMap test = MultiValueMap.multiValueMap(new HashMap(), ArrayList.class); assertEquals("a", test.put((K) "A", "a")); assertEquals("b", test.put((K) "A", "b")); assertEquals(1, test.size()); assertEquals(2, test.size("A")); assertEquals(2, test.totalSize()); } @SuppressWarnings("unchecked") public void testPutWithSet() { @SuppressWarnings("rawtypes") final MultiValueMap test = MultiValueMap.multiValueMap(new HashMap(), HashSet.class); assertEquals("a", test.put((K) "A", "a")); assertEquals("b", test.put((K) "A", "b")); assertEquals(null, test.put((K) "A", "a")); assertEquals(1, test.size()); assertEquals(2, test.size("A")); assertEquals(2, test.totalSize()); } @SuppressWarnings("unchecked") public void testPutAll_Map1() { final MultiMap original = new MultiValueMap(); original.put((K) "key", "object1"); original.put((K) "key", "object2"); final MultiValueMap test = new MultiValueMap(); test.put((K) "keyA", "objectA"); test.put((K) "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")); } @SuppressWarnings("unchecked") public void testPutAll_Map2() { final Map original = new HashMap(); original.put((K) "keyX", (V) "object1"); original.put((K) "keyY", (V) "object2"); final MultiValueMap test = new MultiValueMap(); test.put((K) "keyA", "objectA"); test.put((K) "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")); } @SuppressWarnings("unchecked") public void testPutAll_KeyCollection() { final MultiValueMap map = new MultiValueMap(); Collection coll = (Collection) Arrays.asList("X", "Y", "Z"); assertEquals(true, map.putAll((K) "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((K) "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((K) "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 = (Collection) Arrays.asList("M"); assertEquals(true, map.putAll((K) "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")); } @SuppressWarnings("unchecked") public void testRemove_KeyItem() { final MultiValueMap map = new MultiValueMap(); map.put((K) "A", "AA"); map.put((K) "A", "AB"); map.put((K) "A", "AC"); assertEquals(false, map.removeMapping("C", "CA")); assertEquals(false, map.removeMapping("A", "AD")); assertEquals(true, map.removeMapping("A", "AC")); assertEquals(true, map.removeMapping("A", "AB")); assertEquals(true, map.removeMapping("A", "AA")); assertEquals(new MultiValueMap(), map); } //----------------------------------------------------------------------- // Manual serialization testing as this class cannot easily // extend the AbstractTestMap //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } @Override public Object makeObject() { @SuppressWarnings("unchecked") final Map m = makeEmptyMap(); m.put("a", "1"); m.put("a", "1b"); m.put("b", "2"); m.put("c", "3"); m.put("c", "3b"); m.put("d", "4"); return m; } @SuppressWarnings("rawtypes") private Map makeEmptyMap() { return new MultiValueMap(); } public void testEmptyMapCompatibility() throws Exception { final Map map = makeEmptyMap(); final Map map2 = (Map) readExternalFormFromDisk(getCanonicalEmptyCollectionName(map)); assertEquals("Map is empty", 0, map2.size()); } public void testFullMapCompatibility() throws Exception { final Map map = (Map) makeObject(); final Map map2 = (Map) readExternalFormFromDisk(getCanonicalFullCollectionName(map)); assertEquals("Map is the right size", map.size(), map2.size()); for (final Object key : map.keySet()) { assertEquals( "Map had inequal elements", map.get(key), map2.get(key) ); map2.remove(key); } assertEquals("Map had extra values", 0, map2.size()); } // public void testCreate() throws Exception { // writeExternalFormToDisk( // (java.io.Serializable) makeEmptyMap(), // "src/test/resources/data/test/MultiValueMap.emptyCollection.version4.obj"); // // writeExternalFormToDisk( // (java.io.Serializable) makeObject(), // "src/test/resources/data/test/MultiValueMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/TransformedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/TransformedMapTest.ja100664 14427 12243235516 31674 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.TransformerUtils; import org.apache.commons.collections4.collection.TransformedCollectionTest; /** * Extension of {@link AbstractMapTest} for exercising the {@link TransformedMap} * implementation. * * @since 3.0 * @version $Id: TransformedMapTest.java 1543964 2013-11-20 21:53:39Z tn $ */ public class TransformedMapTest extends AbstractIterableMapTest { public TransformedMapTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public IterableMap makeObject() { return TransformedMap.transformingMap(new HashMap(), TransformerUtils. nopTransformer(), TransformerUtils. nopTransformer()); } //----------------------------------------------------------------------- @SuppressWarnings({ "unchecked", "rawtypes" }) public void testTransformedMap() { final Object[] els = new Object[] { "1", "3", "5", "7", "2", "4", "6" }; Map map = TransformedMap .transformingMap( new HashMap(), (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER, null); assertEquals(0, map.size()); for (int i = 0; i < els.length; i++) { map.put((K) els[i], (V) els[i]); assertEquals(i + 1, map.size()); assertEquals(true, map.containsKey(Integer.valueOf((String) els[i]))); assertEquals(false, map.containsKey(els[i])); assertEquals(true, map.containsValue(els[i])); assertEquals(els[i], map.get(Integer.valueOf((String) els[i]))); } assertEquals(null, map.remove(els[0])); assertEquals(els[0], map.remove(Integer.valueOf((String) els[0]))); map = TransformedMap.transformingMap(new HashMap(), null, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, map.size()); for (int i = 0; i < els.length; i++) { map.put((K) els[i], (V) els[i]); assertEquals(i + 1, map.size()); assertEquals(true, map.containsValue(Integer.valueOf((String) els[i]))); assertEquals(false, map.containsValue(els[i])); assertEquals(true, map.containsKey(els[i])); assertEquals(Integer.valueOf((String) els[i]), map.get(els[i])); } assertEquals(Integer.valueOf((String) els[0]), map.remove(els[0])); final Set> entrySet = map.entrySet(); final Map.Entry[] array = entrySet.toArray(new Map.Entry[0]); array[0].setValue((V) "66"); assertEquals(Integer.valueOf(66), array[0].getValue()); assertEquals(Integer.valueOf(66), map.get(array[0].getKey())); final Map.Entry entry = entrySet.iterator().next(); entry.setValue((V) "88"); assertEquals(Integer.valueOf(88), entry.getValue()); assertEquals(Integer.valueOf(88), map.get(entry.getKey())); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testFactory_Decorate() { final Map base = new HashMap(); base.put((K) "A", (V) "1"); base.put((K) "B", (V) "2"); base.put((K) "C", (V) "3"); final Map trans = TransformedMap .transformingMap( base, null, (Transformer) TransformedCollectionTest.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((K) "D", (V) "4"); assertEquals(Integer.valueOf(4), trans.get("D")); } @SuppressWarnings("unchecked") public void testFactory_decorateTransform() { final Map base = new HashMap(); base.put((K) "A", (V) "1"); base.put((K) "B", (V) "2"); base.put((K) "C", (V) "3"); final Map trans = TransformedMap .transformedMap( base, null, (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(3, trans.size()); assertEquals(Integer.valueOf(1), trans.get("A")); assertEquals(Integer.valueOf(2), trans.get("B")); assertEquals(Integer.valueOf(3), trans.get("C")); trans.put((K) "D", (V) "4"); assertEquals(Integer.valueOf(4), trans.get("D")); } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/TransformedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/TransformedMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/PredicatedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/PredicatedMapTest.jav100664 11706 12243235516 31637 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.TruePredicate; /** * Extension of {@link AbstractMapTest} for exercising the * {@link PredicatedMap} implementation. * * @since 3.0 * @version $Id: PredicatedMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class PredicatedMapTest extends AbstractIterableMapTest { protected static final Predicate truePredicate = TruePredicate.truePredicate(); protected static final Predicate testPredicate = new Predicate() { public boolean evaluate(final Object o) { return o instanceof String; } }; public PredicatedMapTest(final String testName) { super(testName); } //----------------------------------------------------------------------- protected IterableMap decorateMap(final Map map, final Predicate keyPredicate, final Predicate valuePredicate) { return PredicatedMap.predicatedMap(map, keyPredicate, valuePredicate); } @Override public IterableMap makeObject() { return decorateMap(new HashMap(), truePredicate, truePredicate); } public IterableMap makeTestMap() { return decorateMap(new HashMap(), testPredicate, testPredicate); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testEntrySet() { Map map = makeTestMap(); assertTrue("returned entryset should not be null", map.entrySet() != null); map = decorateMap(new HashMap(), null, null); map.put((K) "oneKey", (V) "oneValue"); assertTrue("returned entryset should contain one entry", map.entrySet().size() == 1); map = decorateMap(map, null, null); } @SuppressWarnings("unchecked") public void testPut() { final Map map = makeTestMap(); try { map.put((K) "Hi", (V) Integer.valueOf(3)); fail("Illegal value should raise IllegalArgument"); } catch (final IllegalArgumentException e) { // expected } try { map.put((K) Integer.valueOf(3), (V) "Hi"); fail("Illegal key should raise IllegalArgument"); } catch (final IllegalArgumentException e) { // expected } assertTrue(!map.containsKey(Integer.valueOf(3))); assertTrue(!map.containsValue(Integer.valueOf(3))); final Map map2 = new HashMap(); map2.put((K) "A", (V) "a"); map2.put((K) "B", (V) "b"); map2.put((K) "C", (V) "c"); map2.put((K) "c", (V) Integer.valueOf(3)); try { map.putAll(map2); fail("Illegal value should raise IllegalArgument"); } catch (final IllegalArgumentException e) { // expected } map.put((K) "E", (V) "e"); Iterator> iterator = map.entrySet().iterator(); try { final Map.Entry entry = iterator.next(); entry.setValue((V) Integer.valueOf(3)); fail("Illegal value should raise IllegalArgument"); } catch (final IllegalArgumentException e) { // expected } map.put((K) "F", (V) "f"); iterator = map.entrySet().iterator(); final Map.Entry entry = iterator.next(); entry.setValue((V) "x"); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/PredicatedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/PredicatedMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/UnmodifiableMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/UnmodifiableMapTest.j100664 6226 12243235516 31623 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.Unmodifiable; /** * Extension of {@link AbstractMapTest} for exercising the * {@link UnmodifiableMap} implementation. * * @since 3.0 * @version $Id: UnmodifiableMapTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class UnmodifiableMapTest extends AbstractIterableMapTest { public UnmodifiableMapTest(final String testName) { super(testName); } //------------------------------------------------------------------- @Override public IterableMap makeObject() { return (IterableMap) UnmodifiableMap.unmodifiableMap(new HashMap()); } @Override public boolean isPutChangeSupported() { return false; } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public IterableMap makeFullMap() { final Map m = new HashMap(); addSampleMappings(m); return (IterableMap) UnmodifiableMap.unmodifiableMap(m); } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { final Map map = makeFullMap(); assertSame(map, UnmodifiableMap.unmodifiableMap(map)); try { UnmodifiableMap.unmodifiableMap(null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/UnmodifiableMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/UnmodifiableMap.fullCollection.version4.obj"); // } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/MultiKeyMapTest.java100664 55260 12243235516 31502 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.keyvalue.MultiKey; /** * JUnit tests. * * @version $Id: MultiKeyMapTest.java 1542782 2013-11-17 18:27:12Z tn $ */ public class MultiKeyMapTest extends AbstractIterableMapTest, V> { static final Integer I1 = Integer.valueOf(1); static final Integer I2 = Integer.valueOf(2); static final Integer I3 = Integer.valueOf(3); static final Integer I4 = Integer.valueOf(4); static final Integer I5 = Integer.valueOf(5); static final Integer I6 = Integer.valueOf(6); static final Integer I7 = Integer.valueOf(7); static final Integer I8 = Integer.valueOf(8); public MultiKeyMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(MultiKeyMapTest.class); } @Override public MultiKeyMap makeObject() { return new MultiKeyMap(); } @Override public MultiKey[] getSampleKeys() { return getMultiKeyKeys(); } @SuppressWarnings("unchecked") 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), }; } @Override @SuppressWarnings("unchecked") public V[] getSampleValues() { return (V[]) new Object[] { "2A", "2B", "2C", "3D", "3E", "3F", "4G", "4H", "4I", "5J", "5K", "5L", }; } @Override @SuppressWarnings("unchecked") public V[] getNewSampleValues() { return (V[]) new Object[] { "1a", "1b", "1c", "2d", "2e", "2f", "3g", "3h", "3i", "4j", "4k", "4l", }; } @Override @SuppressWarnings("unchecked") public MultiKey[] getOtherKeys() { return new MultiKey[] { new MultiKey(I1, I7), new MultiKey(I1, I8), new MultiKey(I2, I4), new MultiKey(I2, I5), }; } @Override public boolean isAllowNullKey() { return false; } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") 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 (final NullPointerException ex) {} assertEquals(null, map.put(new MultiKey(null, null), null)); try { map.put(null, (V) new Object()); fail(); } catch (final NullPointerException ex) {} } //----------------------------------------------------------------------- public void testMultiKeyGet() { resetFull(); final MultiKeyMap multimap = getMap(); final MultiKey[] keys = getMultiKeyKeys(); final V[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { final MultiKey key = keys[i]; final V 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(); final MultiKeyMap multimap = getMap(); final MultiKey[] keys = getMultiKeyKeys(); for (final MultiKey key : keys) { 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() { final MultiKey[] keys = getMultiKeyKeys(); final V[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { final MultiKeyMap multimap = new MultiKeyMap(); final MultiKey key = keys[i]; final V 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() { final MultiKey[] keys = getMultiKeyKeys(); final V[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { resetFull(); final MultiKeyMap multimap = getMap(); final int size = multimap.size(); final MultiKey key = keys[i]; final V value = values[i]; switch (key.size()) { case 2: assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); assertEquals(value, multimap.removeMultiKey(key.getKey(0), key.getKey(1))); assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1))); assertEquals(size - 1, multimap.size()); assertEquals(null, multimap.removeMultiKey(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.removeMultiKey(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.removeMultiKey(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.removeMultiKey(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.removeMultiKey(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.removeMultiKey(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.removeMultiKey(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(); final MultiKeyMap multimap = getMap(); assertEquals(12, multimap.size()); multimap.removeAll(I1); assertEquals(8, multimap.size()); for (final MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { final MultiKey key = it.next(); assertEquals(false, I1.equals(key.getKey(0))); } } public void testMultiKeyRemoveAll2() { resetFull(); final MultiKeyMap multimap = getMap(); assertEquals(12, multimap.size()); multimap.removeAll(I2, I3); assertEquals(9, multimap.size()); for (final MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { final MultiKey key = it.next(); assertEquals(false, I2.equals(key.getKey(0)) && I3.equals(key.getKey(1))); } } public void testMultiKeyRemoveAll3() { resetFull(); final MultiKeyMap multimap = getMap(); assertEquals(12, multimap.size()); multimap.removeAll(I1, I1, I2); assertEquals(9, multimap.size()); for (final MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { final MultiKey key = it.next(); assertEquals(false, I1.equals(key.getKey(0)) && I1.equals(key.getKey(1)) && I2.equals(key.getKey(2))); } } public void testMultiKeyRemoveAll4() { resetFull(); final MultiKeyMap multimap = getMap(); assertEquals(12, multimap.size()); multimap.removeAll(I1, I1, I2, I3); assertEquals(10, multimap.size()); for (final MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { final MultiKey key = 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))); } } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testClone() { final MultiKeyMap map = new MultiKeyMap(); map.put(new MultiKey((K) I1, (K) I2), (V) "1-2"); final Map, V> cloned = map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get(new MultiKey((K) I1, (K) I2)), cloned.get(new MultiKey((K) I1, (K) I2))); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testLRUMultiKeyMap() { final MultiKeyMap map = MultiKeyMap.multiKeyMap(new LRUMap, V>(2)); map.put((K) I1, (K) I2, (V) "1-2"); map.put((K) I1, (K) I3, (V) "1-1"); assertEquals(2, map.size()); map.put((K) I1, (K) I4, (V) "1-4"); assertEquals(2, map.size()); assertEquals(true, map.containsKey(I1, I3)); assertEquals(true, map.containsKey(I1, I4)); assertEquals(false, map.containsKey(I1, I2)); final MultiKeyMap cloned = 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((K) I1, (K) I5, (V) "1-5"); assertEquals(2, cloned.size()); assertEquals(true, cloned.containsKey(I1, I4)); assertEquals(true, cloned.containsKey(I1, I5)); } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/MultiKeyMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/MultiKeyMap.fullCollection.version4.obj"); // } /** * {@inheritDoc} */ @Override public MultiKeyMap getMap() { return (MultiKeyMap) super.getMap(); } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/ReferenceIdentityMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/ReferenceIdentityMapT100664 30041 12243235516 31701 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.lang.ref.WeakReference; import java.util.Iterator; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength; /** * Tests for ReferenceIdentityMap. * * @version $Id: ReferenceIdentityMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ReferenceIdentityMapTest extends AbstractIterableMapTest { private static final Integer I1A = new Integer(1); // Cannot use valueOf here 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 ReferenceIdentityMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(ReferenceIdentityMapTest.class); } @Override public ReferenceIdentityMap makeObject() { return new ReferenceIdentityMap(ReferenceStrength.WEAK, ReferenceStrength.WEAK); } @Override public Map makeConfirmedMap() { // Testing against another [collections] class generally isn't a good idea, // but the closest alternative is IdentityHashMap, which propagates reference-equality down to keySet and values. // arguably ReferenceIdentityMap should do the same but that's a later discussion. return new IdentityMap(); } @Override public boolean isAllowNullKey() { return false; } @Override public boolean isAllowNullValue() { return false; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/ReferenceIdentityMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/ReferenceIdentityMap.fullCollection.version4.obj"); // } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testBasics() { final IterableMap map = new ReferenceIdentityMap(ReferenceStrength.HARD, ReferenceStrength.HARD); assertEquals(0, map.size()); map.put((K) I1A, (V) 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((K) I1A, (V) 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((K) I1B, (V) 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)); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testHashEntry() { final IterableMap map = new ReferenceIdentityMap(ReferenceStrength.HARD, ReferenceStrength.HARD); map.put((K) I1A, (V) I2A); map.put((K) I1B, (V) I2A); final Map.Entry entry1 = map.entrySet().iterator().next(); final Iterator> it = map.entrySet().iterator(); final Map.Entry entry2 = it.next(); final Map.Entry entry3 = it.next(); assertEquals(true, entry1.equals(entry2)); assertEquals(true, entry2.equals(entry1)); assertEquals(false, entry1.equals(entry3)); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testNullHandling() { resetFull(); assertEquals(null, getMap().get(null)); assertEquals(false, getMap().containsKey(null)); assertEquals(false, getMap().containsValue(null)); assertEquals(null, getMap().remove(null)); assertEquals(false, getMap().entrySet().contains(null)); assertEquals(false, getMap().keySet().contains(null)); assertEquals(false, getMap().values().contains(null)); try { getMap().put(null, null); fail(); } catch (final NullPointerException ex) {} try { getMap().put((K) new Object(), null); fail(); } catch (final NullPointerException ex) {} try { getMap().put(null, (V) new Object()); fail(); } catch (final 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(Integer.valueOf(i), Integer.valueOf(i)); } gc(); for (int i = 0; i < 10; i++) { Integer I = Integer.valueOf(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] = Integer.valueOf(10 + i); map.put(Integer.valueOf(i), Integer.valueOf(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] = Integer.valueOf(10 + i); map.put(Integer.valueOf(i), Integer.valueOf(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] = Integer.valueOf(10 + i); map.put(Integer.valueOf(i), Integer.valueOf(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; @SuppressWarnings("unchecked") private Map buildRefMap() { final K key = (K) new Object(); final V value = (V) new Object(); keyReference = new WeakReference(key); valueReference = new WeakReference(value); final Map testMap = new ReferenceIdentityMap(ReferenceStrength.WEAK, ReferenceStrength.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 final 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: @SuppressWarnings("unused") final byte[] b = new byte[bytz]; bytz = bytz * 2; } } } @SuppressWarnings("unused") private static void gc() { try { // trigger GC final byte[][] tooLarge = new byte[1000000000][1000000000]; fail("you have too much RAM"); } catch (final OutOfMemoryError ex) { System.gc(); // ignore } } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/CompositeMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/CompositeMapTest.java100664 17115 12243235516 31676 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.Map; import java.util.HashMap; import java.util.Collection; /** * Extension of {@link AbstractMapTest} for exercising the * {@link CompositeMap} implementation. * * @since 3.0 * @version $Id: CompositeMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class CompositeMapTest extends AbstractIterableMapTest { /** used as a flag in MapMutator tests */ private boolean pass = false; public CompositeMapTest(final String testName) { super(testName); } @Override public void setUp() throws Exception { super.setUp(); this.pass = false; } @Override public CompositeMap makeObject() { final CompositeMap map = new CompositeMap(); map.addComposited(new HashMap()); map.setMutator( new EmptyMapMutator() ); return map; } @SuppressWarnings("unchecked") private Map buildOne() { final HashMap map = new HashMap(); map.put((K) "1", (V) "one"); map.put((K) "2", (V) "two"); return map; } @SuppressWarnings("unchecked") public Map buildTwo() { final HashMap map = new HashMap(); map.put((K) "3", (V) "three"); map.put((K) "4", (V) "four"); return map; } public void testGet() { final CompositeMap map = new CompositeMap(buildOne(), buildTwo()); assertEquals("one", map.get("1")); assertEquals("four", map.get("4")); } @SuppressWarnings("unchecked") public void testAddComposited() { final CompositeMap map = new CompositeMap(buildOne(), buildTwo()); final HashMap three = new HashMap(); three.put((K) "5", (V) "five"); map.addComposited(three); assertTrue(map.containsKey("5")); try { map.addComposited(three); fail("Expecting IllegalArgumentException."); } catch (final IllegalArgumentException ex) { // expected } } @SuppressWarnings("unchecked") public void testRemoveComposited() { final CompositeMap map = new CompositeMap(buildOne(), buildTwo()); final HashMap three = new HashMap(); three.put((K) "5", (V) "five"); map.addComposited(three); assertTrue(map.containsKey("5")); map.removeComposited(three); assertFalse(map.containsKey("5")); map.removeComposited(buildOne()); assertFalse(map.containsKey("2")); } @SuppressWarnings("unchecked") public void testRemoveFromUnderlying() { final CompositeMap map = new CompositeMap(buildOne(), buildTwo()); final HashMap three = new HashMap(); three.put((K) "5", (V) "five"); map.addComposited(three); assertTrue(map.containsKey("5")); //Now remove "5" three.remove("5"); assertFalse(map.containsKey("5")); } @SuppressWarnings("unchecked") public void testRemoveFromComposited() { final CompositeMap map = new CompositeMap(buildOne(), buildTwo()); final HashMap three = new HashMap(); three.put((K) "5", (V) "five"); map.addComposited(three); assertTrue(map.containsKey("5")); //Now remove "5" map.remove("5"); assertFalse(three.containsKey("5")); } public void testResolveCollision() { final CompositeMap map = new CompositeMap(buildOne(), buildTwo(), new CompositeMap.MapMutator() { private static final long serialVersionUID = 1L; public void resolveCollision(final CompositeMap composite, final Map existing, final Map added, final Collection intersect) { pass = true; } public V put(final CompositeMap map, final Map[] composited, final K key, final V value) { throw new UnsupportedOperationException(); } public void putAll(final CompositeMap map, final Map[] composited, final Map t) { throw new UnsupportedOperationException(); } }); map.addComposited(buildOne()); assertTrue(pass); } @SuppressWarnings("unchecked") public void testPut() { final CompositeMap map = new CompositeMap(buildOne(), buildTwo(), new CompositeMap.MapMutator() { private static final long serialVersionUID = 1L; public void resolveCollision(final CompositeMap composite, final Map existing, final Map added, final Collection intersect) { throw new UnsupportedOperationException(); } public V put(final CompositeMap map, final Map[] composited, final K key, final V value) { pass = true; return (V) "foo"; } public void putAll(final CompositeMap map, final Map[] composited, final Map t) { throw new UnsupportedOperationException(); } }); map.put((K) "willy", (V) "wonka"); assertTrue(pass); } public void testPutAll() { final CompositeMap map = new CompositeMap(buildOne(), buildTwo(), new CompositeMap.MapMutator() { private static final long serialVersionUID = 1L; public void resolveCollision(final CompositeMap composite, final Map existing, final Map added, final Collection intersect) { throw new UnsupportedOperationException(); } public V put(final CompositeMap map, final Map[] composited, final K key, final V value) { throw new UnsupportedOperationException(); } public void putAll(final CompositeMap map, final Map[] composited, final Map t) { pass = true; } }); map.putAll(null); assertTrue(pass); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/CompositeMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/CompositeMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/FixedSizeSortedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/FixedSizeSortedMapTes100664 5440 12243235516 31661 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * Extension of {@link AbstractSortedMapTest} for exercising the {@link FixedSizeSortedMap} * implementation. * * @since 3.0 * @version $Id: FixedSizeSortedMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class FixedSizeSortedMapTest extends AbstractSortedMapTest { public FixedSizeSortedMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(FixedSizeSortedMapTest.class); } //----------------------------------------------------------------------- @Override public SortedMap makeObject() { return FixedSizeSortedMap.fixedSizeSortedMap(new TreeMap()); } @Override public SortedMap makeFullMap() { final SortedMap map = new TreeMap(); addSampleMappings(map); return FixedSizeSortedMap.fixedSizeSortedMap(map); } @Override public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/FixedSizeSortedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/FixedSizeSortedMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/AbstractOrderedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/AbstractOrderedMapTes100664 17650 12243235516 31704 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.BulkTest; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.comparators.NullComparator; import org.apache.commons.collections4.iterators.AbstractOrderedMapIteratorTest; /** * Abstract test class for {@link OrderedMap} methods and contracts. * * @version $Id: AbstractOrderedMapTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractOrderedMapTest extends AbstractIterableMapTest { /** * JUnit constructor. * * @param testName the test name */ public AbstractOrderedMapTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @Override public abstract OrderedMap makeObject(); /** * {@inheritDoc} */ @Override public OrderedMap makeFullMap() { return (OrderedMap) super.makeFullMap(); } //----------------------------------------------------------------------- /** * OrderedMap uses TreeMap as its known comparison. * * @return a map that is known to be valid */ @Override 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. */ @Override @SuppressWarnings("unchecked") public K[] getSampleKeys() { final List list = new ArrayList(Arrays.asList(super.getSampleKeys())); Collections.sort(list, new NullComparator()); return (K[]) list.toArray(); } //----------------------------------------------------------------------- public void testFirstKey() { resetEmpty(); OrderedMap ordered = getMap(); try { ordered.firstKey(); fail(); } catch (final NoSuchElementException ex) {} resetFull(); ordered = getMap(); final K confirmedFirst = confirmed.keySet().iterator().next(); assertEquals(confirmedFirst, ordered.firstKey()); } public void testLastKey() { resetEmpty(); OrderedMap ordered = getMap(); try { ordered.lastKey(); fail(); } catch (final NoSuchElementException ex) {} resetFull(); ordered = getMap(); K confirmedLast = null; for (final Iterator it = confirmed.keySet().iterator(); it.hasNext();) { confirmedLast = it.next(); } assertEquals(confirmedLast, ordered.lastKey()); } //----------------------------------------------------------------------- public void testNextKey() { resetEmpty(); OrderedMap ordered = getMap(); assertEquals(null, ordered.nextKey(getOtherKeys()[0])); if (!isAllowNullKey()) { try { assertEquals(null, ordered.nextKey(null)); // this is allowed too } catch (final NullPointerException ex) {} } else { assertEquals(null, ordered.nextKey(null)); } resetFull(); ordered = getMap(); final Iterator it = confirmed.keySet().iterator(); K confirmedLast = it.next(); while (it.hasNext()) { final K confirmedObject = it.next(); assertEquals(confirmedObject, ordered.nextKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, ordered.nextKey(confirmedLast)); if (!isAllowNullKey()) { try { ordered.nextKey(null); fail(); } catch (final NullPointerException ex) {} } else { assertEquals(null, ordered.nextKey(null)); } } public void testPreviousKey() { resetEmpty(); OrderedMap ordered = getMap(); assertEquals(null, ordered.previousKey(getOtherKeys()[0])); if (!isAllowNullKey()) { try { assertEquals(null, ordered.previousKey(null)); // this is allowed too } catch (final NullPointerException ex) {} } else { assertEquals(null, ordered.previousKey(null)); } resetFull(); ordered = getMap(); final List list = new ArrayList(confirmed.keySet()); Collections.reverse(list); final Iterator it = list.iterator(); K confirmedLast = it.next(); while (it.hasNext()) { final K confirmedObject = it.next(); assertEquals(confirmedObject, ordered.previousKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, ordered.previousKey(confirmedLast)); if (!isAllowNullKey()) { try { ordered.previousKey(null); fail(); } catch (final NullPointerException ex) {} } else { if (!isAllowNullKey()) { assertEquals(null, ordered.previousKey(null)); } } } //----------------------------------------------------------------------- public BulkTest bulkTestOrderedMapIterator() { return new InnerTestOrderedMapIterator(); } public class InnerTestOrderedMapIterator extends AbstractOrderedMapIteratorTest { public InnerTestOrderedMapIterator() { super("InnerTestOrderedMapIterator"); } @Override public boolean supportsRemove() { return AbstractOrderedMapTest.this.isRemoveSupported(); } @Override public boolean isGetStructuralModify() { return AbstractOrderedMapTest.this.isGetStructuralModify(); } @Override public boolean supportsSetValue() { return AbstractOrderedMapTest.this.isSetValueSupported(); } @Override public OrderedMapIterator makeEmptyIterator() { resetEmpty(); return AbstractOrderedMapTest.this.getMap().mapIterator(); } @Override public OrderedMapIterator makeObject() { resetFull(); return AbstractOrderedMapTest.this.getMap().mapIterator(); } @Override public OrderedMap getMap() { // assumes makeFullMapIterator() called first return AbstractOrderedMapTest.this.getMap(); } @Override public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return AbstractOrderedMapTest.this.getConfirmed(); } @Override public void verify() { super.verify(); AbstractOrderedMapTest.this.verify(); } } /** * {@inheritDoc} */ @Override public OrderedMap getMap() { return (OrderedMap) super.getMap(); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/LinkedMapTest.java100664 22562 12243235516 31144 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.ResettableIterator; import org.apache.commons.collections4.list.AbstractListTest; /** * JUnit tests. * * @version $Id: LinkedMapTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class LinkedMapTest extends AbstractOrderedMapTest { public LinkedMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(LinkedMapTest.class); } @Override public LinkedMap makeObject() { return new LinkedMap(); } /** * {@inheritDoc} */ @Override public LinkedMap makeFullMap() { return (LinkedMap) super.makeFullMap(); } @Override public String getCompatibilityVersion() { return "4"; } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testReset() { resetEmpty(); OrderedMap ordered = getMap(); ((ResettableIterator) ordered.mapIterator()).reset(); resetFull(); ordered = getMap(); final List list = new ArrayList(ordered.keySet()); final 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() || !isPutChangeSupported()) { return; } final K[] keys = getSampleKeys(); final V[] values = getSampleValues(); Iterator keyIter; Iterator valueIter; resetEmpty(); map.put(keys[0], values[0]); map.put(keys[1], values[1]); keyIter = map.keySet().iterator(); assertSame(keys[0], keyIter.next()); assertSame(keys[1], keyIter.next()); valueIter = map.values().iterator(); assertSame(values[0], valueIter.next()); assertSame(values[1], valueIter.next()); // no change to order map.put(keys[1], values[1]); keyIter = map.keySet().iterator(); assertSame(keys[0], keyIter.next()); assertSame(keys[1], keyIter.next()); valueIter = map.values().iterator(); assertSame(values[0], valueIter.next()); assertSame(values[1], valueIter.next()); // no change to order map.put(keys[1], values[2]); keyIter = map.keySet().iterator(); assertSame(keys[0], keyIter.next()); assertSame(keys[1], keyIter.next()); valueIter = map.values().iterator(); assertSame(values[0], valueIter.next()); assertSame(values[2], valueIter.next()); // no change to order map.put(keys[0], values[3]); keyIter = map.keySet().iterator(); assertSame(keys[0], keyIter.next()); assertSame(keys[1], keyIter.next()); valueIter = map.values().iterator(); assertSame(values[3], valueIter.next()); assertSame(values[2], valueIter.next()); } //----------------------------------------------------------------------- public void testGetByIndex() { resetEmpty(); LinkedMap lm = getMap(); try { lm.get(0); } catch (final IndexOutOfBoundsException ex) {} try { lm.get(-1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); lm = getMap(); try { lm.get(-1); } catch (final IndexOutOfBoundsException ex) {} try { lm.get(lm.size()); } catch (final IndexOutOfBoundsException ex) {} int i = 0; for (final MapIterator it = lm.mapIterator(); it.hasNext(); i++) { assertSame(it.next(), lm.get(i)); } } public void testGetValueByIndex() { resetEmpty(); LinkedMap lm = getMap(); try { lm.getValue(0); } catch (final IndexOutOfBoundsException ex) {} try { lm.getValue(-1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); lm = getMap(); try { lm.getValue(-1); } catch (final IndexOutOfBoundsException ex) {} try { lm.getValue(lm.size()); } catch (final IndexOutOfBoundsException ex) {} int i = 0; for (final MapIterator it = lm.mapIterator(); it.hasNext(); i++) { it.next(); assertSame(it.getValue(), lm.getValue(i)); } } public void testIndexOf() { resetEmpty(); LinkedMap lm = getMap(); assertEquals(-1, lm.indexOf(getOtherKeys())); resetFull(); lm = getMap(); final List list = new ArrayList(); for (final 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 = getMap(); try { lm.remove(0); } catch (final IndexOutOfBoundsException ex) {} try { lm.remove(-1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); lm = getMap(); try { lm.remove(-1); } catch (final IndexOutOfBoundsException ex) {} try { lm.remove(lm.size()); } catch (final IndexOutOfBoundsException ex) {} final List list = new ArrayList(); for (final MapIterator it = lm.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { final Object key = list.get(i); final 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 AbstractListTest { TestListView() { super("TestListView"); } @Override public List makeObject() { return LinkedMapTest.this.makeObject().asList(); } @Override public List makeFullCollection() { return LinkedMapTest.this.makeFullMap().asList(); } @Override public K[] getFullElements() { return LinkedMapTest.this.getSampleKeys(); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public boolean isSetSupported() { return false; } @Override public boolean isNullSupported() { return LinkedMapTest.this.isAllowNullKey(); } @Override public boolean isTestSerialization() { return false; } } @SuppressWarnings("unchecked") public void testClone() { final LinkedMap map = new LinkedMap(10); map.put((K) "1", (V) "1"); final Map cloned = 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, "src/test/resources/data/test/LinkedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/LinkedMap.fullCollection.version4.obj"); // } /** * {@inheritDoc} */ @Override public LinkedMap getMap() { return (LinkedMap) super.getMap(); } /** * Test for COLLECTIONS-323. */ public void testInitialCapacityZero() { final LinkedMap map = new LinkedMap(0); assertEquals(1, map.data.length); } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/CaseInsensitiveMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/CaseInsensitiveMapTes100664 13074 12243235516 31724 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * Tests for the {@link CaseInsensitiveMap} implementation. * * @version $Id: CaseInsensitiveMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class CaseInsensitiveMapTest extends AbstractIterableMapTest { public CaseInsensitiveMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(CaseInsensitiveMapTest.class); } @Override public CaseInsensitiveMap makeObject() { return new CaseInsensitiveMap(); } @Override public String getCompatibilityVersion() { return "4"; } //------------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testCaseInsensitive() { final Map map = makeObject(); map.put((K) "One", (V) "One"); map.put((K) "Two", (V) "Two"); assertEquals("One", map.get("one")); assertEquals("One", map.get("oNe")); map.put((K) "two", (V) "Three"); assertEquals("Three", map.get("Two")); } @SuppressWarnings("unchecked") public void testNullHandling() { final Map map = makeObject(); map.put((K) "One", (V) "One"); map.put((K) "Two", (V) "Two"); map.put(null, (V) "Three"); assertEquals("Three", map.get(null)); map.put(null, (V) "Four"); assertEquals("Four", map.get(null)); final Set keys = map.keySet(); assertTrue(keys.contains("one")); assertTrue(keys.contains("two")); assertTrue(keys.contains(null)); assertEquals(3, keys.size()); } public void testPutAll() { final Map map = new HashMap(); map.put("One", "One"); map.put("Two", "Two"); map.put("one", "Three"); map.put(null, "Four"); map.put(Integer.valueOf(20), "Five"); final Map caseInsensitiveMap = new CaseInsensitiveMap(map); assertEquals(4, caseInsensitiveMap.size()); // ones collapsed final Set keys = caseInsensitiveMap.keySet(); assertTrue(keys.contains("one")); assertTrue(keys.contains("two")); assertTrue(keys.contains(null)); assertTrue(keys.contains(Integer.toString(20))); assertEquals(4, keys.size()); assertTrue(!caseInsensitiveMap.containsValue("One") || !caseInsensitiveMap.containsValue("Three")); // ones collaped assertEquals("Four", caseInsensitiveMap.get(null)); } @SuppressWarnings("unchecked") public void testClone() { final CaseInsensitiveMap map = new CaseInsensitiveMap(10); map.put((K) "1", (V) "1"); final CaseInsensitiveMap cloned = 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, "src/test/resources/data/test/CaseInsensitiveMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/CaseInsensitiveMap.fullCollection.version4.obj"); // } // COLLECTIONS-294 public void testLocaleIndependence() { final Locale orig = Locale.getDefault(); final Locale[] locales = { Locale.ENGLISH, new Locale("tr", "", ""), Locale.getDefault() }; final String[][] data = { { "i", "I" }, { "\u03C2", "\u03C3" }, { "\u03A3", "\u03C2" }, { "\u03A3", "\u03C3" }, }; try { for (final Locale locale : locales) { Locale.setDefault(locale); for (int j = 0; j < data.length; j++) { assertTrue("Test data corrupt: " + j, data[j][0].equalsIgnoreCase(data[j][1])); final CaseInsensitiveMap map = new CaseInsensitiveMap(); map.put(data[j][0], "value"); assertEquals(Locale.getDefault() + ": " + j, "value", map.get(data[j][1])); } } } finally { Locale.setDefault(orig); } } /** * Test for COLLECTIONS-323. */ public void testInitialCapacityZero() { final CaseInsensitiveMap map = new CaseInsensitiveMap(0); assertEquals(1, map.data.length); } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/PredicatedSortedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/PredicatedSortedMapTe100664 15100 12243235516 31662 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.TruePredicate; /** * Extension of {@link PredicatedMapTest} for exercising the * {@link PredicatedSortedMap} implementation. * * @since 3.0 * @version $Id: PredicatedSortedMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class PredicatedSortedMapTest extends AbstractSortedMapTest { protected static final Predicate truePredicate = TruePredicate.truePredicate(); protected static final Predicate testPredicate = new Predicate() { public boolean evaluate(final Object o) { return o instanceof String; } }; public PredicatedSortedMapTest(final String testName) { super(testName); } //----------------------------------------------------------------------- protected SortedMap decorateMap(final SortedMap map, final Predicate keyPredicate, final Predicate valuePredicate) { return PredicatedSortedMap.predicatedSortedMap(map, keyPredicate, valuePredicate); } @Override public SortedMap makeObject() { return decorateMap(new TreeMap(), truePredicate, truePredicate); } public SortedMap makeTestMap() { return decorateMap(new TreeMap(), testPredicate, testPredicate); } @Override public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; } @Override public boolean isAllowNullKey() { return false; } // from TestPredicatedMap //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testEntrySet() { SortedMap map = makeTestMap(); assertTrue("returned entryset should not be null", map.entrySet() != null); map = decorateMap(new TreeMap(), null, null); map.put((K) "oneKey", (V) "oneValue"); assertTrue("returned entryset should contain one entry", map.entrySet().size() == 1); map = decorateMap(map, null, null); } @SuppressWarnings("unchecked") public void testPut() { final Map map = makeTestMap(); try { map.put((K) "Hi", (V) Integer.valueOf(3)); fail("Illegal value should raise IllegalArgument"); } catch (final IllegalArgumentException e) { // expected } try { map.put((K) Integer.valueOf(3), (V) "Hi"); fail("Illegal key should raise IllegalArgument"); } catch (final IllegalArgumentException e) { // expected } assertTrue(!map.containsKey(Integer.valueOf(3))); assertTrue(!map.containsValue(Integer.valueOf(3))); final Map map2 = new HashMap(); map2.put((K) "A", (V) "a"); map2.put((K) "B", (V) "b"); map2.put((K) "C", (V) "c"); map2.put((K) "c", (V) Integer.valueOf(3)); try { map.putAll(map2); fail("Illegal value should raise IllegalArgument"); } catch (final IllegalArgumentException e) { // expected } map.put((K) "E", (V) "e"); Iterator> iterator = map.entrySet().iterator(); try { final Map.Entry entry = iterator.next(); entry.setValue((V) Integer.valueOf(3)); fail("Illegal value should raise IllegalArgument"); } catch (final IllegalArgumentException e) { // expected } map.put((K) "F", (V) "f"); iterator = map.entrySet().iterator(); final Map.Entry entry = iterator.next(); entry.setValue((V) "x"); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testSortOrder() { final SortedMap map = makeTestMap(); map.put((K) "A", (V) "a"); map.put((K) "B", (V) "b"); try { map.put(null, (V) "c"); fail("Null key should raise IllegalArgument"); } catch (final IllegalArgumentException e) { // expected } map.put((K) "C", (V) "c"); try { map.put((K) "D", null); fail("Null value should raise IllegalArgument"); } catch (final IllegalArgumentException e) { // expected } assertEquals("First key should be A", "A", map.firstKey()); assertEquals("Last key should be C", "C", map.lastKey()); assertEquals("First key in tail map should be B", "B", map.tailMap((K) "B").firstKey()); assertEquals("Last key in head map should be B", "B", map.headMap((K) "C").lastKey()); assertEquals("Last key in submap should be B", "B", map.subMap((K) "A",(K) "C").lastKey()); final Comparator c = map.comparator(); assertTrue("natural order, so comparator should be null", c == null); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/PredicatedSortedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/PredicatedSortedMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/UnmodifiableOrderedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/UnmodifiableOrderedMa100664 6411 12243235516 31654 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.HashMap; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.Unmodifiable; /** * Extension of {@link AbstractOrderedMapTest} for exercising the * {@link UnmodifiableOrderedMap} implementation. * * @since 3.0 * @version $Id: UnmodifiableOrderedMapTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class UnmodifiableOrderedMapTest extends AbstractOrderedMapTest { public UnmodifiableOrderedMapTest(final String testName) { super(testName); } //------------------------------------------------------------------- @Override public OrderedMap makeObject() { return UnmodifiableOrderedMap.unmodifiableOrderedMap(ListOrderedMap.listOrderedMap(new HashMap())); } @Override public boolean isPutChangeSupported() { return false; } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public OrderedMap makeFullMap() { final OrderedMap m = ListOrderedMap.listOrderedMap(new HashMap()); addSampleMappings(m); return UnmodifiableOrderedMap.unmodifiableOrderedMap(m); } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { final OrderedMap map = makeFullMap(); assertSame(map, UnmodifiableOrderedMap.unmodifiableOrderedMap(map)); try { UnmodifiableOrderedMap.unmodifiableOrderedMap(null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/UnmodifiableOrderedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/UnmodifiableOrderedMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/ListOrderedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/ListOrderedMapTest.ja100664 42307 12243235516 31626 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.list.AbstractListTest; /** * Extension of {@link AbstractOrderedMapTest} for exercising the {@link ListOrderedMap} * implementation. * * @since 3.0 * @version $Id: ListOrderedMapTest.java 1543964 2013-11-20 21:53:39Z tn $ */ public class ListOrderedMapTest extends AbstractOrderedMapTest { public ListOrderedMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(ListOrderedMapTest.class); } @Override public ListOrderedMap makeObject() { return ListOrderedMap.listOrderedMap(new HashMap()); } /** * {@inheritDoc} */ @Override public ListOrderedMap makeFullMap() { return (ListOrderedMap) super.makeFullMap(); } //----------------------------------------------------------------------- public void testGetByIndex() { resetEmpty(); ListOrderedMap lom = getMap(); try { lom.get(0); } catch (final IndexOutOfBoundsException ex) {} try { lom.get(-1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); lom = getMap(); try { lom.get(-1); } catch (final IndexOutOfBoundsException ex) {} try { lom.get(lom.size()); } catch (final IndexOutOfBoundsException ex) {} int i = 0; for (final MapIterator it = lom.mapIterator(); it.hasNext(); i++) { assertSame(it.next(), lom.get(i)); } } public void testGetValueByIndex() { resetEmpty(); ListOrderedMap lom = getMap(); try { lom.getValue(0); } catch (final IndexOutOfBoundsException ex) {} try { lom.getValue(-1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); lom = getMap(); try { lom.getValue(-1); } catch (final IndexOutOfBoundsException ex) {} try { lom.getValue(lom.size()); } catch (final IndexOutOfBoundsException ex) {} int i = 0; for (final MapIterator it = lom.mapIterator(); it.hasNext(); i++) { it.next(); assertSame(it.getValue(), lom.getValue(i)); } } public void testIndexOf() { resetEmpty(); ListOrderedMap lom = getMap(); assertEquals(-1, lom.indexOf(getOtherKeys())); resetFull(); lom = getMap(); final List list = new ArrayList(); for (final 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))); } } @SuppressWarnings("unchecked") public void testSetValueByIndex() { resetEmpty(); ListOrderedMap lom = getMap(); try { lom.setValue(0, (V) ""); } catch (final IndexOutOfBoundsException ex) {} try { lom.setValue(-1, (V) ""); } catch (final IndexOutOfBoundsException ex) {} resetFull(); lom = getMap(); try { lom.setValue(-1, (V) ""); } catch (final IndexOutOfBoundsException ex) {} try { lom.setValue(lom.size(), (V) ""); } catch (final IndexOutOfBoundsException ex) {} for (int i = 0; i < lom.size(); i++) { final V value = lom.getValue(i); final Object input = Integer.valueOf(i); assertEquals(value, lom.setValue(i, (V) input)); assertEquals(input, lom.getValue(i)); } } public void testRemoveByIndex() { resetEmpty(); ListOrderedMap lom = getMap(); try { lom.remove(0); } catch (final IndexOutOfBoundsException ex) {} try { lom.remove(-1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); lom = getMap(); try { lom.remove(-1); } catch (final IndexOutOfBoundsException ex) {} try { lom.remove(lom.size()); } catch (final IndexOutOfBoundsException ex) {} final List list = new ArrayList(); for (final MapIterator it = lom.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { final Object key = list.get(i); final Object value = lom.get(key); assertEquals(value, lom.remove(i)); list.remove(i); assertEquals(false, lom.containsKey(key)); } } @SuppressWarnings("unchecked") public void testPut_intObjectObject() { resetEmpty(); ListOrderedMap lom = getMap(); try { lom.put(1, (K) "testInsert1", (V) "testInsert1v"); fail("should not be able to insert at pos 1 in empty Map"); } catch (final IndexOutOfBoundsException ex) {} try { lom.put(-1, (K) "testInsert-1", (V) "testInsert-1v"); fail("should not be able to insert at pos -1 in empty Map"); } catch (final IndexOutOfBoundsException ex) {} // put where key doesn't exist lom.put(0, (K) "testInsert1", (V) "testInsert1v"); assertEquals("testInsert1v", lom.getValue(0)); lom.put((K) "testInsertPut", (V) "testInsertPutv"); assertEquals("testInsert1v", lom.getValue(0)); assertEquals("testInsertPutv", lom.getValue(1)); lom.put(0, (K) "testInsert0", (V) "testInsert0v"); assertEquals("testInsert0v", lom.getValue(0)); assertEquals("testInsert1v", lom.getValue(1)); assertEquals("testInsertPutv", lom.getValue(2)); lom.put(3, (K) "testInsert3", (V) "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 = getMap(); final ListOrderedMap lom2 = new ListOrderedMap(); lom2.putAll(lom); lom2.put(0, (K) "testInsert0", (V) "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 final Integer i1 = Integer.valueOf(1); final Integer i1b = Integer.valueOf(1); final Integer i2 = Integer.valueOf(2); final Integer i3 = Integer.valueOf(3); resetEmpty(); lom = getMap(); lom.put((K) i1, (V) "1"); lom.put((K) i2, (V) "2"); lom.put((K) i3, (V) "3"); lom.put(0, (K) i1, (V) "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.keyList().size()); assertEquals("One", lom.getValue(0)); assertSame(i1, lom.get(0)); resetEmpty(); lom = getMap(); lom.put((K) i1, (V) "1"); lom.put((K) i2, (V) "2"); lom.put((K) i3, (V) "3"); lom.put(0, (K) i1b, (V) "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.keyList().size()); assertEquals("One", lom.getValue(0)); assertEquals("2", lom.getValue(1)); assertEquals("3", lom.getValue(2)); assertSame(i1b, lom.get(0)); resetEmpty(); lom = getMap(); lom.put((K) i1, (V) "1"); lom.put((K) i2, (V) "2"); lom.put((K) i3, (V) "3"); lom.put(1, (K) i1b, (V) "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.keyList().size()); assertEquals("One", lom.getValue(0)); assertEquals("2", lom.getValue(1)); assertEquals("3", lom.getValue(2)); resetEmpty(); lom = getMap(); lom.put((K) i1, (V) "1"); lom.put((K) i2, (V) "2"); lom.put((K) i3, (V) "3"); lom.put(2, (K) i1b, (V) "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.keyList().size()); assertEquals("2", lom.getValue(0)); assertEquals("One", lom.getValue(1)); assertEquals("3", lom.getValue(2)); resetEmpty(); lom = getMap(); lom.put((K) i1, (V) "1"); lom.put((K) i2, (V) "2"); lom.put((K) i3, (V) "3"); lom.put(3, (K) i1b, (V) "One"); assertEquals(3, lom.size()); assertEquals(3, lom.map.size()); assertEquals(3, lom.keyList().size()); assertEquals("2", lom.getValue(0)); assertEquals("3", lom.getValue(1)); assertEquals("One", lom.getValue(2)); } public void testPutAllWithIndex() { resetEmpty(); @SuppressWarnings("unchecked") final ListOrderedMap lom = (ListOrderedMap) map; // Create Initial Data lom.put("testInsert0", "testInsert0v"); lom.put("testInsert1", "testInsert1v"); lom.put("testInsert2", "testInsert2v"); assertEquals("testInsert0v", lom.getValue(0)); assertEquals("testInsert1v", lom.getValue(1)); assertEquals("testInsert2v", lom.getValue(2)); // Create New Test Map and Add using putAll(int, Object, Object) final Map values = new ListOrderedMap(); values.put("NewInsert0", "NewInsert0v"); values.put("NewInsert1", "NewInsert1v"); lom.putAll(1, values); // Perform Asserts assertEquals("testInsert0v", lom.getValue(0)); assertEquals("NewInsert0v", lom.getValue(1)); assertEquals("NewInsert1v", lom.getValue(2)); assertEquals("testInsert1v", lom.getValue(3)); assertEquals("testInsert2v", lom.getValue(4)); } @SuppressWarnings("unchecked") public void testPutAllWithIndexBug441() { // see COLLECTIONS-441 resetEmpty(); final ListOrderedMap lom = getMap(); final int size = 5; for (int i = 0; i < size; i++) { lom.put((K) Integer.valueOf(i), (V) Boolean.TRUE); } final Map map = new TreeMap(); for (int i = 0; i < size; i++) { map.put((K) Integer.valueOf(i), (V) Boolean.FALSE); } lom.putAll(3, map); final List orderedList = lom.asList(); for (int i = 0; i < size; i++) { assertEquals(Integer.valueOf(i), orderedList.get(i)); } } //----------------------------------------------------------------------- public void testValueList_getByIndex() { resetFull(); final ListOrderedMap lom = getMap(); for (int i = 0; i < lom.size(); i++) { final V expected = lom.getValue(i); assertEquals(expected, lom.valueList().get(i)); } } @SuppressWarnings("unchecked") public void testValueList_setByIndex() { resetFull(); final ListOrderedMap lom = getMap(); for (int i = 0; i < lom.size(); i++) { final Object input = Integer.valueOf(i); final V expected = lom.getValue(i); assertEquals(expected, lom.valueList().set(i, (V) input)); assertEquals(input, lom.getValue(i)); assertEquals(input, lom.valueList().get(i)); } } public void testValueList_removeByIndex() { resetFull(); final ListOrderedMap lom = getMap(); while (lom.size() > 1) { final V expected = lom.getValue(1); assertEquals(expected, lom.valueList().remove(1)); } } public void testCOLLECTIONS_474_nullValues () { Object key1 = new Object(); Object key2 = new Object(); HashMap hmap = new HashMap(); hmap.put(key1, null); hmap.put(key2, null); assertEquals("Should have two elements", 2, hmap.size()); ListOrderedMap listMap = new ListOrderedMap(); listMap.put(key1, null); listMap.put(key2, null); assertEquals("Should have two elements", 2, listMap.size()); listMap.putAll(2, hmap); } public void testCOLLECTIONS_474_nonNullValues () { Object key1 = new Object(); Object key2 = new Object(); HashMap hmap = new HashMap(); hmap.put(key1, "1"); hmap.put(key2, "2"); assertEquals("Should have two elements", 2, hmap.size()); ListOrderedMap listMap = new ListOrderedMap(); listMap.put(key1, "3"); listMap.put(key2, "4"); assertEquals("Should have two elements", 2, listMap.size()); listMap.putAll(2, hmap); } //----------------------------------------------------------------------- public BulkTest bulkTestKeyListView() { return new TestKeyListView(); } public BulkTest bulkTestValueListView() { return new TestValueListView(); } //----------------------------------------------------------------------- public class TestKeyListView extends AbstractListTest { TestKeyListView() { super("TestKeyListView"); } @Override public List makeObject() { return ListOrderedMapTest.this.makeObject().keyList(); } @Override public List makeFullCollection() { return ListOrderedMapTest.this.makeFullMap().keyList(); } @Override public K[] getFullElements() { return ListOrderedMapTest.this.getSampleKeys(); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public boolean isSetSupported() { return false; } @Override public boolean isNullSupported() { return ListOrderedMapTest.this.isAllowNullKey(); } @Override public boolean isTestSerialization() { return false; } } //----------------------------------------------------------------------- public class TestValueListView extends AbstractListTest { TestValueListView() { super("TestValueListView"); } @Override public List makeObject() { return ListOrderedMapTest.this.makeObject().valueList(); } @Override public List makeFullCollection() { return ListOrderedMapTest.this.makeFullMap().valueList(); } @Override public V[] getFullElements() { return ListOrderedMapTest.this.getSampleValues(); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return true; } @Override public boolean isSetSupported() { return true; } @Override public boolean isNullSupported() { return ListOrderedMapTest.this.isAllowNullKey(); } @Override public boolean isTestSerialization() { return false; } } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/ListOrderedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/ListOrderedMap.fullCollection.version4.obj"); // } /** * {@inheritDoc} */ @Override public ListOrderedMap getMap() { return (ListOrderedMap) super.getMap(); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/ListOrderedMap2Test.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/ListOrderedMap2Test.j100664 15110 12243235516 31537 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.ArrayList; import java.util.List; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.list.AbstractListTest; /** * Extension of {@link AbstractOrderedMapTest} for exercising the {@link ListOrderedMap} * implementation. * * @since 3.1 * @version $Id: ListOrderedMap2Test.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ListOrderedMap2Test extends AbstractOrderedMapTest { public ListOrderedMap2Test(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(ListOrderedMap2Test.class); } @Override public ListOrderedMap makeObject() { return new ListOrderedMap(); } /** * {@inheritDoc} */ @Override public ListOrderedMap makeFullMap() { return (ListOrderedMap) super.makeFullMap(); } //----------------------------------------------------------------------- public void testGetByIndex() { resetEmpty(); ListOrderedMap lom = getMap(); try { lom.get(0); } catch (final IndexOutOfBoundsException ex) {} try { lom.get(-1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); lom = getMap(); try { lom.get(-1); } catch (final IndexOutOfBoundsException ex) {} try { lom.get(lom.size()); } catch (final IndexOutOfBoundsException ex) {} int i = 0; for (final MapIterator it = lom.mapIterator(); it.hasNext(); i++) { assertSame(it.next(), lom.get(i)); } } public void testGetValueByIndex() { resetEmpty(); ListOrderedMap lom = getMap(); try { lom.getValue(0); } catch (final IndexOutOfBoundsException ex) {} try { lom.getValue(-1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); lom = getMap(); try { lom.getValue(-1); } catch (final IndexOutOfBoundsException ex) {} try { lom.getValue(lom.size()); } catch (final IndexOutOfBoundsException ex) {} int i = 0; for (final MapIterator it = lom.mapIterator(); it.hasNext(); i++) { it.next(); assertSame(it.getValue(), lom.getValue(i)); } } public void testIndexOf() { resetEmpty(); ListOrderedMap lom = getMap(); assertEquals(-1, lom.indexOf(getOtherKeys())); resetFull(); lom = getMap(); final List list = new ArrayList(); for (final 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 = getMap(); try { lom.remove(0); } catch (final IndexOutOfBoundsException ex) {} try { lom.remove(-1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); lom = getMap(); try { lom.remove(-1); } catch (final IndexOutOfBoundsException ex) {} try { lom.remove(lom.size()); } catch (final IndexOutOfBoundsException ex) {} final List list = new ArrayList(); for (final MapIterator it = lom.mapIterator(); it.hasNext();) { list.add(it.next()); } for (int i = 0; i < list.size(); i++) { final Object key = list.get(i); final 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 AbstractListTest { TestListView() { super("TestListView"); } @Override public List makeObject() { return ListOrderedMap2Test.this.makeObject().asList(); } @Override public List makeFullCollection() { return ListOrderedMap2Test.this.makeFullMap().asList(); } @Override public K[] getFullElements() { return ListOrderedMap2Test.this.getSampleKeys(); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public boolean isSetSupported() { return false; } @Override public boolean isNullSupported() { return ListOrderedMap2Test.this.isAllowNullKey(); } @Override public boolean isTestSerialization() { return false; } } @Override public String getCompatibilityVersion() { return "4"; } // 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"); // } /** * {@inheritDoc} */ @Override public ListOrderedMap getMap() { return (ListOrderedMap) super.getMap(); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/LRUMapTest.java100664 72607 12243235516 30405 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.ResettableIterator; /** * JUnit tests. * * @version $Id: LRUMapTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class LRUMapTest extends AbstractOrderedMapTest { public LRUMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(LRUMapTest.class); } @Override public LRUMap makeObject() { return new LRUMap(); } /** * {@inheritDoc} */ @Override public LRUMap makeFullMap() { return (LRUMap) super.makeFullMap(); } @Override public boolean isGetStructuralModify() { return true; } @Override public String getCompatibilityVersion() { return "4"; } //----------------------------------------------------------------------- public void testLRU() { if (!isPutAddSupported() || !isPutChangeSupported()) { return; } final K[] keys = getSampleKeys(); final V[] values = getSampleValues(); Iterator kit; Iterator vit; final 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()); kit = map.keySet().iterator(); assertSame(keys[0], kit.next()); assertSame(keys[1], kit.next()); vit = map.values().iterator(); assertSame(values[0], vit.next()); assertSame(values[1], vit.next()); map.put(keys[2], values[2]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); kit = map.keySet().iterator(); assertSame(keys[1], kit.next()); assertSame(keys[2], kit.next()); vit = map.values().iterator(); assertSame(values[1], vit.next()); assertSame(values[2], vit.next()); map.put(keys[2], values[0]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); kit = map.keySet().iterator(); assertSame(keys[1], kit.next()); assertSame(keys[2], kit.next()); vit = map.values().iterator(); assertSame(values[1], vit.next()); assertSame(values[0], vit.next()); map.put(keys[1], values[3]); assertEquals(2, map.size()); assertEquals(true, map.isFull()); assertEquals(2, map.maxSize()); kit = map.keySet().iterator(); assertSame(keys[2], kit.next()); assertSame(keys[1], kit.next()); vit = map.values().iterator(); assertSame(values[0], vit.next()); assertSame(values[3], vit.next()); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testReset() { resetEmpty(); OrderedMap ordered = getMap(); ((ResettableIterator) ordered.mapIterator()).reset(); resetFull(); ordered = getMap(); final List list = new ArrayList(ordered.keySet()); final 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() || !isPutChangeSupported()) { return; } final K[] keys = getSampleKeys(); final V[] values = getSampleValues(); Iterator kit = null; Iterator vit = null; resetEmpty(); map.put(keys[0], values[0]); map.put(keys[1], values[1]); kit = map.keySet().iterator(); assertSame(keys[0], kit.next()); assertSame(keys[1], kit.next()); vit = map.values().iterator(); assertSame(values[0], vit.next()); assertSame(values[1], vit.next()); // no change to order map.put(keys[1], values[1]); kit = map.keySet().iterator(); assertSame(keys[0], kit.next()); assertSame(keys[1], kit.next()); vit = map.values().iterator(); assertSame(values[0], vit.next()); assertSame(values[1], vit.next()); // no change to order map.put(keys[1], values[2]); kit = map.keySet().iterator(); assertSame(keys[0], kit.next()); assertSame(keys[1], kit.next()); vit = map.values().iterator(); assertSame(values[0], vit.next()); assertSame(values[2], vit.next()); // change to order map.put(keys[0], values[3]); kit = map.keySet().iterator(); assertSame(keys[1], kit.next()); assertSame(keys[0], kit.next()); vit = map.values().iterator(); assertSame(values[2], vit.next()); assertSame(values[3], vit.next()); // change to order map.get(keys[1]); kit = map.keySet().iterator(); assertSame(keys[0], kit.next()); assertSame(keys[1], kit.next()); vit = map.values().iterator(); assertSame(values[3], vit.next()); assertSame(values[2], vit.next()); // change to order map.get(keys[0]); kit = map.keySet().iterator(); assertSame(keys[1], kit.next()); assertSame(keys[0], kit.next()); vit = map.values().iterator(); assertSame(values[2], vit.next()); assertSame(values[3], vit.next()); // no change to order map.get(keys[0]); kit = map.keySet().iterator(); assertSame(keys[1], kit.next()); assertSame(keys[0], kit.next()); vit = map.values().iterator(); assertSame(values[2], vit.next()); assertSame(values[3], vit.next()); } @SuppressWarnings("unchecked") public void testClone() { final LRUMap map = new LRUMap(10); map.put((K) "1", (V) "1"); final Map cloned = map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } @SuppressWarnings("unchecked") public void testRemoveLRU() { final MockLRUMapSubclass map = new MockLRUMapSubclass(2); assertNull(map.entry); map.put((K) "A", "a"); assertNull(map.entry); map.put((K) "B", "b"); assertNull(map.entry); map.put((K) "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 { /** * Generated serial version ID. */ private static final long serialVersionUID = -2126883654452042477L; LinkEntry entry; K key; V value; MockLRUMapSubclass(final int size) { super(size); } @Override protected boolean removeLRU(final LinkEntry entry) { this.entry = entry; this.key = entry.getKey(); this.value = entry.getValue(); return true; } } @SuppressWarnings("unchecked") public void testRemoveLRUBlocksRemove() { final MockLRUMapSubclassBlocksRemove map = new MockLRUMapSubclassBlocksRemove(2, false); assertEquals(0, map.size()); map.put((K) "A", (V) "a"); assertEquals(1, map.size()); map.put((K) "B", (V) "b"); assertEquals(2, map.size()); map.put((K) "C", (V) "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")); } @SuppressWarnings("unchecked") public void testRemoveLRUBlocksRemoveScan() { final MockLRUMapSubclassBlocksRemove map = new MockLRUMapSubclassBlocksRemove(2, true); assertEquals(0, map.size()); map.put((K) "A", (V) "a"); assertEquals(1, map.size()); map.put((K) "B", (V) "b"); assertEquals(2, map.size()); map.put((K) "C", (V) "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 { /** * Generated serial version ID. */ private static final long serialVersionUID = 6278917461128992945L; MockLRUMapSubclassBlocksRemove(final int size, final boolean scanUntilRemove) { super(size, scanUntilRemove); } @Override protected boolean removeLRU(final LinkEntry entry) { return false; } } @SuppressWarnings("unchecked") public void testRemoveLRUFirstBlocksRemove() { final MockLRUMapSubclassFirstBlocksRemove map = new MockLRUMapSubclassFirstBlocksRemove(2); assertEquals(0, map.size()); map.put((K) "A", (V) "a"); assertEquals(1, map.size()); map.put((K) "B", (V) "b"); assertEquals(2, map.size()); map.put((K) "C", (V) "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 { /** * Generated serial version ID. */ private static final long serialVersionUID = -6939790801702973428L; MockLRUMapSubclassFirstBlocksRemove(final int size) { super(size, true); } @Override protected boolean removeLRU(final LinkEntry entry) { if ("a".equals(entry.getValue())) { return false; } else { return true; } } } //----------------------------------------------------------------------- static class SingleHashCode { private final String code; SingleHashCode(final String code) { this.code = code; } @Override public int hashCode() { // always return the same hashcode // that way, it will end up in the same bucket return 12; } @Override public String toString() { return "SingleHashCode:" + code; } } @SuppressWarnings("unchecked") public void testInternalState_Buckets() { if (!isPutAddSupported() || !isPutChangeSupported()) { return; } final SingleHashCode one = new SingleHashCode("1"); final SingleHashCode two = new SingleHashCode("2"); final SingleHashCode three = new SingleHashCode("3"); final SingleHashCode four = new SingleHashCode("4"); final SingleHashCode five = new SingleHashCode("5"); final SingleHashCode six = new SingleHashCode("6"); final LRUMap map = new LRUMap(3, 1.0f); final int hashIndex = map.hashIndex(map.hash(one), 4); map.put((K) one, (V) "A"); map.put((K) two, (V) "B"); map.put((K) three, (V) "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((K) four, (V) "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((K) five, (V) "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((K) six, (V) "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); } @SuppressWarnings("unchecked") public void testInternalState_getEntry_int() { if (!isPutAddSupported() || !isPutChangeSupported()) { return; } final SingleHashCode one = new SingleHashCode("1"); final SingleHashCode two = new SingleHashCode("2"); final SingleHashCode three = new SingleHashCode("3"); final LRUMap map = new LRUMap(3, 1.0f); map.put((K) one, (V) "A"); map.put((K) two, (V) "B"); map.put((K) three, (V) "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 (final IndexOutOfBoundsException ex) {} try { map.getEntry(3); fail(); } catch (final IndexOutOfBoundsException ex) {} } public void testSynchronizedRemoveFromMapIterator() throws InterruptedException { final LRUMap map = new LRUMap(10000); final Map exceptions = new HashMap(); final ThreadGroup tg = new ThreadGroup(getName()) { @Override public void uncaughtException(final Thread t, final Throwable e) { exceptions.put(e, t.getName()); super.uncaughtException(t, e); } }; final int[] counter = new int[1]; counter[0] = 0; final Thread[] threads = new Thread[50]; for (int i = 0; i < threads.length; ++i) { threads[i] = new Thread(tg, "JUnit Thread " + i) { @Override public void run() { int i = 0; try { synchronized (this) { notifyAll(); wait(); } final Thread thread = Thread.currentThread(); while (i < 1000 && !interrupted()) { synchronized (map) { map.put(thread.getName() + "[" + ++i + "]", thread); } } synchronized (map) { for (final MapIterator iter = map.mapIterator(); iter.hasNext();) { iter.next(); if (iter.getValue() == this) { iter.remove(); } } } } catch (final InterruptedException e) { fail("Unexpected InterruptedException"); } if (i > 0) { synchronized (counter) { counter[0]++; } } } }; } for (final Thread thread : threads) { synchronized (thread) { thread.start(); thread.wait(); } } for (final Thread thread : threads) { synchronized (thread) { thread.notifyAll(); } } Thread.sleep(1000); for (final Thread thread : threads) { thread.interrupt(); } for (final Thread thread : threads) { synchronized (thread) { thread.join(); } } assertEquals("Exceptions have been thrown: " + exceptions, 0, exceptions.size()); assertTrue("Each thread should have put at least 1 element into the map, but only " + counter[0] + " did succeed", counter[0] >= threads.length); } public void testSynchronizedRemoveFromEntrySet() throws InterruptedException { final Map map = new LRUMap(10000); final Map exceptions = new HashMap(); final ThreadGroup tg = new ThreadGroup(getName()) { @Override public void uncaughtException(final Thread t, final Throwable e) { exceptions.put(e, t.getName()); super.uncaughtException(t, e); } }; final int[] counter = new int[1]; counter[0] = 0; final Thread[] threads = new Thread[50]; for (int i = 0; i < threads.length; ++i) { threads[i] = new Thread(tg, "JUnit Thread " + i) { @Override public void run() { int i = 0; try { synchronized (this) { notifyAll(); wait(); } final Thread thread = Thread.currentThread(); while (i < 1000 && !interrupted()) { synchronized (map) { map.put(thread.getName() + "[" + ++i + "]", thread); } } synchronized (map) { for (final Iterator> iter = map.entrySet().iterator(); iter.hasNext();) { final Map.Entry entry = iter.next(); if (entry.getValue() == this) { iter.remove(); } } } } catch (final InterruptedException e) { fail("Unexpected InterruptedException"); } if (i > 0) { synchronized (counter) { counter[0]++; } } } }; } for (final Thread thread : threads) { synchronized (thread) { thread.start(); thread.wait(); } } for (final Thread thread : threads) { synchronized (thread) { thread.notifyAll(); } } Thread.sleep(1000); for (final Thread thread : threads) { thread.interrupt(); } for (final Thread thread : threads) { synchronized (thread) { thread.join(); } } assertEquals("Exceptions have been thrown: " + exceptions, 0, exceptions.size()); assertTrue("Each thread should have put at least 1 element into the map, but only " + counter[0] + " did succeed", counter[0] >= threads.length); } public void testSynchronizedRemoveFromKeySet() throws InterruptedException { final Map map = new LRUMap(10000); final Map exceptions = new HashMap(); final ThreadGroup tg = new ThreadGroup(getName()) { @Override public void uncaughtException(final Thread t, final Throwable e) { exceptions.put(e, t.getName()); super.uncaughtException(t, e); } }; final int[] counter = new int[1]; counter[0] = 0; final Thread[] threads = new Thread[50]; for (int i = 0; i < threads.length; ++i) { threads[i] = new Thread(tg, "JUnit Thread " + i) { @Override public void run() { int i = 0; try { synchronized (this) { notifyAll(); wait(); } final Thread thread = Thread.currentThread(); while (i < 1000 && !interrupted()) { synchronized (map) { map.put(thread.getName() + "[" + ++i + "]", thread); } } synchronized (map) { for (final Iterator iter = map.keySet().iterator(); iter.hasNext();) { final String name = (String) iter.next(); if (name.substring(0, name.indexOf('[')).equals(getName())) { iter.remove(); } } } } catch (final InterruptedException e) { fail("Unexpected InterruptedException"); } if (i > 0) { synchronized (counter) { counter[0]++; } } } }; } for (final Thread thread : threads) { synchronized (thread) { thread.start(); thread.wait(); } } for (final Thread thread : threads) { synchronized (thread) { thread.notifyAll(); } } Thread.sleep(1000); for (final Thread thread : threads) { thread.interrupt(); } for (final Thread thread : threads) { synchronized (thread) { thread.join(); } } assertEquals("Exceptions have been thrown: " + exceptions, 0, exceptions.size()); assertTrue("Each thread should have put at least 1 element into the map, but only " + counter[0] + " did succeed", counter[0] >= threads.length); } public void testSynchronizedRemoveFromValues() throws InterruptedException { final Map map = new LRUMap(10000); final Map exceptions = new HashMap(); final ThreadGroup tg = new ThreadGroup(getName()) { @Override public void uncaughtException(final Thread t, final Throwable e) { exceptions.put(e, t.getName()); super.uncaughtException(t, e); } }; final int[] counter = new int[1]; counter[0] = 0; final Thread[] threads = new Thread[50]; for (int i = 0; i < threads.length; ++i) { threads[i] = new Thread(tg, "JUnit Thread " + i) { @Override public void run() { int i = 0; try { synchronized (this) { notifyAll(); wait(); } final Thread thread = Thread.currentThread(); while (i < 1000 && !interrupted()) { synchronized (map) { map.put(thread.getName() + "[" + ++i + "]", thread); } } synchronized (map) { for (final Iterator iter = map.values().iterator(); iter.hasNext();) { if (iter.next() == this) { iter.remove(); } } } } catch (final InterruptedException e) { fail("Unexpected InterruptedException"); } if (i > 0) { synchronized (counter) { counter[0]++; } } } }; } for (final Thread thread : threads) { synchronized (thread) { thread.start(); thread.wait(); } } for (final Thread thread : threads) { synchronized (thread) { thread.notifyAll(); } } Thread.sleep(1000); for (final Thread thread : threads) { thread.interrupt(); } for (final Thread thread : threads) { synchronized (thread) { thread.join(); } } assertEquals("Exceptions have been thrown: " + exceptions, 0, exceptions.size()); assertTrue("Each thread should have put at least 1 element into the map, but only " + counter[0] + " did succeed", counter[0] >= threads.length); } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/LRUMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/LRUMap.fullCollection.version4.obj"); // } /** * {@inheritDoc} */ @Override public LRUMap getMap() { return (LRUMap) super.getMap(); } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/ReferenceMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/ReferenceMapTest.java100664 21673 12243235516 31636 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.lang.ref.WeakReference; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength; /** * Tests for ReferenceMap. * * @version $Id: ReferenceMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ReferenceMapTest extends AbstractIterableMapTest { public ReferenceMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(ReferenceMapTest.class); } @Override public ReferenceMap makeObject() { return new ReferenceMap(ReferenceStrength.WEAK, ReferenceStrength.WEAK); } @Override public boolean isAllowNullKey() { return false; } @Override public boolean isAllowNullValue() { return false; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/ReferenceMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/ReferenceMap.fullCollection.version4.obj"); // } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") 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 (final NullPointerException ex) {} try { map.put((K) new Object(), null); fail(); } catch (final NullPointerException ex) {} try { map.put(null, (V) new Object()); fail(); } catch (final 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(Integer.valueOf(i), Integer.valueOf(i)); } gc(); for (int i = 0; i < 10; i++) { Integer I = Integer.valueOf(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] = Integer.valueOf(10 + i); map.put(Integer.valueOf(i), Integer.valueOf(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] = Integer.valueOf(10 + i); map.put(Integer.valueOf(i), Integer.valueOf(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] = Integer.valueOf(10 + i); map.put(Integer.valueOf(i), Integer.valueOf(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; @SuppressWarnings("unchecked") public Map buildRefMap() { final K key = (K) new Object(); final V value = (V) new Object(); keyReference = new WeakReference(key); valueReference = new WeakReference(value); final Map testMap = new ReferenceMap(ReferenceStrength.WEAK, ReferenceStrength.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 final 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: @SuppressWarnings("unused") final byte[] b = new byte[bytz]; bytz = bytz * 2; } } } @SuppressWarnings("unused") private static void gc() { try { // trigger GC final byte[][] tooLarge = new byte[1000000000][1000000000]; fail("you have too much RAM"); } catch (final OutOfMemoryError ex) { System.gc(); // ignore } } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/UnmodifiableSortedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/UnmodifiableSortedMap100664 6240 12243235516 31710 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.collections4.Unmodifiable; /** * Extension of {@link AbstractSortedMapTest} for exercising the * {@link UnmodifiableSortedMap} implementation. * * @since 3.0 * @version $Id: UnmodifiableSortedMapTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class UnmodifiableSortedMapTest extends AbstractSortedMapTest { public UnmodifiableSortedMapTest(final String testName) { super(testName); } //------------------------------------------------------------------- @Override public SortedMap makeObject() { return UnmodifiableSortedMap.unmodifiableSortedMap(new TreeMap()); } @Override public boolean isPutChangeSupported() { return false; } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public SortedMap makeFullMap() { final SortedMap m = new TreeMap(); addSampleMappings(m); return UnmodifiableSortedMap.unmodifiableSortedMap(m); } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { final SortedMap map = makeFullMap(); assertSame(map, UnmodifiableSortedMap.unmodifiableSortedMap(map)); try { UnmodifiableSortedMap.unmodifiableSortedMap(null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/UnmodifiableSortedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/UnmodifiableSortedMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/DefaultedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/DefaultedMapTest.java100664 12673 12243235516 31635 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.FactoryUtils; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.functors.ConstantFactory; /** * Extension of {@link AbstractMapTest} for exercising the * {@link DefaultedMap} implementation. * * @since 3.2 * @version $Id: DefaultedMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class DefaultedMapTest extends AbstractIterableMapTest { protected final Factory nullFactory = FactoryUtils.nullFactory(); public DefaultedMapTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public IterableMap makeObject() { return DefaultedMap.defaultedMap(new HashMap(), nullFactory); } //----------------------------------------------------------------------- @Override @SuppressWarnings("unchecked") public void testMapGet() { final Map map = new DefaultedMap((V) "NULL"); assertEquals(0, map.size()); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); map.put((K) "Key", (V) "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")); } @SuppressWarnings("unchecked") public void testMapGet2() { final HashMap base = new HashMap(); final Map map = DefaultedMap.defaultedMap(base, (V) "NULL"); assertEquals(0, map.size()); assertEquals(0, base.size()); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); map.put((K) "Key", (V) "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")); } @SuppressWarnings("unchecked") public void testMapGet3() { final HashMap base = new HashMap(); final Map map = DefaultedMap.defaultedMap(base, ConstantFactory.constantFactory((V) "NULL")); assertEquals(0, map.size()); assertEquals(0, base.size()); assertEquals(false, map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); map.put((K) "Key", (V) "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")); } @SuppressWarnings("unchecked") public void testMapGet4() { final HashMap base = new HashMap(); final Map map = DefaultedMap.defaultedMap(base, new Transformer() { public V transform(final K input) { if (input instanceof String) { return (V) "NULL"; } return (V) "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(Integer.valueOf(0))); map.put((K) "Key", (V) "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(Integer.valueOf(0))); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/DefaultedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/DefaultedMap.fullCollection.version4.obj"); // } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/AbstractMapTest.java100664 224465 12243235516 31527 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.collections4.AbstractObjectTest; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.collection.AbstractCollectionTest; import org.apache.commons.collections4.keyvalue.DefaultMapEntry; import org.apache.commons.collections4.set.AbstractSetTest; /** * Abstract test class for {@link java.util.Map} methods and contracts. *

* The forces at work here are similar to those in {@link AbstractCollectionTest}. * If your class implements the full Map interface, including optional * operations, simply extend this class, and implement the * {@link #makeObject()} method. *

* On the other hand, if your map implementation is weird, you may have to * override one or more of the other protected methods. They're described * below. *

* Entry Population Methods *

* Override these methods if your map requires special entries: * *

    *
  • {@link #getSampleKeys()} *
  • {@link #getSampleValues()} *
  • {@link #getNewSampleValues()} *
  • {@link #getOtherKeys()} *
  • {@link #getOtherValues()} *
* * Supported Operation Methods *

* Override these methods if your map doesn't support certain operations: * *

    *
  • {@link #isPutAddSupported()} *
  • {@link #isPutChangeSupported()} *
  • {@link #isSetValueSupported()} *
  • {@link #isRemoveSupported()} *
  • {@link #isGetStructuralModify()} *
  • {@link #isAllowDuplicateValues()} *
  • {@link #isAllowNullKey()} *
  • {@link #isAllowNullValue()} *
* * Fixture Methods *

* For tests on modification operations (puts and removes), fixtures are used * to verify that that operation results in correct state for the map and its * collection views. Basically, the modification is performed against your * map implementation, and an identical modification is performed against * a confirmed map implementation. A confirmed map implementation is * something like java.util.HashMap, which is known to conform * exactly to the {@link Map} contract. After the modification takes place * on both your map implementation and the confirmed map implementation, the * two maps are compared to see if their state is identical. The comparison * also compares the collection views to make sure they're still the same.

* * The upshot of all that is that any test that modifies the map in * any way will verify that all of the map's state is still * correct, including the state of its collection views. So for instance * if a key is removed by the map's key set's iterator, then the entry set * is checked to make sure the key/value pair no longer appears.

* * The {@link #map} field holds an instance of your collection implementation. * The {@link #entrySet}, {@link #keySet} and {@link #values} fields hold * that map's collection views. And the {@link #confirmed} field holds * an instance of the confirmed collection implementation. The * {@link #resetEmpty()} and {@link #resetFull()} methods set these fields to * empty or full maps, so that tests can proceed from a known state.

* * After a modification operation to both {@link #map} and {@link #confirmed}, * the {@link #verify()} method is invoked to compare the results. The * {@link #verify} method calls separate methods to verify the map and its three * collection views ({@link #verifyMap}, {@link #verifyEntrySet}, * {@link #verifyKeySet}, and {@link #verifyValues}). You may want to override * one of the verification methods to 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 * * @version $Id: AbstractMapTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractMapTest extends AbstractObjectTest { /** * 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 { final 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 AbstractMapTest(final String testName) { super(testName); } /** * Returns true if the maps produced by * {@link #makeObject()} 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 #makeObject()} 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 #makeObject()} 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 #makeObject()} 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 #makeObject()} 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 #makeObject()} 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 #makeObject()} 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 #makeObject()} 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 true if the maps produced by * {@link #makeObject()} and {@link #makeFullMap()} * provide fail-fast behavior on their various iterators. *

* Default implementation returns true. * Override if your collection class does not support fast failure. */ public boolean isFailFastExpected() { 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. */ @SuppressWarnings("unchecked") public K[] getSampleKeys() { final 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 (K[]) result; } @SuppressWarnings("unchecked") public K[] getOtherKeys() { return (K[]) getOtherNonNullStringElements(); } @SuppressWarnings("unchecked") public V[] getOtherValues() { return (V[]) getOtherNonNullStringElements(); } @SuppressWarnings("unchecked") protected List getAsList(final Object[] o) { final ArrayList result = new ArrayList(); for (final Object element : o) { result.add((E) element); } return result; } /** * Returns a list of string elements suitable for return by * {@link #getOtherKeys()} or {@link #getOtherValues}. * *

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" }; } /** * 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. */ @SuppressWarnings("unchecked") public V[] getSampleValues() { final 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 (V[]) 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. */ @SuppressWarnings("unchecked") public V[] getNewSampleValues() { final 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 (V[]) result; } /** * Helper method to add all the mappings described by * {@link #getSampleKeys()} and {@link #getSampleValues()}. */ public void addSampleMappings(final Map m) { final K[] keys = getSampleKeys(); final V[] values = getSampleValues(); for (int i = 0; i < keys.length; i++) { try { m.put(keys[i], values[i]); } catch (final 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 */ @Override public abstract Map makeObject(); /** * 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() { final Map m = makeObject(); addSampleMappings(m); return m; } /** * 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 static Map.Entry cloneMapEntry(final Map.Entry entry) { final HashMap map = new HashMap(); map.put(entry.getKey(), entry.getValue()); return map.entrySet().iterator().next(); } /** * Gets the compatability version, needed for package access. */ @Override 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() { final Object[] keys = getSampleKeys(); final Object[] values = getSampleValues(); final Object[] newValues = getNewSampleValues(); assertNotNull("failure in test: Must have keys returned from " + "getSampleKeys.", keys); assertNotNull("failure in test: Must have values returned from " + "getSampleValues.", values); // 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() { final Map em = makeObject(); assertTrue("failure in test: makeEmptyMap must return a non-null map.", em != null); final Map em2 = makeObject(); 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); final Map fm = makeFullMap(); assertTrue("failure in test: makeFullMap must return a non-null map.", fm != null); final 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, getMap().isEmpty()); verify(); resetFull(); assertEquals("Map.isEmpty() should return false with a non-empty map", false, getMap().isEmpty()); verify(); } /** * Tests Map.size() */ public void testMapSize() { resetEmpty(); assertEquals("Map.size() should be 0 with an empty map", 0, getMap().size()); verify(); resetFull(); assertEquals("Map.size() should equal the number of entries " + "in the map", getSampleKeys().length, getMap().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(); getMap().clear(); fail("Expected UnsupportedOperationException on clear"); } catch (final UnsupportedOperationException ex) {} return; } resetEmpty(); getMap().clear(); getConfirmed().clear(); verify(); resetFull(); getMap().clear(); getConfirmed().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() { final Object[] keys = getSampleKeys(); resetEmpty(); for (Object key : keys) { assertTrue("Map must not contain key when map is empty", !getMap().containsKey(key)); } verify(); resetFull(); for (Object key : keys) { assertTrue("Map must contain key for a mapping in the map. " + "Missing: " + key, getMap().containsKey(key)); } 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() { final Object[] values = getSampleValues(); resetEmpty(); for(int i = 0; i < values.length; i++) { assertTrue("Empty map must not contain value", !getMap().containsValue(values[i])); } verify(); resetFull(); for (final Object value : values) { assertTrue("Map must contain value for a mapping in the map.", getMap().containsValue(value)); } verify(); } /** * Tests Map.equals(Object) */ public void testMapEquals() { resetEmpty(); assertTrue("Empty maps unequal.", getMap().equals(confirmed)); verify(); resetFull(); assertTrue("Full maps unequal.", getMap().equals(confirmed)); verify(); resetFull(); // modify the HashMap created from the full map and make sure this // change results in map.equals() to return false. final Iterator iter = confirmed.keySet().iterator(); iter.next(); iter.remove(); assertTrue("Different maps equal.", !getMap().equals(confirmed)); resetFull(); assertTrue("equals(null) returned true.", !getMap().equals(null)); assertTrue("equals(new Object()) returned true.", !getMap().equals(new Object())); verify(); } /** * Tests Map.get(Object) */ public void testMapGet() { resetEmpty(); final Object[] keys = getSampleKeys(); final Object[] values = getSampleValues(); for (final Object key : keys) { assertTrue("Empty map.get() should return null.", getMap().get(key) == null); } verify(); resetFull(); for (int i = 0; i < keys.length; i++) { assertEquals("Full map.get() should return value from mapping.", values[i], getMap().get(keys[i])); } } /** * Tests Map.hashCode() */ public void testMapHashCode() { resetEmpty(); assertTrue("Empty maps have different hashCodes.", getMap().hashCode() == confirmed.hashCode()); resetFull(); assertTrue("Equal maps have different hashCodes.", getMap().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", getMap().toString() != null); verify(); resetFull(); assertTrue("Empty map toString() should not return null", getMap().toString() != null); verify(); } /** * Compare the current serialized form of the Map * against the canonical version in SVN. */ 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 final Map map = makeObject(); if (map instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { @SuppressWarnings("unchecked") final 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 SVN. */ 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 final Map map = makeFullMap(); if (map instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { @SuppressWarnings("unchecked") final 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(); final K[] keys = getSampleKeys(); final V[] values = getSampleValues(); final V[] newValues = getNewSampleValues(); if (isPutAddSupported()) { for (int i = 0; i < keys.length; i++) { final Object o = getMap().put(keys[i], values[i]); getConfirmed().put(keys[i], values[i]); verify(); assertTrue("First map.put should return null", o == null); assertTrue("Map should contain key after put", getMap().containsKey(keys[i])); assertTrue("Map should contain value after put", getMap().containsValue(values[i])); } if (isPutChangeSupported()) { for (int i = 0; i < keys.length; i++) { final Object o = getMap().put(keys[i], newValues[i]); getConfirmed().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", getMap().containsKey(keys[i])); assertTrue("Map should contain new value after put when changed", getMap().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", !getMap().containsValue(values[i])); } } } else { try { // two possible exception here, either valid getMap().put(keys[0], newValues[0]); fail("Expected IllegalArgumentException or UnsupportedOperationException on put (change)"); } catch (final IllegalArgumentException ex) { } catch (final UnsupportedOperationException ex) {} } } else if (isPutChangeSupported()) { resetEmpty(); try { getMap().put(keys[0], values[0]); fail("Expected UnsupportedOperationException or IllegalArgumentException on put (add) when fixed size"); } catch (final IllegalArgumentException ex) { } catch (final UnsupportedOperationException ex) { } resetFull(); int i = 0; for (final Iterator it = getMap().keySet().iterator(); it.hasNext() && i < newValues.length; i++) { final K key = it.next(); final V o = getMap().put(key, newValues[i]); final V value = getConfirmed().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", getMap() .containsKey(key)); assertTrue("Map should contain new value after put when changed", getMap() .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", !getMap().containsValue(values[i])); } } } else { try { getMap().put(keys[0], values[0]); fail("Expected UnsupportedOperationException on put (add)"); } catch (final UnsupportedOperationException ex) {} } } /** * Tests Map.put(null, value) */ public void testMapPutNullKey() { resetFull(); final V[] values = getSampleValues(); if (isPutAddSupported()) { if (isAllowNullKey()) { getMap().put(null, values[0]); } else { try { getMap().put(null, values[0]); fail("put(null, value) should throw NPE/IAE"); } catch (final NullPointerException ex) { } catch (final IllegalArgumentException ex) {} } } } /** * Tests Map.put(null, value) */ public void testMapPutNullValue() { resetFull(); final K[] keys = getSampleKeys(); if (isPutAddSupported()) { if (isAllowNullValue()) { getMap().put(keys[0], null); } else { try { getMap().put(keys[0], null); fail("put(key, null) should throw NPE/IAE"); } catch (final NullPointerException ex) { } catch (final IllegalArgumentException ex) {} } } } /** * Tests Map.putAll(map) */ public void testMapPutAll() { if (!isPutAddSupported()) { if (!isPutChangeSupported()) { final Map temp = makeFullMap(); resetEmpty(); try { getMap().putAll(temp); fail("Expected UnsupportedOperationException on putAll"); } catch (final UnsupportedOperationException ex) {} } return; } // check putAll OK adding empty map to empty map resetEmpty(); assertEquals(0, getMap().size()); getMap().putAll(new HashMap()); assertEquals(0, getMap().size()); // check putAll OK adding empty map to non-empty map resetFull(); final int size = getMap().size(); getMap().putAll(new HashMap()); assertEquals(size, getMap().size()); // check putAll OK adding non-empty map to empty map resetEmpty(); Map m2 = makeFullMap(); getMap().putAll(m2); getConfirmed().putAll(m2); verify(); // check putAll OK adding non-empty JDK map to empty map resetEmpty(); m2 = makeConfirmedMap(); final K[] keys = getSampleKeys(); final V[] values = getSampleValues(); for(int i = 0; i < keys.length; i++) { m2.put(keys[i], values[i]); } getMap().putAll(m2); getConfirmed().putAll(m2); verify(); // check putAll OK adding non-empty JDK map to non-empty map resetEmpty(); m2 = makeConfirmedMap(); getMap().put(keys[0], values[0]); getConfirmed().put(keys[0], values[0]); verify(); for(int i = 1; i < keys.length; i++) { m2.put(keys[i], values[i]); } getMap().putAll(m2); getConfirmed().putAll(m2); verify(); } /** * Tests Map.remove(Object) */ public void testMapRemove() { if (!isRemoveSupported()) { try { resetFull(); getMap().remove(getMap().keySet().iterator().next()); fail("Expected UnsupportedOperationException on remove"); } catch (final UnsupportedOperationException ex) {} return; } resetEmpty(); final Object[] keys = getSampleKeys(); final Object[] values = getSampleValues(); for (final Object key : keys) { final Object o = getMap().remove(key); assertTrue("First map.remove should return null", o == null); } verify(); resetFull(); for (int i = 0; i < keys.length; i++) { final Object o = getMap().remove(keys[i]); getConfirmed().remove(keys[i]); verify(); assertEquals("map.remove with valid key should return value", values[i], o); } final Object[] other = getOtherKeys(); resetFull(); final int size = getMap().size(); for (final Object element : other) { final Object o = getMap().remove(element); assertNull("map.remove for nonexistent key should return null", o); assertEquals("map.remove for nonexistent key should not " + "shrink map", size, getMap().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 = getMap().values(); assertTrue(getMap().size() > 0); assertTrue(values.size() > 0); values.clear(); assertTrue(getMap().size() == 0); assertTrue(values.size() == 0); // clear map, reflected in values resetFull(); values = getMap().values(); assertTrue(getMap().size() > 0); assertTrue(values.size() > 0); getMap().clear(); assertTrue(getMap().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 = getMap().keySet(); assertTrue(getMap().size() > 0); assertTrue(keySet.size() > 0); keySet.clear(); assertTrue(getMap().size() == 0); assertTrue(keySet.size() == 0); // clear map, reflected in values resetFull(); keySet = getMap().keySet(); assertTrue(getMap().size() > 0); assertTrue(keySet.size() > 0); getMap().clear(); assertTrue(getMap().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 = getMap().entrySet(); assertTrue(getMap().size() > 0); assertTrue(entrySet.size() > 0); entrySet.clear(); assertTrue(getMap().size() == 0); assertTrue(entrySet.size() == 0); // clear map, reflected in values resetFull(); entrySet = getMap().entrySet(); assertTrue(getMap().size() > 0); assertTrue(entrySet.size() > 0); getMap().clear(); assertTrue(getMap().size() == 0); assertTrue(entrySet.size() == 0); } //----------------------------------------------------------------------- public void testEntrySetContains1() { resetFull(); final Set> entrySet = getMap().entrySet(); final Map.Entry entry = entrySet.iterator().next(); assertEquals(true, entrySet.contains(entry)); } public void testEntrySetContains2() { resetFull(); final Set> entrySet = getMap().entrySet(); final Map.Entry entry = entrySet.iterator().next(); final Map.Entry test = cloneMapEntry(entry); assertEquals(true, entrySet.contains(test)); } @SuppressWarnings("unchecked") public void testEntrySetContains3() { resetFull(); final Set> entrySet = getMap().entrySet(); final Map.Entry entry = entrySet.iterator().next(); final HashMap temp = new HashMap(); temp.put(entry.getKey(), (V) "A VERY DIFFERENT VALUE"); final Map.Entry test = temp.entrySet().iterator().next(); assertEquals(false, entrySet.contains(test)); } public void testEntrySetRemove1() { if (!isRemoveSupported()) { return; } resetFull(); final int size = getMap().size(); final Set> entrySet = getMap().entrySet(); final Map.Entry entry = entrySet.iterator().next(); final K key = entry.getKey(); assertEquals(true, entrySet.remove(entry)); assertEquals(false, getMap().containsKey(key)); assertEquals(size - 1, getMap().size()); } public void testEntrySetRemove2() { if (!isRemoveSupported()) { return; } resetFull(); final int size = getMap().size(); final Set> entrySet = getMap().entrySet(); final Map.Entry entry = entrySet.iterator().next(); final K key = entry.getKey(); final Map.Entry test = cloneMapEntry(entry); assertEquals(true, entrySet.remove(test)); assertEquals(false, getMap().containsKey(key)); assertEquals(size - 1, getMap().size()); } @SuppressWarnings("unchecked") public void testEntrySetRemove3() { if (!isRemoveSupported()) { return; } resetFull(); final int size = getMap().size(); final Set> entrySet = getMap().entrySet(); final Map.Entry entry = entrySet.iterator().next(); final K key = entry.getKey(); final HashMap temp = new HashMap(); temp.put(entry.getKey(), (V) "A VERY DIFFERENT VALUE"); final Map.Entry test = temp.entrySet().iterator().next(); assertEquals(false, entrySet.remove(test)); assertEquals(true, getMap().containsKey(key)); assertEquals(size, getMap().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(); final V[] sampleValues = getSampleValues(); final Collection values = getMap().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 (final 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.", !getMap().containsValue(sampleValues[i])); } } } /** * Tests values.removeAll. */ public void testValuesRemoveAll() { resetFull(); final Collection values = getMap().values(); final List sampleValuesAsList = Arrays.asList(getSampleValues()); if (!values.equals(sampleValuesAsList)) { return; } try { assertFalse(values.removeAll(Collections. emptySet())); } catch (final UnsupportedOperationException e) { // if values.removeAll is unsupported, just skip this test return; } assertEquals(sampleValuesAsList.size(), getMap().size()); try { assertTrue(values.removeAll(sampleValuesAsList)); } catch (final UnsupportedOperationException e) { // if values.removeAll is unsupported, just skip this test return; } assertTrue(getMap().isEmpty()); } /** * Test values.retainAll. */ public void testValuesRetainAll() { resetFull(); final Collection values = getMap().values(); final List sampleValuesAsList = Arrays.asList(getSampleValues()); if (!values.equals(sampleValuesAsList)) { return; } try { assertFalse(values.retainAll(sampleValuesAsList)); } catch (final UnsupportedOperationException e) { // if values.retainAll is unsupported, just skip this test return; } assertEquals(sampleValuesAsList.size(), getMap().size()); try { assertTrue(values.retainAll(Collections. emptySet())); } catch (final UnsupportedOperationException e) { // if values.retainAll is unsupported, just skip this test return; } assertTrue(getMap().isEmpty()); } /** * Verifies that values.iterator.remove changes the underlying map. */ @SuppressWarnings("boxing") // OK in test code public void testValuesIteratorRemoveChangesMap() { resetFull(); final List sampleValuesAsList = Arrays.asList(getSampleValues()); final Map cardinality = CollectionUtils.getCardinalityMap(sampleValuesAsList); final Collection values = getMap().values(); for (final Iterator iter = values.iterator(); iter.hasNext();) { final V value = iter.next(); Integer count = cardinality.get(value); if (count == null) { return; } try { iter.remove(); cardinality.put(value, --count); } catch (final UnsupportedOperationException e) { // if values.iterator.remove is unsupported, just skip this test return; } final boolean expected = count > 0; final StringBuilder msg = new StringBuilder("Value should "); msg.append(expected ? "yet " : "no longer "); msg.append("be present in the underlying map"); assertEquals(msg.toString(), expected, getMap().containsValue(value)); } assertTrue(getMap().isEmpty()); } /** * 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(); final K[] sampleKeys = getSampleKeys(); final Set keys = getMap().keySet(); for (int i = 0; i < sampleKeys.length; i++) { try { keys.remove(sampleKeys[i]); } catch (final UnsupportedOperationException e) { // if key.remove is unsupported, just skip this test return; } assertTrue( "Key should have been removed from the underlying map.", !getMap().containsKey(sampleKeys[i])); } } /** * Test keySet.removeAll. */ public void testKeySetRemoveAll() { resetFull(); final Set keys = getMap().keySet(); final List sampleKeysAsList = Arrays.asList(getSampleKeys()); if (!keys.equals(sampleKeysAsList)) { return; } try { assertFalse(keys.removeAll(Collections. emptySet())); } catch (final UnsupportedOperationException e) { return; } assertEquals(sampleKeysAsList, keys); try { assertTrue(keys.removeAll(sampleKeysAsList)); } catch (final UnsupportedOperationException e) { return; } assertTrue(getMap().isEmpty()); } /** * Test keySet.retainAll. */ public void testKeySetRetainAll() { resetFull(); final Set keys = getMap().keySet(); final List sampleKeysAsList = Arrays.asList(getSampleKeys()); if (!keys.equals(sampleKeysAsList)) { return; } try { assertFalse(keys.retainAll(sampleKeysAsList)); } catch (final UnsupportedOperationException e) { return; } assertEquals(sampleKeysAsList, keys); try { assertTrue(keys.retainAll(Collections. emptySet())); } catch (final UnsupportedOperationException e) { return; } assertTrue(getMap().isEmpty()); } /** * Verify that keySet.iterator.remove changes the underlying map. */ public void testKeySetIteratorRemoveChangesMap() { resetFull(); for (final Iterator iter = getMap().keySet().iterator(); iter.hasNext();) { final K key = iter.next(); try { iter.remove(); } catch (final UnsupportedOperationException e) { return; } assertFalse(getMap().containsKey(key)); } } /** * Tests that the {@link Map#entrySet} set is backed by * the underlying map by removing from the entrySet set * and testing if the entry was removed from the map. */ public void testEntrySetRemoveChangesMap() { resetFull(); final K[] sampleKeys = getSampleKeys(); final V[] sampleValues = getSampleValues(); final Set> entrySet = getMap().entrySet(); for (int i = 0; i < sampleKeys.length; i++) { try { entrySet.remove(new DefaultMapEntry(sampleKeys[i], sampleValues[i])); } catch (final UnsupportedOperationException e) { // if entrySet removal is unsupported, just skip this test return; } assertTrue( "Entry should have been removed from the underlying map.", !getMap().containsKey(sampleKeys[i])); } } /** * Test entrySet.removeAll. */ public void testEntrySetRemoveAll() { resetFull(); final K[] sampleKeys = getSampleKeys(); final V[] sampleValues = getSampleValues(); //verify map looks as expected: for (int i = 0; i < sampleKeys.length; i++) { if (!getMap().containsKey(sampleKeys[i])) { return; } final V value = sampleValues[i]; final V test = getMap().get(sampleKeys[i]); if (value == test || value != null && value.equals(test)) { continue; } return; } final Set> entrySet = getMap().entrySet(); final HashSet> comparisonSet = new HashSet>(entrySet); try { assertFalse(entrySet.removeAll(Collections.> emptySet())); } catch (final UnsupportedOperationException e) { return; } assertEquals(sampleKeys.length, getMap().size()); try { assertTrue(entrySet.removeAll(comparisonSet)); } catch (final UnsupportedOperationException e) { return; } assertTrue(getMap().isEmpty()); } /** * Test entrySet.retainAll. */ public void testEntrySetRetainAll() { resetFull(); final K[] sampleKeys = getSampleKeys(); final V[] sampleValues = getSampleValues(); //verify map looks as expected: for (int i = 0; i < sampleKeys.length; i++) { if (!getMap().containsKey(sampleKeys[i])) { return; } final V value = sampleValues[i]; final V test = getMap().get(sampleKeys[i]); if (value == test || value != null && value.equals(test)) { continue; } return; } final Set> entrySet = getMap().entrySet(); final HashSet> comparisonSet = new HashSet>(entrySet); try { assertFalse(entrySet.retainAll(comparisonSet)); } catch (final UnsupportedOperationException e) { return; } assertEquals(sampleKeys.length, getMap().size()); try { assertTrue(entrySet.retainAll(Collections.> emptySet())); } catch (final UnsupportedOperationException e) { return; } assertTrue(getMap().isEmpty()); } /** * Verify that entrySet.iterator.remove changes the underlying map. */ public void testEntrySetIteratorRemoveChangesMap() { resetFull(); for (final Iterator> iter = getMap().entrySet().iterator(); iter.hasNext();) { final K key = iter.next().getKey(); try { iter.remove(); } catch (final UnsupportedOperationException e) { return; } assertFalse(getMap().containsKey(key)); } } /** * 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 */ @SuppressWarnings("unchecked") private Map.Entry[] makeEntryArray(final K[] keys, final V[] values) { final Map.Entry[] result = new Map.Entry[keys.length]; for (int i = 0; i < keys.length; i++) { final Map map = makeConfirmedMap(); map.put(keys[i], values[i]); result[i] = map.entrySet().iterator().next(); } return result; } /** * Bulk test {@link Map#entrySet()}. This method runs through all of * the tests in {@link AbstractSetTest}. * After modification operations, {@link #verify()} is invoked to ensure * that the map and the other collection views are still valid. * * @return a {@link AbstractSetTest} instance for testing the map's entry set */ public BulkTest bulkTestMapEntrySet() { return new TestMapEntrySet(); } public class TestMapEntrySet extends AbstractSetTest> { public TestMapEntrySet() { super("MapEntrySet"); } // Have to implement manually; entrySet doesn't support addAll /** * {@inheritDoc} */ @Override public Entry[] getFullElements() { return getFullNonNullElements(); } /** * {@inheritDoc} */ @Override public Map.Entry[] getFullNonNullElements() { final K[] k = getSampleKeys(); final V[] v = getSampleValues(); return makeEntryArray(k, v); } // Have to implement manually; entrySet doesn't support addAll @Override public Map.Entry[] getOtherElements() { final K[] k = getOtherKeys(); final V[] v = getOtherValues(); return makeEntryArray(k, v); } @Override public Set> makeObject() { return AbstractMapTest.this.makeObject().entrySet(); } @Override public Set> makeFullCollection() { return makeFullMap().entrySet(); } @Override public boolean isAddSupported() { // Collection views don't support add operations. return false; } @Override public boolean isRemoveSupported() { // Entry set should only support remove if map does return AbstractMapTest.this.isRemoveSupported(); } public boolean isGetStructuralModify() { return AbstractMapTest.this.isGetStructuralModify(); } @Override public boolean isTestSerialization() { return false; } @Override public void resetFull() { AbstractMapTest.this.resetFull(); setCollection(AbstractMapTest.this.getMap().entrySet()); TestMapEntrySet.this.setConfirmed(AbstractMapTest.this.getConfirmed().entrySet()); } @Override public void resetEmpty() { AbstractMapTest.this.resetEmpty(); setCollection(AbstractMapTest.this.getMap().entrySet()); TestMapEntrySet.this.setConfirmed(AbstractMapTest.this.getConfirmed().entrySet()); } public void testMapEntrySetIteratorEntry() { resetFull(); final Iterator> it = getCollection().iterator(); int count = 0; while (it.hasNext()) { final Map.Entry entry = it.next(); assertEquals(true, AbstractMapTest.this.getMap().containsKey(entry.getKey())); assertEquals(true, AbstractMapTest.this.getMap().containsValue(entry.getValue())); if (!isGetStructuralModify()) { assertEquals(AbstractMapTest.this.getMap().get(entry.getKey()), entry.getValue()); } count++; } assertEquals(getCollection().size(), count); } public void testMapEntrySetIteratorEntrySetValue() { final K key1 = getSampleKeys()[0]; final K key2 = getSampleKeys().length == 1 ? getSampleKeys()[0] : getSampleKeys()[1]; final V newValue1 = getNewSampleValues()[0]; final V 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.getCollection().iterator(); final Map.Entry entry1 = getEntry(it, key1); it = TestMapEntrySet.this.getCollection().iterator(); final Map.Entry entry2 = getEntry(it, key2); Iterator> itConfirmed = TestMapEntrySet.this.getConfirmed().iterator(); final Map.Entry entryConfirmed1 = getEntry(itConfirmed, key1); itConfirmed = TestMapEntrySet.this.getConfirmed().iterator(); final Map.Entry entryConfirmed2 = getEntry(itConfirmed, key2); verify(); if (!isSetValueSupported()) { try { entry1.setValue(newValue1); } catch (final UnsupportedOperationException ex) { } return; } entry1.setValue(newValue1); entryConfirmed1.setValue(newValue1); assertEquals(newValue1, entry1.getValue()); assertEquals(true, AbstractMapTest.this.getMap().containsKey(entry1.getKey())); assertEquals(true, AbstractMapTest.this.getMap().containsValue(newValue1)); assertEquals(newValue1, AbstractMapTest.this.getMap().get(entry1.getKey())); verify(); entry1.setValue(newValue1); entryConfirmed1.setValue(newValue1); assertEquals(newValue1, entry1.getValue()); assertEquals(true, AbstractMapTest.this.getMap().containsKey(entry1.getKey())); assertEquals(true, AbstractMapTest.this.getMap().containsValue(newValue1)); assertEquals(newValue1, AbstractMapTest.this.getMap().get(entry1.getKey())); verify(); entry2.setValue(newValue2); entryConfirmed2.setValue(newValue2); assertEquals(newValue2, entry2.getValue()); assertEquals(true, AbstractMapTest.this.getMap().containsKey(entry2.getKey())); assertEquals(true, AbstractMapTest.this.getMap().containsValue(newValue2)); assertEquals(newValue2, AbstractMapTest.this.getMap().get(entry2.getKey())); verify(); } public Map.Entry getEntry(final Iterator> itConfirmed, final K key) { Map.Entry entry = null; while (itConfirmed.hasNext()) { final Map.Entry temp = 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()) { return; } resetFull(); assertEquals(false, getCollection().remove(null)); assertEquals(false, getCollection().remove(new Object())); } @Override public void verify() { super.verify(); AbstractMapTest.this.verify(); } } /** * Bulk test {@link Map#keySet()}. This method runs through all of * the tests in {@link AbstractSetTest}. * After modification operations, {@link #verify()} is invoked to ensure * that the map and the other collection views are still valid. * * @return a {@link AbstractSetTest} instance for testing the map's key set */ public BulkTest bulkTestMapKeySet() { return new TestMapKeySet(); } public class TestMapKeySet extends AbstractSetTest { public TestMapKeySet() { super(""); } @Override public K[] getFullElements() { return getSampleKeys(); } @Override public K[] getOtherElements() { return getOtherKeys(); } @Override public Set makeObject() { return AbstractMapTest.this.makeObject().keySet(); } @Override public Set makeFullCollection() { return AbstractMapTest.this.makeFullMap().keySet(); } @Override public boolean isNullSupported() { return AbstractMapTest.this.isAllowNullKey(); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return AbstractMapTest.this.isRemoveSupported(); } @Override public boolean isTestSerialization() { return false; } @Override public void resetEmpty() { AbstractMapTest.this.resetEmpty(); setCollection(AbstractMapTest.this.getMap().keySet()); TestMapKeySet.this.setConfirmed(AbstractMapTest.this.getConfirmed().keySet()); } @Override public void resetFull() { AbstractMapTest.this.resetFull(); setCollection(AbstractMapTest.this.getMap().keySet()); TestMapKeySet.this.setConfirmed(AbstractMapTest.this.getConfirmed().keySet()); } @Override public void verify() { super.verify(); AbstractMapTest.this.verify(); } } /** * Bulk test {@link Map#values()}. This method runs through all of * the tests in {@link AbstractCollectionTest}. * After modification operations, {@link #verify()} is invoked to ensure * that the map and the other collection views are still valid. * * @return a {@link AbstractCollectionTest} instance for testing the map's * values collection */ public BulkTest bulkTestMapValues() { return new TestMapValues(); } public class TestMapValues extends AbstractCollectionTest { public TestMapValues() { super(""); } @Override public V[] getFullElements() { return getSampleValues(); } @Override public V[] getOtherElements() { return getOtherValues(); } @Override public Collection makeObject() { return AbstractMapTest.this.makeObject().values(); } @Override public Collection makeFullCollection() { return AbstractMapTest.this.makeFullMap().values(); } @Override public boolean isNullSupported() { return AbstractMapTest.this.isAllowNullKey(); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return AbstractMapTest.this.isRemoveSupported(); } @Override public boolean isTestSerialization() { return false; } @Override public boolean areEqualElementsDistinguishable() { // equal values are associated with different keys, so they are // distinguishable. return true; } @Override public Collection makeConfirmedCollection() { // never gets called, reset methods are overridden return null; } @Override public Collection makeConfirmedFullCollection() { // never gets called, reset methods are overridden return null; } @Override public void resetFull() { AbstractMapTest.this.resetFull(); setCollection(map.values()); TestMapValues.this.setConfirmed(AbstractMapTest.this.getConfirmed().values()); } @Override public void resetEmpty() { AbstractMapTest.this.resetEmpty(); setCollection(map.values()); TestMapValues.this.setConfirmed(AbstractMapTest.this.getConfirmed().values()); } @Override public void verify() { super.verify(); AbstractMapTest.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 = makeObject(); 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(); final K[] k = getSampleKeys(); final V[] 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 = getMap().keySet(); // see verifyValues: retrieve the values collection only when verifying them // this.values = getMap().values(); this.entrySet = getMap().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() { final int size = getConfirmed().size(); final boolean empty = getConfirmed().isEmpty(); assertEquals("Map should be same size as HashMap", size, getMap().size()); assertEquals("Map should be empty if HashMap is", empty, getMap().isEmpty()); assertEquals("hashCodes should be the same", getConfirmed().hashCode(), getMap().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", getMap().equals(getConfirmed())); // 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). // When comparing two maps, the entries in the map have to be accessed // (usually with the get(Object) method). In the case of the LRUMap, this // also alters the modCount as moveToMRU is called for the retrieved entry. // Imho, the modCount should not be increased for a read-only operation. } public void verifyEntrySet() { final int size = getConfirmed().size(); final boolean empty = getConfirmed().isEmpty(); assertEquals("entrySet should be same size as HashMap's" + "\nTest: " + entrySet + "\nReal: " + getConfirmed().entrySet(), size, entrySet.size()); assertEquals("entrySet should be empty if HashMap is" + "\nTest: " + entrySet + "\nReal: " + getConfirmed().entrySet(), empty, entrySet.isEmpty()); assertTrue("entrySet should contain all HashMap's elements" + "\nTest: " + entrySet + "\nReal: " + getConfirmed().entrySet(), entrySet.containsAll(getConfirmed().entrySet())); assertEquals("entrySet hashCodes should be the same" + "\nTest: " + entrySet + "\nReal: " + getConfirmed().entrySet(), getConfirmed().entrySet().hashCode(), entrySet.hashCode()); assertEquals("Map's entry set should still equal HashMap's", getConfirmed().entrySet(), entrySet); } public void verifyKeySet() { final int size = getConfirmed().size(); final boolean empty = getConfirmed().isEmpty(); assertEquals("keySet should be same size as HashMap's" + "\nTest: " + keySet + "\nReal: " + getConfirmed().keySet(), size, keySet.size()); assertEquals("keySet should be empty if HashMap is" + "\nTest: " + keySet + "\nReal: " + getConfirmed().keySet(), empty, keySet.isEmpty()); assertTrue("keySet should contain all HashMap's elements" + "\nTest: " + keySet + "\nReal: " + getConfirmed().keySet(), keySet.containsAll(getConfirmed().keySet())); assertEquals("keySet hashCodes should be the same" + "\nTest: " + keySet + "\nReal: " + getConfirmed().keySet(), getConfirmed().keySet().hashCode(), keySet.hashCode()); assertEquals("Map's key set should still equal HashMap's", getConfirmed().keySet(), keySet); } public void verifyValues() { final List known = new ArrayList(getConfirmed().values()); // bug in IBM JDK: IBM J9 VM build 2.4, JRE 1.6.0 IBM J9 2.4 Linux x86-32 jvmxi3260sr12-20121024_126067 // a call to values() on an empty map retrieved via TreeMap#headMap or tailMap // will render the values view unusable: resulting in NullPointerExceptions or missing values // it will also not recover, as the value view is cached internally values = getMap().values(); final List test = new ArrayList(values); final int size = getConfirmed().size(); final boolean empty = getConfirmed().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 (final V v : known) { final boolean removed = test.remove(v); 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. */ @Override public void tearDown() throws Exception { map = null; keySet = null; entrySet = null; values = null; confirmed = null; } /** * Get the map. * @return Map */ public Map getMap() { return map; } /** * Get the confirmed. * @return Map */ public Map getConfirmed() { return confirmed; } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/Flat3MapTest.java100664 40414 12243235516 30703 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Iterator; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.iterators.AbstractMapIteratorTest; /** * JUnit tests. * * @version $Id: Flat3MapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class Flat3MapTest extends AbstractIterableMapTest { private static final Integer ONE = Integer.valueOf(1); private static final Integer TWO = Integer.valueOf(2); private static final Integer THREE = Integer.valueOf(3); private static final String TEN = "10"; private static final String TWENTY = "20"; private static final String THIRTY = "30"; public Flat3MapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(Flat3MapTest.class); } @Override public Flat3Map makeObject() { return new Flat3Map(); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testEquals1() { final Flat3Map map1 = makeObject(); map1.put((K) "a", (V) "testA"); map1.put((K) "b", (V) "testB"); final Flat3Map map2 = makeObject(); map2.put((K) "a", (V) "testB"); map2.put((K) "b", (V) "testA"); assertEquals(false, map1.equals(map2)); } @SuppressWarnings("unchecked") public void testEquals2() { final Flat3Map map1 = makeObject(); map1.put((K) "a", (V) "testA"); map1.put((K) "b", (V) "testB"); final Flat3Map map2 = makeObject(); map2.put((K) "a", (V) "testB"); map2.put((K) "c", (V) "testA"); assertEquals(false, map1.equals(map2)); } @SuppressWarnings("unchecked") public void testClone2() { final Flat3Map map = makeObject(); assertEquals(0, map.size()); map.put((K) ONE, (V) TEN); map.put((K) TWO, (V) 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) final Flat3Map cloned = 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((K) TEN, (V) ONE); map.put((K) TWENTY, (V) 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)); } @SuppressWarnings("unchecked") public void testClone4() { final Flat3Map map = makeObject(); assertEquals(0, map.size()); map.put((K) ONE, (V) TEN); map.put((K) TWO, (V) TWENTY); map.put((K) TEN, (V) ONE); map.put((K) TWENTY, (V) TWO); // clone works (size = 4) final Flat3Map cloned = 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 { final Flat3Map map = makeObject(); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(map); final byte[] bytes = bout.toByteArray(); out.close(); final ByteArrayInputStream bin = new ByteArrayInputStream(bytes); final ObjectInputStream in = new ObjectInputStream(bin); final Flat3Map ser = (Flat3Map) in.readObject(); in.close(); assertEquals(0, map.size()); assertEquals(0, ser.size()); } @SuppressWarnings("unchecked") public void testSerialisation2() throws Exception { final Flat3Map map = makeObject(); map.put((K) ONE, (V) TEN); map.put((K) TWO, (V) TWENTY); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(map); final byte[] bytes = bout.toByteArray(); out.close(); final ByteArrayInputStream bin = new ByteArrayInputStream(bytes); final ObjectInputStream in = new ObjectInputStream(bin); final 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)); } @SuppressWarnings("unchecked") public void testSerialisation4() throws Exception { final Flat3Map map = makeObject(); map.put((K) ONE, (V) TEN); map.put((K) TWO, (V) TWENTY); map.put((K) TEN, (V) ONE); map.put((K) TWENTY, (V) TWO); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bout); out.writeObject(map); final byte[] bytes = bout.toByteArray(); out.close(); final ByteArrayInputStream bin = new ByteArrayInputStream(bytes); final ObjectInputStream in = new ObjectInputStream(bin); final 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)); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testEntryIteratorSetValue1() throws Exception { final Flat3Map map = makeObject(); map.put((K) ONE, (V) TEN); map.put((K) TWO, (V) TWENTY); map.put((K) THREE, (V) THIRTY); final Iterator> it = map.entrySet().iterator(); final Map.Entry entry = it.next(); entry.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); assertEquals(true, map.containsKey(THREE)); assertEquals("NewValue", map.get(ONE)); assertEquals(TWENTY, map.get(TWO)); assertEquals(THIRTY, map.get(THREE)); } @SuppressWarnings("unchecked") public void testEntryIteratorSetValue2() throws Exception { final Flat3Map map = makeObject(); map.put((K) ONE, (V) TEN); map.put((K) TWO, (V) TWENTY); map.put((K) THREE, (V) THIRTY); final Iterator> it = map.entrySet().iterator(); it.next(); final Map.Entry entry = it.next(); entry.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); assertEquals(true, map.containsKey(THREE)); assertEquals(TEN, map.get(ONE)); assertEquals("NewValue", map.get(TWO)); assertEquals(THIRTY, map.get(THREE)); } @SuppressWarnings("unchecked") public void testEntryIteratorSetValue3() throws Exception { final Flat3Map map = makeObject(); map.put((K) ONE, (V) TEN); map.put((K) TWO, (V) TWENTY); map.put((K) THREE, (V) THIRTY); final Iterator> it = map.entrySet().iterator(); it.next(); it.next(); final Map.Entry entry = it.next(); entry.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); assertEquals(true, map.containsKey(THREE)); assertEquals(TEN, map.get(ONE)); assertEquals(TWENTY, map.get(TWO)); assertEquals("NewValue", map.get(THREE)); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testMapIteratorSetValue1() throws Exception { final Flat3Map map = makeObject(); map.put((K) ONE, (V) TEN); map.put((K) TWO, (V) TWENTY); map.put((K) THREE, (V) THIRTY); final MapIterator it = map.mapIterator(); it.next(); it.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); assertEquals(true, map.containsKey(THREE)); assertEquals("NewValue", map.get(ONE)); assertEquals(TWENTY, map.get(TWO)); assertEquals(THIRTY, map.get(THREE)); } @SuppressWarnings("unchecked") public void testMapIteratorSetValue2() throws Exception { final Flat3Map map = makeObject(); map.put((K) ONE, (V) TEN); map.put((K) TWO, (V) TWENTY); map.put((K) THREE, (V) THIRTY); final MapIterator it = map.mapIterator(); it.next(); it.next(); it.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); assertEquals(true, map.containsKey(THREE)); assertEquals(TEN, map.get(ONE)); assertEquals("NewValue", map.get(TWO)); assertEquals(THIRTY, map.get(THREE)); } @SuppressWarnings("unchecked") public void testMapIteratorSetValue3() throws Exception { final Flat3Map map = makeObject(); map.put((K) ONE, (V) TEN); map.put((K) TWO, (V) TWENTY); map.put((K) THREE, (V) THIRTY); final MapIterator it = map.mapIterator(); it.next(); it.next(); it.next(); it.setValue((V) "NewValue"); assertEquals(3, map.size()); assertEquals(true, map.containsKey(ONE)); assertEquals(true, map.containsKey(TWO)); assertEquals(true, map.containsKey(THREE)); assertEquals(TEN, map.get(ONE)); assertEquals(TWENTY, map.get(TWO)); assertEquals("NewValue", map.get(THREE)); } //----------------------------------------------------------------------- @Override public BulkTest bulkTestMapIterator() { return new TestFlatMapIterator(); } public class TestFlatMapIterator extends AbstractMapIteratorTest { public TestFlatMapIterator() { super("TestFlatMapIterator"); } @Override public V[] addSetValues() { return Flat3MapTest.this.getNewSampleValues(); } @Override public boolean supportsRemove() { return Flat3MapTest.this.isRemoveSupported(); } @Override public boolean supportsSetValue() { return Flat3MapTest.this.isSetValueSupported(); } @Override public MapIterator makeEmptyIterator() { resetEmpty(); return Flat3MapTest.this.getMap().mapIterator(); } @Override public MapIterator makeObject() { resetFull(); return Flat3MapTest.this.getMap().mapIterator(); } @Override public IterableMap getMap() { // assumes makeFullMapIterator() called first return Flat3MapTest.this.getMap(); } @Override public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return Flat3MapTest.this.getConfirmed(); } @Override public void verify() { super.verify(); Flat3MapTest.this.verify(); } } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/Flat3Map.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/Flat3Map.fullCollection.version4.obj"); // } public void testCollections261() { final Flat3Map m = new Flat3Map(); m.put( Integer.valueOf(1), Integer.valueOf(1) ); m.put( Integer.valueOf(0), Integer.valueOf(0) ); assertEquals( Integer.valueOf(1), m.remove( Integer.valueOf(1) ) ); assertEquals( Integer.valueOf(0), m.remove( Integer.valueOf(0) ) ); m.put( Integer.valueOf(2), Integer.valueOf(2) ); m.put( Integer.valueOf(1), Integer.valueOf(1) ); m.put( Integer.valueOf(0), Integer.valueOf(0) ); assertEquals( Integer.valueOf(2), m.remove( Integer.valueOf(2) ) ); assertEquals( Integer.valueOf(1), m.remove( Integer.valueOf(1) ) ); assertEquals( Integer.valueOf(0), m.remove( Integer.valueOf(0) ) ); } public void testToString() { final Flat3Map m = new Flat3Map(); final String string0 = m.toString(); assertNotNull(string0); m.put( Integer.valueOf(1), Integer.valueOf(1) ); final String string1 = m.toString(); assertNotNull(string1); assertNotSame(string0, string1); m.put( Integer.valueOf(0), Integer.valueOf(0) ); final String string2 = m.toString(); assertNotNull(string2); assertNotSame(string0, string2); assertNotSame(string1, string2); m.put( Integer.valueOf(2), Integer.valueOf(2) ); final String string3 = m.toString(); assertNotNull(string3); assertNotSame(string0, string3); assertNotSame(string1, string3); assertNotSame(string2, string3); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/EmptyMapMutator.java100664 3355 12243235516 31527 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.Map; import java.util.Collection; /** * This class is used in TestCompositeMap. When testing serialization, * the class has to be separate of TestCompositeMap, else the test * class also has to be serialized. */ class EmptyMapMutator implements CompositeMap.MapMutator { /** Serialization version */ private static final long serialVersionUID = -2729718980002476794L; public void resolveCollision(final CompositeMap composite, final Map existing, final Map added, final Collection intersect) { // Do nothing } public V put(final CompositeMap map, final Map[] composited, final K key, final V value) { return composited[0].put(key, value); } public void putAll(final CompositeMap map, final Map[] composited, final Map t) { composited[0].putAll(t); } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/AbstractIterableMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/AbstractIterableMapTe100664 14225 12243235516 31657 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.iterators.AbstractMapIteratorTest; /** * Abstract test class for {@link IterableMap} methods and contracts. * * @version $Id: AbstractIterableMapTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractIterableMapTest extends AbstractMapTest { /** * JUnit constructor. * * @param testName the test name */ public AbstractIterableMapTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @Override public abstract IterableMap makeObject(); /** * {@inheritDoc} */ @Override public IterableMap makeFullMap() { return (IterableMap) super.makeFullMap(); } //----------------------------------------------------------------------- public void testFailFastEntrySet() { if (!isRemoveSupported()) { return; } if (!isFailFastExpected()) { return; } resetFull(); Iterator> it = getMap().entrySet().iterator(); final Map.Entry val = it.next(); getMap().remove(val.getKey()); try { it.next(); fail(); } catch (final ConcurrentModificationException ex) {} resetFull(); it = getMap().entrySet().iterator(); it.next(); getMap().clear(); try { it.next(); fail(); } catch (final ConcurrentModificationException ex) {} } public void testFailFastKeySet() { if (!isRemoveSupported()) { return; } if (!isFailFastExpected()) { return; } resetFull(); Iterator it = getMap().keySet().iterator(); final K val = it.next(); getMap().remove(val); try { it.next(); fail(); } catch (final ConcurrentModificationException ex) {} resetFull(); it = getMap().keySet().iterator(); it.next(); getMap().clear(); try { it.next(); fail(); } catch (final ConcurrentModificationException ex) {} } public void testFailFastValues() { if (!isRemoveSupported()) { return; } if (!isFailFastExpected()) { return; } resetFull(); Iterator it = getMap().values().iterator(); it.next(); getMap().remove(getMap().keySet().iterator().next()); try { it.next(); fail(); } catch (final ConcurrentModificationException ex) {} resetFull(); it = getMap().values().iterator(); it.next(); getMap().clear(); try { it.next(); fail(); } catch (final ConcurrentModificationException ex) {} } //----------------------------------------------------------------------- public BulkTest bulkTestMapIterator() { return new InnerTestMapIterator(); } public class InnerTestMapIterator extends AbstractMapIteratorTest { public InnerTestMapIterator() { super("InnerTestMapIterator"); } @Override public V[] addSetValues() { return AbstractIterableMapTest.this.getNewSampleValues(); } @Override public boolean supportsRemove() { return AbstractIterableMapTest.this.isRemoveSupported(); } @Override public boolean isGetStructuralModify() { return AbstractIterableMapTest.this.isGetStructuralModify(); } @Override public boolean supportsSetValue() { return AbstractIterableMapTest.this.isSetValueSupported(); } @Override public MapIterator makeEmptyIterator() { resetEmpty(); return AbstractIterableMapTest.this.getMap().mapIterator(); } @Override public MapIterator makeObject() { resetFull(); return AbstractIterableMapTest.this.getMap().mapIterator(); } @Override public Map getMap() { // assumes makeFullMapIterator() called first return AbstractIterableMapTest.this.getMap(); } @Override public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return AbstractIterableMapTest.this.getConfirmed(); } @Override public void verify() { super.verify(); AbstractIterableMapTest.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"); // } /** * {@inheritDoc} */ @Override public IterableMap getMap() { return (IterableMap) super.getMap(); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/StaticBucketMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/StaticBucketMapTest.j100664 6564 12243235516 31617 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * Unit tests. * {@link StaticBucketMap}. * * @version $Id: StaticBucketMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class StaticBucketMapTest extends AbstractIterableMapTest { public StaticBucketMapTest(final String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(StaticBucketMapTest.class); } @Override public StaticBucketMap makeObject() { return new StaticBucketMap(30); } /** * {@inheritDoc} */ @Override public boolean isFailFastExpected() { return false; } @Override public String[] ignoredTests() { final String pre = "StaticBucketMapTest.bulkTestMap"; final String post = ".testCollectionIteratorFailFast"; return new String[] { pre + "EntrySet" + post, pre + "KeySet" + post, pre + "Values" + post }; } // Bugzilla 37567 @SuppressWarnings("unchecked") public void test_get_nullMatchesIncorrectly() { final StaticBucketMap map = new StaticBucketMap(17); map.put(null, (V) "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++) { final String str = String.valueOf((char) i); assertEquals("String: " + str, null, map.get(str)); } } @SuppressWarnings("unchecked") public void test_containsKey_nullMatchesIncorrectly() { final StaticBucketMap map = new StaticBucketMap(17); map.put(null, (V) "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++) { final String str = String.valueOf((char) i); assertEquals("String: " + str, false, map.containsKey(str)); } } @SuppressWarnings("unchecked") public void test_containsValue_nullMatchesIncorrectly() { final StaticBucketMap map = new StaticBucketMap(17); map.put((K) "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++) { final String str = String.valueOf((char) i); assertEquals("String: " + str, false, map.containsValue(str)); } } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/HashedMapTest.java100664 5326 12243235516 31111 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * JUnit tests. * * @version $Id: HashedMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class HashedMapTest extends AbstractIterableMapTest { public HashedMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(HashedMapTest.class); } @Override public HashedMap makeObject() { return new HashedMap(); } @Override public String getCompatibilityVersion() { return "4"; } @SuppressWarnings("unchecked") public void testClone() { final HashedMap map = new HashedMap(10); map.put((K) "1", (V) "1"); final HashedMap cloned = map.clone(); assertEquals(map.size(), cloned.size()); assertSame(map.get("1"), cloned.get("1")); } public void testInternalState() { final 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, "src/test/resources/data/test/HashedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/HashedMap.fullCollection.version4.obj"); // } /** * Test for COLLECTIONS-323. */ public void testInitialCapacityZero() { final HashedMap map = new HashedMap(0); assertEquals(1, map.data.length); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/IdentityMap.java100664 15454 12243235516 30671 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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. In particular, you can't * use decorators like {@link ListOrderedMap} on it, which silently assume that these * contracts are fulfilled. *

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

* From 4.0, this class is replaced by java.util.IdentityHashMap but kept as a * test-class because it is still used by the ReferenceIdentityMapTest. * * @since 3.0 * @version $Id: IdentityMap.java 1540860 2013-11-11 21:58:27Z ebourg $ */ 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 negative */ public IdentityMap(final 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 negative * @throws IllegalArgumentException if the load factor is less than zero */ public IdentityMap(final int initialCapacity, final 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(final 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 */ @Override protected int hash(final 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 */ @Override protected boolean isEqualKey(final Object key1, final 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 */ @Override protected boolean isEqualValue(final Object value1, final 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 */ @Override protected IdentityEntry createEntry(final HashEntry next, final int hashCode, final K key, final V value) { return new IdentityEntry(next, hashCode, key, value); } //----------------------------------------------------------------------- /** * HashEntry */ protected static class IdentityEntry extends HashEntry { protected IdentityEntry(final HashEntry next, final int hashCode, final K key, final V value) { super(next, hashCode, key, value); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof Entry)) { return false; } final Map.Entry other = (Map.Entry) obj; return getKey() == other.getKey() && getValue() == other.getValue(); } @Override public int hashCode() { return System.identityHashCode(getKey()) ^ System.identityHashCode(getValue()); } } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ @Override public IdentityMap clone() { return (IdentityMap) super.clone(); } /** * Write the map out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/SingletonMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/SingletonMapTest.java100664 13726 12243235516 31702 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.HashMap; import junit.framework.Test; import org.apache.commons.collections4.BoundedMap; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.OrderedMap; /** * JUnit tests. * * @version $Id: SingletonMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class SingletonMapTest extends AbstractOrderedMapTest { private static final Integer ONE = Integer.valueOf(1); private static final Integer TWO = Integer.valueOf(2); private static final String TEN = "10"; public SingletonMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(SingletonMapTest.class); } //----------------------------------------------------------------------- @Override public OrderedMap makeObject() { // need an empty singleton map, but thats not possible // use a ridiculous fake instead to make the tests pass return UnmodifiableOrderedMap.unmodifiableOrderedMap(ListOrderedMap.listOrderedMap(new HashMap())); } @Override public String[] ignoredTests() { // the ridiculous map above still doesn't pass these tests // but its not relevant, so we ignore them return new String[] { "SingletonMapTest.bulkTestMapIterator.testEmptyMapIterator", "SingletonMapTest.bulkTestOrderedMapIterator.testEmptyMapIterator", }; } @Override @SuppressWarnings("unchecked") public SingletonMap makeFullMap() { return new SingletonMap((K) ONE, (V) TWO); } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override @SuppressWarnings("unchecked") public K[] getSampleKeys() { return (K[]) new Object[] { ONE }; } @Override @SuppressWarnings("unchecked") public V[] getSampleValues() { return (V[]) new Object[] { TWO }; } @Override @SuppressWarnings("unchecked") public V[] getNewSampleValues() { return (V[]) new Object[] { TEN }; } //----------------------------------------------------------------------- public void testClone() { final SingletonMap map = makeFullMap(); assertEquals(1, map.size()); final SingletonMap cloned = map.clone(); assertEquals(1, cloned.size()); assertEquals(true, cloned.containsKey(ONE)); assertEquals(true, cloned.containsValue(TWO)); } public void testKeyValue() { final SingletonMap map = makeFullMap(); assertEquals(1, map.size()); assertEquals(ONE, map.getKey()); assertEquals(TWO, map.getValue()); assertTrue(map instanceof KeyValue); } public void testBoundedMap() { final SingletonMap map = makeFullMap(); 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(); // } // } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/SingletonMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/SingletonMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/PassiveExpiringMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/PassiveExpiringMapTes100664 21120 12243235516 31737 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.map.PassiveExpiringMap.ExpirationPolicy; /** * JUnit tests. * * @since 4.0 * @version $Id: PassiveExpiringMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class PassiveExpiringMapTest extends AbstractMapTest { private static class TestExpirationPolicy implements ExpirationPolicy { private static final long serialVersionUID = 1L; public long expirationTime(final Integer key, final String value) { // odd keys expire immediately, even keys never expire if (key == null) { return 0; } if (key.intValue() % 2 == 0) { return -1; } return 0; } } public static Test suite() { return BulkTest.makeSuite(PassiveExpiringMapTest.class); } public PassiveExpiringMapTest(final String testName) { super(testName); } // public void testCreate() throws Exception { // writeExternalFormToDisk((java.io.Serializable) makeObject(), // "src/test/resources/data/test/PassiveExpiringMap.emptyCollection.version4.obj"); // // writeExternalFormToDisk((java.io.Serializable) makeFullMap(), // "src/test/resources/data/test/PassiveExpiringMap.fullCollection.version4.obj"); // } @Override public String getCompatibilityVersion() { return "4"; } private Map makeDecoratedTestMap() { final Map m = new HashMap(); m.put(Integer.valueOf(1), "one"); m.put(Integer.valueOf(2), "two"); m.put(Integer.valueOf(3), "three"); m.put(Integer.valueOf(4), "four"); m.put(Integer.valueOf(5), "five"); m.put(Integer.valueOf(6), "six"); return new PassiveExpiringMap(new TestExpirationPolicy(), m); } @Override public Map makeObject() { return new PassiveExpiringMap(); } private Map makeTestMap() { final Map m = new PassiveExpiringMap(new TestExpirationPolicy()); m.put(Integer.valueOf(1), "one"); m.put(Integer.valueOf(2), "two"); m.put(Integer.valueOf(3), "three"); m.put(Integer.valueOf(4), "four"); m.put(Integer.valueOf(5), "five"); m.put(Integer.valueOf(6), "six"); return m; } public void testConstructors() { try { final Map map = null; new PassiveExpiringMap(map); fail("constructor - exception should have been thrown."); } catch (final IllegalArgumentException ex) { // success } try { final ExpirationPolicy policy = null; new PassiveExpiringMap(policy); fail("constructor - exception should have been thrown."); } catch (final IllegalArgumentException ex) { // success } try { final TimeUnit unit = null; new PassiveExpiringMap(10L, unit); fail("constructor - exception should have been thrown."); } catch (final IllegalArgumentException ex) { // success } } public void testContainsKey() { final Map m = makeTestMap(); assertFalse(m.containsKey(Integer.valueOf(1))); assertFalse(m.containsKey(Integer.valueOf(3))); assertFalse(m.containsKey(Integer.valueOf(5))); assertTrue(m.containsKey(Integer.valueOf(2))); assertTrue(m.containsKey(Integer.valueOf(4))); assertTrue(m.containsKey(Integer.valueOf(6))); } public void testContainsValue() { final Map m = makeTestMap(); assertFalse(m.containsValue("one")); assertFalse(m.containsValue("three")); assertFalse(m.containsValue("five")); assertTrue(m.containsValue("two")); assertTrue(m.containsValue("four")); assertTrue(m.containsValue("six")); } public void testDecoratedMap() { // entries shouldn't expire final Map m = makeDecoratedTestMap(); assertEquals(6, m.size()); assertEquals("one", m.get(Integer.valueOf(1))); // removing a single item shouldn't affect any other items assertEquals("two", m.get(Integer.valueOf(2))); m.remove(Integer.valueOf(2)); assertEquals(5, m.size()); assertEquals("one", m.get(Integer.valueOf(1))); assertNull(m.get(Integer.valueOf(2))); // adding a single, even item shouldn't affect any other items assertNull(m.get(Integer.valueOf(2))); m.put(Integer.valueOf(2), "two"); assertEquals(6, m.size()); assertEquals("one", m.get(Integer.valueOf(1))); assertEquals("two", m.get(Integer.valueOf(2))); // adding a single, odd item (one that expires) shouldn't affect any // other items // put the entry expires immediately m.put(Integer.valueOf(1), "one-one"); assertEquals(5, m.size()); assertNull(m.get(Integer.valueOf(1))); assertEquals("two", m.get(Integer.valueOf(2))); } public void testEntrySet() { final Map m = makeTestMap(); assertEquals(3, m.entrySet().size()); } public void testGet() { final Map m = makeTestMap(); assertNull(m.get(Integer.valueOf(1))); assertEquals("two", m.get(Integer.valueOf(2))); assertNull(m.get(Integer.valueOf(3))); assertEquals("four", m.get(Integer.valueOf(4))); assertNull(m.get(Integer.valueOf(5))); assertEquals("six", m.get(Integer.valueOf(6))); } public void testIsEmpty() { Map m = makeTestMap(); assertFalse(m.isEmpty()); // remove just evens m = makeTestMap(); m.remove(Integer.valueOf(2)); m.remove(Integer.valueOf(4)); m.remove(Integer.valueOf(6)); assertTrue(m.isEmpty()); } public void testKeySet() { final Map m = makeTestMap(); assertEquals(3, m.keySet().size()); } public void testSize() { final Map m = makeTestMap(); assertEquals(3, m.size()); } public void testValues() { final Map m = makeTestMap(); assertEquals(3, m.values().size()); } public void testZeroTimeToLive() { // item should not be available final PassiveExpiringMap m = new PassiveExpiringMap(0L); m.put("a", "b"); assertNull(m.get("a")); } public void testExpiration() { validateExpiration(new PassiveExpiringMap(500), 500); validateExpiration(new PassiveExpiringMap(1000), 1000); validateExpiration(new PassiveExpiringMap( new PassiveExpiringMap.ConstantTimeToLiveExpirationPolicy(500)), 500); validateExpiration(new PassiveExpiringMap( new PassiveExpiringMap.ConstantTimeToLiveExpirationPolicy(1, TimeUnit.SECONDS)), 1000); } private void validateExpiration(final Map map, long timeout) { map.put("a", "b"); assertNotNull(map.get("a")); try { Thread.sleep(2 * timeout); } catch (InterruptedException e) { fail(); } assertNull(map.get("a")); } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/FixedSizeMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/FixedSizeMapTest.java100664 4434 12243235516 31606 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections4.IterableMap; /** * Extension of {@link AbstractMapTest} for exercising the {@link FixedSizeMap} * implementation. * * @since 3.0 * @version $Id: FixedSizeMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class FixedSizeMapTest extends AbstractIterableMapTest { public FixedSizeMapTest(final String testName) { super(testName); } @Override public IterableMap makeObject() { return FixedSizeMap.fixedSizeMap(new HashMap()); } @Override public IterableMap makeFullMap() { final Map map = new HashMap(); addSampleMappings(map); return FixedSizeMap.fixedSizeMap(map); } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/FixedSizeMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/FixedSizeMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/LazySortedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/LazySortedMapTest.jav100664 11533 12243235516 31671 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import static org.apache.commons.collections4.map.LazySortedMap.lazySortedMap; import java.util.Comparator; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.FactoryUtils; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.TransformerUtils; import org.junit.Test; /** * Extension of {@link LazyMapTest} for exercising the * {@link LazySortedMap} implementation. * * @since 3.0 * @version $Id: LazySortedMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("boxing") public class LazySortedMapTest extends AbstractSortedMapTest { private static final Factory oneFactory = FactoryUtils.constantFactory(1); public LazySortedMapTest(final String testName) { super(testName); } @Override public SortedMap makeObject() { return lazySortedMap(new TreeMap(), FactoryUtils.nullFactory()); } @Override public boolean isAllowNullKey() { return false; } // from LazyMapTest //----------------------------------------------------------------------- @Override public void testMapGet() { //TODO eliminate need for this via superclass - see svn history. } @Test public void mapGet() { Map map = lazySortedMap(new TreeMap(), oneFactory); assertEquals(0, map.size()); final Number i1 = map.get(5); assertEquals(1, i1); assertEquals(1, map.size()); map = lazySortedMap(new TreeMap(), FactoryUtils.nullFactory()); final Number o = map.get(5); assertEquals(null,o); assertEquals(1, map.size()); } //----------------------------------------------------------------------- public void testSortOrder() { final SortedMap map = lazySortedMap(new TreeMap(), oneFactory); map.put("A", 5); map.get("B"); // Entry with value "One" created map.put("C", 8); assertEquals("First key should be A", "A", map.firstKey()); assertEquals("Last key should be C", "C", map.lastKey()); assertEquals("First key in tail map should be B", "B", map.tailMap("B").firstKey()); assertEquals("Last key in head map should be B", "B", map.headMap("C").lastKey()); assertEquals("Last key in submap should be B", "B", map.subMap("A","C").lastKey()); final Comparator c = map.comparator(); assertTrue("natural order, so comparator should be null", c == null); } public void testTransformerDecorate() { final Transformer transformer = TransformerUtils.asTransformer(oneFactory); SortedMap map = lazySortedMap(new TreeMap(), transformer); assertTrue(map instanceof LazySortedMap); try { map = lazySortedMap(new TreeMap(), (Transformer) null); fail("Expecting IllegalArgumentException for null transformer"); } catch (final IllegalArgumentException e) { // expected } try { map = lazySortedMap((SortedMap) null, transformer); fail("Expecting IllegalArgumentException for null map"); } catch (final IllegalArgumentException e) { // expected } } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/LazySortedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/LazySortedMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/AbstractSortedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/AbstractSortedMapTest100664 33415 12243235516 31741 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.collections4.BulkTest; /** * Abstract test class for {@link java.util.SortedMap} methods and contracts. * * @version $Id: AbstractSortedMapTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractSortedMapTest extends AbstractMapTest { /** * JUnit constructor. * * @param testName the test name */ public AbstractSortedMapTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * Can't sort null keys. * * @return false */ @Override public boolean isAllowNullKey() { return false; } /** * SortedMap uses TreeMap as its known comparison. * * @return a map that is known to be valid */ @Override public SortedMap makeConfirmedMap() { return new TreeMap(); } //----------------------------------------------------------------------- public void testComparator() { // SortedMap sm = makeFullMap(); // no tests I can think of } /** * {@inheritDoc} */ @Override public abstract SortedMap makeObject(); /** * {@inheritDoc} */ @Override public SortedMap makeFullMap() { return (SortedMap) super.makeFullMap(); } public void testFirstKey() { final SortedMap sm = makeFullMap(); assertSame(sm.keySet().iterator().next(), sm.firstKey()); } public void testLastKey() { final SortedMap sm = makeFullMap(); K obj = null; for (K k : sm.keySet()) { obj = k; } 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 AbstractSortedMapTest { protected final AbstractMapTest main; protected final List subSortedKeys = new ArrayList(); protected final List subSortedValues = new ArrayList(); protected final List subSortedNewValues = new ArrayList(); public TestViewMap(final String name, final AbstractMapTest main) { super(name); this.main = main; } @Override public void resetEmpty() { // needed to init verify correctly main.resetEmpty(); super.resetEmpty(); } @Override public void resetFull() { // needed to init verify correctly main.resetFull(); super.resetFull(); } @Override public void verify() { // cross verify changes on view with changes on main map super.verify(); main.verify(); } @Override public BulkTest bulkTestHeadMap() { return null; // block infinite recursion } @Override public BulkTest bulkTestTailMap() { return null; // block infinite recursion } @Override public BulkTest bulkTestSubMap() { return null; // block infinite recursion } @Override @SuppressWarnings("unchecked") public K[] getSampleKeys() { return (K[]) subSortedKeys.toArray(); } @Override @SuppressWarnings("unchecked") public V[] getSampleValues() { return (V[]) subSortedValues.toArray(); } @Override @SuppressWarnings("unchecked") public V[] getNewSampleValues() { return (V[]) subSortedNewValues.toArray(); } @Override public boolean isAllowNullKey() { return main.isAllowNullKey(); } @Override public boolean isAllowNullValue() { return main.isAllowNullValue(); } @Override public boolean isPutAddSupported() { return main.isPutAddSupported(); } @Override public boolean isPutChangeSupported() { return main.isPutChangeSupported(); } @Override public boolean isRemoveSupported() { return main.isRemoveSupported(); } @Override 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 K toKey; public TestHeadMap(final AbstractMapTest main) { super("SortedMap.HeadMap", main); final Map sm = main.makeFullMap(); for (final Entry entry : sm.entrySet()) { 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)); } @Override public SortedMap makeObject() { // done this way so toKey is correctly set in the returned map return ((SortedMap) main.makeObject()).headMap(toKey); } @Override public SortedMap makeFullMap() { return ((SortedMap) main.makeFullMap()).headMap(toKey); } public void testHeadMapOutOfRange() { if (!isPutAddSupported()) { return; } resetEmpty(); try { getMap().put(toKey, subSortedValues.get(0)); fail(); } catch (final IllegalArgumentException ex) {} verify(); } @Override 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 K fromKey; final K invalidKey; public TestTailMap(final AbstractMapTest main) { super("SortedMap.TailMap", main); final Map sm = main.makeFullMap(); for (final Entry entry : sm.entrySet()) { 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)); } @Override public SortedMap makeObject() { // done this way so toKey is correctly set in the returned map return ((SortedMap) main.makeObject()).tailMap(fromKey); } @Override public SortedMap makeFullMap() { return ((SortedMap) main.makeFullMap()).tailMap(fromKey); } public void testTailMapOutOfRange() { if (!isPutAddSupported()) { return; } resetEmpty(); try { getMap().put(invalidKey, subSortedValues.get(0)); fail(); } catch (final IllegalArgumentException ex) {} verify(); } @Override 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 K fromKey; final K toKey; public TestSubMap(final AbstractMapTest main) { super("SortedMap.SubMap", main); final Map sm = main.makeFullMap(); for (final Entry entry : sm.entrySet()) { 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)); } @Override public SortedMap makeObject() { // done this way so toKey is correctly set in the returned map return ((SortedMap) main.makeObject()).subMap(fromKey, toKey); } @Override public SortedMap makeFullMap() { return ((SortedMap) main.makeFullMap()).subMap(fromKey, toKey); } public void testSubMapOutOfRange() { if (!isPutAddSupported()) { return; } resetEmpty(); try { getMap().put(toKey, subSortedValues.get(0)); fail(); } catch (final IllegalArgumentException ex) {} verify(); } @Override 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"); // } } /** * {@inheritDoc} */ @Override public SortedMap getMap() { return (SortedMap) super.getMap(); } /** * {@inheritDoc} */ @Override public SortedMap getConfirmed() { return (SortedMap) super.getConfirmed(); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/LazyMapTest.java100664 7056 12243235516 30636 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import static org.apache.commons.collections4.map.LazyMap.lazyMap; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.FactoryUtils; import org.apache.commons.collections4.Transformer; import org.junit.Test; /** * Extension of {@link AbstractMapTest} for exercising the * {@link LazyMap} implementation. * * @since 3.0 * @version $Id: LazyMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("boxing") public class LazyMapTest extends AbstractIterableMapTest { private static final Factory oneFactory = FactoryUtils.constantFactory(1); public LazyMapTest(final String testName) { super(testName); } @Override public LazyMap makeObject() { return lazyMap(new HashMap(), FactoryUtils.nullFactory()); } //----------------------------------------------------------------------- @Override public void testMapGet() { //TODO eliminate need for this via superclass - see svn history. } @Test public void mapGetWithFactory() { Map map = lazyMap(new HashMap(), oneFactory); assertEquals(0, map.size()); final Number i1 = map.get("Five"); assertEquals(1, i1); assertEquals(1, map.size()); final Number i2 = map.get(new String(new char[] {'F','i','v','e'})); assertEquals(1, i2); assertEquals(1, map.size()); assertSame(i1, i2); map = lazyMap(new HashMap(), FactoryUtils.nullFactory()); final Object o = map.get("Five"); assertEquals(null,o); assertEquals(1, map.size()); } @Test public void mapGetWithTransformer() { final Transformer intConverter = new Transformer(){ public Integer transform(final Number input) { return input.intValue(); } }; final Map map = lazyMap(new HashMap(), intConverter ); assertEquals(0, map.size()); final Number i1 = map.get(123L); assertEquals(123, i1); assertEquals(1, map.size()); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/LazyMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/LazyMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/TransformedSortedMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/map/TransformedSortedMapT100664 20416 12243235516 31743 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.BulkTest; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.TransformerUtils; import org.apache.commons.collections4.collection.TransformedCollectionTest; /** * Extension of {@link AbstractSortedMapTest} for exercising the {@link TransformedSortedMap} * implementation. * * @since 3.0 * @version $Id: TransformedSortedMapTest.java 1542074 2013-11-14 20:57:02Z tn $ */ public class TransformedSortedMapTest extends AbstractSortedMapTest { public TransformedSortedMapTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TransformedSortedMapTest.class); } @Override public String[] ignoredTests() { if (IBMJDK16) { final String preSubMap = "TransformedSortedMapTest.bulkTestSubMap."; final String preTailMap = "TransformedSortedMapTest.bulkTestTailMap."; return new String[] { preSubMap + "bulkTestMapEntrySet.testCollectionIteratorRemove", preSubMap + "bulkTestMapKeySet.testCollectionRemove", preSubMap + "bulkTestMapValues.testCollectionIteratorRemove", preTailMap + "testMapRemove", preTailMap + "bulkTestMapEntrySet.testCollectionIteratorRemove", preTailMap + "bulkTestMapEntrySet.testCollectionRemoveAll", preTailMap + "bulkTestMapKeySet.testCollectionIteratorRemove", preTailMap + "bulkTestMapKeySet.testCollectionRemoveAll", preTailMap + "bulkTestMapValues.testCollectionClear", preTailMap + "bulkTestMapValues.testCollectionRemoveAll", preTailMap + "bulkTestMapValues.testCollectionRetainAll" }; } else { return null; } } //----------------------------------------------------------------------- @Override @SuppressWarnings("unchecked") public SortedMap makeObject() { return TransformedSortedMap.transformingSortedMap(new TreeMap(), (Transformer) TransformerUtils.nopTransformer(), (Transformer) TransformerUtils.nopTransformer()); } @Override public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testTransformedMap() { final Object[] els = new Object[] { "1", "3", "5", "7", "2", "4", "6" }; SortedMap map = TransformedSortedMap .transformingSortedMap( new TreeMap(), (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER, null); assertEquals(0, map.size()); for (int i = 0; i < els.length; i++) { map.put((K) els[i], (V) els[i]); assertEquals(i + 1, map.size()); assertEquals(true, map.containsKey(Integer.valueOf((String) els[i]))); try { map.containsKey(els[i]); fail(); } catch (final ClassCastException ex) {} assertEquals(true, map.containsValue(els[i])); assertEquals(els[i], map.get(Integer.valueOf((String) els[i]))); } try { map.remove(els[0]); fail(); } catch (final ClassCastException ex) {} assertEquals(els[0], map.remove(Integer.valueOf((String) els[0]))); map = TransformedSortedMap .transformingSortedMap( new TreeMap(), null, (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, map.size()); for (int i = 0; i < els.length; i++) { map.put((K) els[i], (V) els[i]); assertEquals(i + 1, map.size()); assertEquals(true, map.containsValue(Integer.valueOf((String) els[i]))); assertEquals(false, map.containsValue(els[i])); assertEquals(true, map.containsKey(els[i])); assertEquals(Integer.valueOf((String) els[i]), map.get(els[i])); } assertEquals(Integer.valueOf((String) els[0]), map.remove(els[0])); final Set> entrySet = map.entrySet(); final Map.Entry[] array = entrySet.toArray(new Map.Entry[0]); array[0].setValue((V) "66"); assertEquals(Integer.valueOf(66), array[0].getValue()); assertEquals(Integer.valueOf(66), map.get(array[0].getKey())); final Map.Entry entry = entrySet.iterator().next(); entry.setValue((V) "88"); assertEquals(Integer.valueOf(88), entry.getValue()); assertEquals(Integer.valueOf(88), map.get(entry.getKey())); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testFactory_Decorate() { final SortedMap base = new TreeMap(); base.put((K) "A", (V) "1"); base.put((K) "B", (V) "2"); base.put((K) "C", (V) "3"); final SortedMap trans = TransformedSortedMap .transformingSortedMap( base, null, (Transformer) TransformedCollectionTest.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((K) "D", (V) "4"); assertEquals(Integer.valueOf(4), trans.get("D")); } @SuppressWarnings("unchecked") public void testFactory_decorateTransform() { final SortedMap base = new TreeMap(); base.put((K) "A", (V) "1"); base.put((K) "B", (V) "2"); base.put((K) "C", (V) "3"); final SortedMap trans = TransformedSortedMap .transformedSortedMap( base, null, (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(3, trans.size()); assertEquals(Integer.valueOf(1), trans.get("A")); assertEquals(Integer.valueOf(2), trans.get("B")); assertEquals(Integer.valueOf(3), trans.get("C")); trans.put((K) "D", (V) "4"); assertEquals(Integer.valueOf(4), trans.get("D")); } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/TransformedSortedMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/TransformedSortedMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/EnumerationUtilsTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/EnumerationUtilsTest.java100664 7155 12243235516 32013 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.StringTokenizer; import junit.framework.Test; /** * Tests EnumerationUtils. * * @version $Id: EnumerationUtilsTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class EnumerationUtilsTest extends BulkTest { public EnumerationUtilsTest(final String name) { super(name); } public static final String TO_LIST_FIXTURE = "this is a test"; public void testToListWithStringTokenizer() { final List expectedList1 = new ArrayList(); final StringTokenizer st = new StringTokenizer(TO_LIST_FIXTURE); while (st.hasMoreTokens()) { expectedList1.add(st.nextToken()); } final List expectedList2 = new ArrayList(); expectedList2.add("this"); expectedList2.add("is"); expectedList2.add("a"); expectedList2.add("test"); final List actualList = EnumerationUtils.toList(new StringTokenizer(TO_LIST_FIXTURE)); assertEquals(expectedList1, expectedList2); assertEquals(expectedList1, actualList); assertEquals(expectedList2, actualList); } public void testToListWithHashtable() { final Hashtable expected = new Hashtable(); expected.put("one", Integer.valueOf(1)); expected.put("two", Integer.valueOf(2)); expected.put("three", Integer.valueOf(3)); // validate elements. final List actualEltList = EnumerationUtils.toList(expected.elements()); assertEquals(expected.size(), actualEltList.size()); assertTrue(actualEltList.contains(Integer.valueOf(1))); assertTrue(actualEltList.contains(Integer.valueOf(2))); assertTrue(actualEltList.contains(Integer.valueOf(3))); final List expectedEltList = new ArrayList(); expectedEltList.add(Integer.valueOf(1)); expectedEltList.add(Integer.valueOf(2)); expectedEltList.add(Integer.valueOf(3)); assertTrue(actualEltList.containsAll(expectedEltList)); // validate keys. final List actualKeyList = EnumerationUtils.toList(expected.keys()); assertEquals(expected.size(), actualEltList.size()); assertTrue(actualKeyList.contains("one")); assertTrue(actualKeyList.contains("two")); assertTrue(actualKeyList.contains("three")); final List expectedKeyList = new ArrayList(); expectedKeyList.add("one"); expectedKeyList.add("two"); expectedKeyList.add("three"); assertTrue(actualKeyList.containsAll(expectedKeyList)); } public static Test suite() { return BulkTest.makeSuite(EnumerationUtilsTest.class); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/overview.html100664 3442 12243235516 27530 0ustartntn 0 0

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. commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/MapUtilsTest.java100664 75731 12243235516 30267 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Collection; 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 java.util.List; import java.util.ArrayList; import junit.framework.Test; import org.apache.commons.collections4.collection.TransformedCollectionTest; import org.apache.commons.collections4.keyvalue.DefaultKeyValue; import org.apache.commons.collections4.keyvalue.DefaultMapEntry; import org.apache.commons.collections4.map.HashedMap; import org.apache.commons.collections4.map.LazyMap; import org.apache.commons.collections4.map.MultiValueMap; import org.apache.commons.collections4.map.PredicatedMap; /** * Tests for MapUtils. * * @version $Id: MapUtilsTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("boxing") public class MapUtilsTest extends BulkTest { public MapUtilsTest(final String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(MapUtilsTest.class); } public Predicate getPredicate() { return new Predicate() { public boolean evaluate(final Object o) { return o instanceof String; } }; } public void testPredicatedMap() { final Predicate p = getPredicate(); Map map = MapUtils.predicatedMap(new HashMap(), p, p); assertTrue("returned object should be a PredicatedMap", map instanceof PredicatedMap); try { MapUtils.predicatedMap(null, p, p); fail("Expecting IllegalArgumentException for null map."); } catch (final IllegalArgumentException e) { // expected } } public void testLazyMapFactory() { final Factory factory = FactoryUtils.constantFactory(Integer.valueOf(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 (final IllegalArgumentException e) { // expected } try { map = MapUtils.lazyMap((Map) null, factory); fail("Expecting IllegalArgumentException for null map"); } catch (final IllegalArgumentException e) { // expected } final 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 (final IllegalArgumentException e) { // expected } try { map = MapUtils.lazyMap((Map) null, transformer); fail("Expecting IllegalArgumentException for null map"); } catch (final IllegalArgumentException e) { // expected } } public void testLazyMapTransformer() { final Map map = MapUtils.lazyMap(new HashMap(), new Transformer() { public Object transform(final Object mapKey) { if (mapKey instanceof String) { return Integer.valueOf((String) mapKey); } return null; } }); assertEquals(0, map.size()); final Integer i1 = (Integer) map.get("5"); assertEquals(Integer.valueOf(5), i1); assertEquals(1, map.size()); final Integer i2 = (Integer) map.get(new String(new char[] {'5'})); assertEquals(Integer.valueOf(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( "1", out.get("A")); assertEquals( "2", out.get("B")); assertEquals( "3", out.get("C")); assertEquals( "4", out.get("D")); assertEquals( "5", out.get("E")); } public void testPutAll_Map_array() { try { MapUtils.putAll(null, null); fail(); } catch (final NullPointerException ex) {} try { MapUtils.putAll(null, new Object[0]); fail(); } catch (final 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 (final IllegalArgumentException ex) {} try { MapUtils.putAll(new HashMap(), new String[][] { {"RED", "#FF0000"}, {"GREEN"}, {"BLUE", "#0000FF"} }); fail(); } catch (final IllegalArgumentException ex) {} try { MapUtils.putAll(new HashMap(), new String[][] { {"RED", "#FF0000"}, {}, {"BLUE", "#0000FF"} }); fail(); } catch (final 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"); final ResourceBundle b = new ListResourceBundle() { @Override 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(2, "B"); inner.put(3, "C"); final Map outer = new HashMap(2, 1); outer.put(0, inner); outer.put(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(2, "B"); map.put(3, "C"); map.put(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(2, "B"); map.put(3, "C"); map.put(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 (final NullPointerException expected) { } } public void testDebugPrintNullStream() { try { MapUtils.debugPrint(null, "Map", new HashMap()); fail("Should generate NullPointerException"); } catch (final 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(2, "B"); inner.put(3, "C"); final Map outer = new TreeMap(); outer.put(1, inner); outer.put(0, "A"); outer.put(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(2, "B"); inner.put(3, "C"); final Map outer = new TreeMap(); outer.put(1, inner); outer.put(0, "A"); outer.put(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(0, "A"); grandfather.put(1, father); father.put(2, "B"); father.put(3, grandfather); father.put(4, son); son.put(5, "C"); son.put(6, grandfather); son.put(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(0, "A"); grandfather.put(1, father); father.put(2, "B"); father.put(3, grandfather); father.put(4, son); son.put(5, "C"); son.put(6, grandfather); son.put(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 testEmptyIfNull() { assertTrue(MapUtils.emptyIfNull(null).isEmpty()); final Map map = new HashMap(); assertSame(map, MapUtils.emptyIfNull(map)); } public void testIsEmptyWithEmptyMap() { final Map map = new HashMap(); assertEquals(true, MapUtils.isEmpty(map)); } public void testIsEmptyWithNonEmptyMap() { final Map map = new HashMap(); map.put("item", "value"); assertEquals(false, MapUtils.isEmpty(map)); } public void testIsEmptyWithNull() { final Map map = null; assertEquals(true, MapUtils.isEmpty(map)); } public void testIsNotEmptyWithEmptyMap() { final Map map = new HashMap(); assertEquals(false, MapUtils.isNotEmpty(map)); } public void testIsNotEmptyWithNonEmptyMap() { final Map map = new HashMap(); map.put("item", "value"); assertEquals(true, MapUtils.isNotEmpty(map)); } public void testIsNotEmptyWithNull() { final Map map = null; assertEquals(false, MapUtils.isNotEmpty(map)); } public void testPopulateMap() { // Setup Test Data final List list = new ArrayList(); list.add("1"); list.add("3"); list.add("5"); list.add("7"); list.add("2"); list.add("4"); list.add("6"); // Now test key transform population Map map = new HashMap(); MapUtils.populateMap(map, list, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(list.size(), map.size()); for (int i = 0; i < list.size(); i++) { assertEquals(true, map.containsKey(Integer.valueOf(list.get(i)))); assertEquals(false, map.containsKey(list.get(i))); assertEquals(true, map.containsValue(list.get(i))); assertEquals(list.get(i), map.get(Integer.valueOf(list.get(i)))); } // Now test both Key-Value transform population map = new HashMap(); MapUtils.populateMap(map, list, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(list.size(), map.size()); for (int i = 0; i < list.size(); i++) { assertEquals(true, map.containsKey(Integer.valueOf(list.get(i)))); assertEquals(false, map.containsKey(list.get(i))); assertEquals(true, map.containsValue(Integer.valueOf(list.get(i)))); assertEquals(Integer.valueOf(list.get(i)), map.get(Integer.valueOf(list.get(i)))); } } /** * Test class for populateMap(MultiMap). */ public static class X implements Comparable { int key; String name; public X(int key, String name) { this.key = key; this.name = name; } public int compareTo(X o) { return key - o.key | name.compareTo(o.name); } } public void testPopulateMultiMap() { // Setup Test Data final List list = new ArrayList(); list.add(new X(1, "x1")); list.add(new X(2, "x2")); list.add(new X(2, "x3")); list.add(new X(5, "x4")); list.add(new X(5, "x5")); // Now test key transform population final MultiValueMap map = MultiValueMap.multiValueMap(new TreeMap>()); MapUtils.populateMap(map, list, new Transformer() { public Integer transform(X input) { return input.key; } }, TransformerUtils. nopTransformer()); assertEquals(list.size(), map.totalSize()); for (int i = 0; i < list.size(); i++) { assertEquals(true, map.containsKey(list.get(i).key)); assertEquals(true, map.containsValue(list.get(i))); } } public void testIterableMap() { try { MapUtils.iterableMap(null); fail("Should throw IllegalArgumentException"); } catch (final IllegalArgumentException e) { } final HashMap map = new HashMap(); map.put("foo", "foov"); map.put("bar", "barv"); map.put("baz", "bazv"); final IterableMap iMap = MapUtils.iterableMap(map); assertEquals(map, iMap); assertNotSame(map, iMap); final HashedMap hMap = new HashedMap(map); assertSame(hMap, MapUtils.iterableMap(hMap)); } public void testIterableSortedMap() { try { MapUtils.iterableSortedMap(null); fail("Should throw IllegalArgumentException"); } catch (final IllegalArgumentException e) { } final TreeMap map = new TreeMap(); map.put("foo", "foov"); map.put("bar", "barv"); map.put("baz", "bazv"); final IterableSortedMap iMap = MapUtils.iterableSortedMap(map); assertEquals(map, iMap); assertNotSame(map, iMap); assertSame(iMap, MapUtils.iterableMap(iMap)); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/IteratorUtilsTest.java100664 77405 12243235516 31343 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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.collections4.iterators.EmptyIterator; import org.apache.commons.collections4.iterators.EmptyListIterator; import org.apache.commons.collections4.iterators.EmptyMapIterator; import org.apache.commons.collections4.iterators.EmptyOrderedIterator; import org.apache.commons.collections4.iterators.EmptyOrderedMapIterator; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; /** * Tests for IteratorUtils. * * @version $Id: IteratorUtilsTest.java 1543964 2013-11-20 21:53:39Z tn $ */ public class IteratorUtilsTest extends BulkTest { public IteratorUtilsTest(final String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(IteratorUtilsTest.class); } public void testAsIterable() { final List list = new ArrayList(); list.add(Integer.valueOf(0)); list.add(Integer.valueOf(1)); list.add(Integer.valueOf(2)); final Iterator iterator = list.iterator(); final Iterable iterable = IteratorUtils.asIterable(iterator); int expected = 0; for(final Integer actual : iterable) { assertEquals(expected, actual.intValue()); ++expected; } // insure iteration occurred assertTrue(expected > 0); // single use iterator assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext()); } public void testAsIterableNull() { try { IteratorUtils.asIterable(null); fail("Expecting NullPointerException"); } catch (final NullPointerException ex) { // success } } public void testAsMultipleIterable() { final List list = new ArrayList(); list.add(Integer.valueOf(0)); list.add(Integer.valueOf(1)); list.add(Integer.valueOf(2)); final Iterator iterator = list.iterator(); final Iterable iterable = IteratorUtils.asMultipleUseIterable(iterator); int expected = 0; for(final Integer actual : iterable) { assertEquals(expected, actual.intValue()); ++expected; } // insure iteration occurred assertTrue(expected > 0); // multiple use iterator expected = 0; for(final Integer actual : iterable) { assertEquals(expected, actual.intValue()); ++expected; } // insure iteration occurred assertTrue(expected > 0); } public void testAsMultipleIterableNull() { try { IteratorUtils.asMultipleUseIterable(null); fail("Expecting NullPointerException"); } catch (final NullPointerException ex) { // success } } public void testToList() { final List list = new ArrayList(); list.add(Integer.valueOf(1)); list.add("Two"); list.add(null); final List result = IteratorUtils.toList(list.iterator()); assertEquals(list, result); } public void testToArray() { final List list = new ArrayList(); list.add(Integer.valueOf(1)); list.add("Two"); list.add(null); final Object[] result = IteratorUtils.toArray(list.iterator()); assertEquals(list, Arrays.asList(result)); } public void testToArray2() { final List list = new ArrayList(); list.add("One"); list.add("Two"); list.add(null); final String[] result = IteratorUtils.toArray(list.iterator(), String.class); assertEquals(list, Arrays.asList(result)); } public void testArrayIterator() { final 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(Integer.valueOf(0)); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { // expected } try { iterator = IteratorUtils.arrayIterator((Object[]) null); fail("Expecting NullPointerException"); } catch (final NullPointerException ex) { // expected } iterator = IteratorUtils.arrayIterator(objArray, 1); assertTrue(iterator.next().equals("b")); try { iterator = IteratorUtils.arrayIterator(objArray, -1); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayIterator(objArray, 3); assertTrue(!iterator.hasNext()); iterator.reset(); try { iterator = IteratorUtils.arrayIterator(objArray, 4); fail("Expecting IndexOutOfBoundsException"); } catch (final 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 (final IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayIterator(objArray, -1, 1); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayIterator(objArray, 2, 1); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { // expected } final int[] intArray = {0, 1, 2}; iterator = IteratorUtils.arrayIterator(intArray); assertTrue(iterator.next().equals(Integer.valueOf(0))); assertTrue(iterator.next().equals(Integer.valueOf(1))); iterator.reset(); assertTrue(iterator.next().equals(Integer.valueOf(0))); iterator = IteratorUtils.arrayIterator(intArray, 1); assertTrue(iterator.next().equals(Integer.valueOf(1))); try { iterator = IteratorUtils.arrayIterator(intArray, -1); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayIterator(intArray, 3); assertTrue(!iterator.hasNext()); iterator.reset(); try { iterator = IteratorUtils.arrayIterator(intArray, 4); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayIterator(intArray, 2, 3); assertTrue(iterator.next().equals(Integer.valueOf(2))); try { iterator = IteratorUtils.arrayIterator(intArray, 2, 4); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayIterator(intArray, -1, 1); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayIterator(intArray, 2, 1); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { // expected } } public void testArrayListIterator() { final 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(Integer.valueOf(0)); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator((Object[]) null); fail("Expecting NullPointerException"); } catch (final 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 (final IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayListIterator(objArray, 3); assertTrue(iterator.hasNext()); try { iterator.previous(); fail("Expecting NoSuchElementException."); } catch (final NoSuchElementException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(objArray, 5); fail("Expecting IndexOutOfBoundsException."); } catch (final 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 (final IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(objArray, -1, 1); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(objArray, 2, 1); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { // expected } final int[] intArray = {0, 1, 2}; iterator = IteratorUtils.arrayListIterator(intArray); assertTrue(iterator.previousIndex() == -1); assertTrue(!iterator.hasPrevious()); assertTrue(iterator.nextIndex() == 0); assertTrue(iterator.next().equals(Integer.valueOf(0))); assertTrue(iterator.previousIndex() == 0); assertTrue(iterator.nextIndex() == 1); assertTrue(iterator.next().equals(Integer.valueOf(1))); assertTrue(iterator.previousIndex() == 1); assertTrue(iterator.nextIndex() == 2); assertTrue(iterator.previous().equals(Integer.valueOf(1))); assertTrue(iterator.next().equals(Integer.valueOf(1))); iterator = IteratorUtils.arrayListIterator(intArray, 1); assertTrue(iterator.previousIndex() == -1); assertTrue(!iterator.hasPrevious()); assertTrue(iterator.nextIndex() == 0); assertTrue(iterator.next().equals(Integer.valueOf(1))); assertTrue(iterator.previous().equals(Integer.valueOf(1))); assertTrue(iterator.next().equals(Integer.valueOf(1))); assertTrue(iterator.previousIndex() == 0); assertTrue(iterator.nextIndex() == 1); assertTrue(iterator.next().equals(Integer.valueOf(2))); assertTrue(iterator.previousIndex() == 1); assertTrue(iterator.nextIndex() == 2); assertTrue(iterator.previous().equals(Integer.valueOf(2))); assertTrue(iterator.previousIndex() == 0); assertTrue(iterator.nextIndex() == 1); try { iterator = IteratorUtils.arrayListIterator(intArray, -1); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayListIterator(intArray, 3); assertTrue(!iterator.hasNext()); try { iterator = IteratorUtils.arrayListIterator(intArray, 4); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } iterator = IteratorUtils.arrayListIterator(intArray, 2, 3); assertTrue(!iterator.hasPrevious()); assertTrue(iterator.previousIndex() == -1); assertTrue(iterator.next().equals(Integer.valueOf(2))); assertTrue(iterator.hasPrevious()); assertTrue(!iterator.hasNext()); try { iterator = IteratorUtils.arrayListIterator(intArray, 2, 4); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(intArray, -1, 1); fail("Expecting IndexOutOfBoundsException"); } catch (final IndexOutOfBoundsException ex) { // expected } try { iterator = IteratorUtils.arrayListIterator(intArray, 2, 1); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { // expected } } /** * Gets an immutable Iterator operating on the elements ["a", "b", "c", "d"]. */ private Iterator getImmutableIterator() { final 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() { final 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 (final NoSuchElementException ex) {} try { IteratorUtils.EMPTY_ITERATOR.remove(); fail(); } catch (final 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 (final NoSuchElementException ex) {} try { IteratorUtils.EMPTY_LIST_ITERATOR.previous(); fail(); } catch (final NoSuchElementException ex) {} try { IteratorUtils.EMPTY_LIST_ITERATOR.remove(); fail(); } catch (final IllegalStateException ex) {} try { IteratorUtils.emptyListIterator().set(null); fail(); } catch (final IllegalStateException ex) {} try { IteratorUtils.emptyListIterator().add(null); fail(); } catch (final UnsupportedOperationException ex) {} } //----------------------------------------------------------------------- /** * Test empty map iterator */ @SuppressWarnings("unchecked") 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 (final NoSuchElementException ex) {} try { IteratorUtils.EMPTY_MAP_ITERATOR.remove(); fail(); } catch (final IllegalStateException ex) {} try { IteratorUtils.EMPTY_MAP_ITERATOR.getKey(); fail(); } catch (final IllegalStateException ex) {} try { IteratorUtils.EMPTY_MAP_ITERATOR.getValue(); fail(); } catch (final IllegalStateException ex) {} try { IteratorUtils.EMPTY_MAP_ITERATOR.setValue(null); fail(); } catch (final IllegalStateException ex) {} } //----------------------------------------------------------------------- /** * Test empty map iterator */ @SuppressWarnings("unchecked") 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 (final NoSuchElementException ex) {} try { IteratorUtils.EMPTY_ORDERED_ITERATOR.previous(); fail(); } catch (final NoSuchElementException ex) {} try { IteratorUtils.EMPTY_ORDERED_ITERATOR.remove(); fail(); } catch (final IllegalStateException ex) {} } //----------------------------------------------------------------------- /** * Test empty map iterator */ @SuppressWarnings("unchecked") 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 (final NoSuchElementException ex) {} try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.previous(); fail(); } catch (final NoSuchElementException ex) {} try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.remove(); fail(); } catch (final IllegalStateException ex) {} try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.getKey(); fail(); } catch (final IllegalStateException ex) {} try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.getValue(); fail(); } catch (final IllegalStateException ex) {} try { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.setValue(null); fail(); } catch (final IllegalStateException ex) {} } //----------------------------------------------------------------------- /** * Test next() and hasNext() for an immutable Iterator. */ public void testUnmodifiableIteratorIteration() { final 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() { final 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() { final Iterator iterator = getImmutableIterator(); try { iterator.remove(); // We shouldn't get to here. fail("remove() should throw an UnsupportedOperationException"); } catch (final 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 (final UnsupportedOperationException e) { // This is correct; ignore the exception. } } /** * Test remove() for an immutable ListIterator. */ public void testUnmodifiableListIteratorImmutability() { final ListIterator listIterator = getImmutableListIterator(); try { listIterator.remove(); // We shouldn't get to here. fail("remove() should throw an UnsupportedOperationException"); } catch (final 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 (final 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 (final 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 (final 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 (final 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 (final UnsupportedOperationException e) { // This is correct; ignore the exception. } } /** * Tests method nodeListIterator(NodeList) */ public void testNodeListIterator() { final Node[] nodes = createNodes(); final NodeList nodeList = createNodeList(nodes); final Iterator iterator = IteratorUtils.nodeListIterator(nodeList); int expectedNodeIndex = 0; for (final Node actual : IteratorUtils.asIterable(iterator)) { assertEquals(nodes[expectedNodeIndex], actual); ++expectedNodeIndex; } // insure iteration occurred assertTrue(expectedNodeIndex > 0); // single use iterator assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext()); } /** * Tests method nodeListIterator(Node) */ public void testNodeIterator() { final Node[] nodes = createNodes(); final NodeList nodeList = createNodeList(nodes); final Node parentNode = createMock(Node.class); expect(parentNode.getChildNodes()).andStubReturn(nodeList); replay(parentNode); final Iterator iterator = IteratorUtils.nodeListIterator(parentNode); int expectedNodeIndex = 0; for (final Node actual : IteratorUtils.asIterable(iterator)) { assertEquals(nodes[expectedNodeIndex], actual); ++expectedNodeIndex; } // insure iteration occurred assertTrue(expectedNodeIndex > 0); // single use iterator assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext()); } /** * creates an array of four Node instances, mocked by EasyMock. */ private Node[] createNodes() { final Node node1 = createMock(Node.class); final Node node2 = createMock(Node.class); final Node node3 = createMock(Node.class); final Node node4 = createMock(Node.class); replay(node1); replay(node2); replay(node3); replay(node4); return new Node[]{node1, node2, node3, node4}; } /** * Creates a NodeList containing the specified nodes. */ private NodeList createNodeList(final Node[] nodes) { return new NodeList() { public Node item(final int index) { return nodes[index]; } public int getLength() { return nodes.length; } }; } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/SetUtilsTest.java100664 7233 12243235516 30255 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import junit.framework.Test; import org.apache.commons.collections4.set.PredicatedSet; /** * Tests for SetUtils. * * @version $Id: SetUtilsTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class SetUtilsTest extends BulkTest { public SetUtilsTest(final String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(SetUtilsTest.class); } public void testNothing() { } public void testpredicatedSet() { final Predicate predicate = new Predicate() { public boolean evaluate(final Object o) { return o instanceof String; } }; Set set = SetUtils.predicatedSet(new HashSet(), predicate); assertTrue("returned object should be a PredicatedSet", set instanceof PredicatedSet); try { SetUtils.predicatedSet(new HashSet(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (final IllegalArgumentException ex) { // expected } try { SetUtils.predicatedSet(null, predicate); fail("Expecting IllegalArgumentException for null set."); } catch (final IllegalArgumentException ex) { // expected } } public void testEmptyIfNull() { assertTrue(SetUtils.emptyIfNull(null).isEmpty()); final Set set = new HashSet(); assertSame(set, SetUtils.emptyIfNull(set)); } public void testEquals() { final Collection data = Arrays.asList("a", "b", "c"); final Set a = new HashSet(data); final 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() { final Collection data = Arrays.asList("a", "b", "c"); final Set a = new HashSet(data); final 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)); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/BulkTest.java100664 40415 12243235516 27415 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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 hierarchical suite of tests and child bulk tests. *

* For instance, consider the following two classes: * *

 *  public class SetTest extends BulkTest {
 *
 *      private Set set;
 *
 *      public SetTest(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 HashMapTest 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, SetTest defines two * simple test methods and no bulk test methods; HashMapTest * defines one simple test method and two bulk test methods. When * makeSuite(HashMapTest.class).run is executed, * five simple test methods will be run, in this order:

* *

    *
  1. HashMapTest.testClear() *
  2. HashMapTest.bulkTestKeySet().testContains(); *
  3. HashMapTest.bulkTestKeySet().testClear(); *
  4. HashMapTest.bulkTestEntrySet().testContains(); *
  5. HashMapTest.bulkTestEntrySet().testClear(); *
* * In the graphical junit test runners, the tests would be displayed in * the following tree:

* *

    *
  • HashMapTest
  • *
      *
    • 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. * * @version $Id: BulkTest.java 1542074 2013-11-14 20:57:02Z tn $ */ public class BulkTest extends TestCase implements Cloneable { /** * IBM JDK 1.6.0 has several bugs in their java.util.TreeMap implementation. */ protected static final boolean IBMJDK16; static { final String vmName = System.getProperty("java.vm.name"); final String version = System.getProperty("java.version"); IBMJDK16 = vmName != null && vmName.equals("IBM J9 VM") && version != null && version.equals("1.6.0"); } // 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. /** Path to test data resources */ protected static final String TEST_DATA_PATH = "src/test/resources/data/test/"; /** * 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(final String name) { super(name); this.verboseName = getClass().getName(); } /** * Creates a clone of this BulkTest.

* * @return a clone of this BulkTest */ @Override public Object clone() { try { return super.clone(); } catch (final 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: * *

     *  HashMapTest.bulkTestEntrySet.testClear
     *  
* * is the name of one of the simple tests defined in the sample classes * described above. If the sample HashMapTest class * included this method: * *
     *  public String[] ignoredTests() {
     *      return new String[] { "HashMapTest.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 */ @Override 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 hierarchical {@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(final 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 final 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(final Class startingClass) { this.startingClass = startingClass; } /** * Makes a hierarchical TestSuite based on the starting class. * * @return the hierarchical TestSuite for startingClass */ public TestSuite make() { this.result = new TestSuite(); this.prefix = getBaseName(startingClass); result.setName(prefix); final BulkTest bulk = makeFirstTestCase(startingClass); ignored = new ArrayList(); final 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(final BulkTest bulk) { final Class c = bulk.getClass(); final Method[] all = c.getMethods(); for (final Method element : all) { if (isTest(element)) { addTest(bulk, element); } if (isBulk(element)) { addBulk(bulk, element); } } } /** * 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(final BulkTest bulk, final Method m) { final 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(final BulkTest bulk, final Method m) { final 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 (final InvocationTargetException ex) { ex.getTargetException().printStackTrace(); throw new Error(); // FIXME; } catch (final IllegalAccessException ex) { ex.printStackTrace(); throw new Error(); // FIXME; } // Save current state on the stack. final String oldPrefix = prefix; final 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(final Class c) { String name = c.getName(); final 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(final Class c) { try { return c.getConstructor(new Class[] { String.class }); } catch (final NoSuchMethodException e) { throw new IllegalArgumentException(c + " must provide a (String) constructor"); } } private static BulkTest makeTestCase(final Class c, final Method m) { final Constructor con = getTestCaseConstructor(c); try { return con.newInstance(m.getName()); } catch (final InvocationTargetException e) { e.printStackTrace(); throw new RuntimeException(); // FIXME; } catch (final IllegalAccessException e) { throw new Error(); // should never occur } catch (final InstantiationException e) { throw new RuntimeException(); // FIXME; } } private static BulkTest makeFirstTestCase(final Class c) { final Method[] all = c.getMethods(); for (final Method element : all) { if (isTest(element)) { return makeTestCase(c, element); } } 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(final Method m) { if (!m.getName().startsWith("test")) { return false; } if (m.getReturnType() != Void.TYPE) { return false; } if (m.getParameterTypes().length != 0) { return false; } final 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(final Method m) { if (!m.getName().startsWith("bulkTest")) { return false; } if (m.getReturnType() != BulkTest.class) { return false; } if (m.getParameterTypes().length != 0) { return false; } final int mods = m.getModifiers(); if (Modifier.isStatic(mods)) { return false; } if (Modifier.isAbstract(mods)) { return false; } return true; } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/AbstractLinkedListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/AbstractLinkedListTest.ja100664 14652 12243235516 31723 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections4.list.AbstractListTest; /** * Tests base {@link java.util.LinkedList} methods and contracts. *

* To use, simply extend this class, and implement * the {@link #makeObject()} 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 $Id: AbstractLinkedListTest.java 1477661 2013-04-30 14:27:35Z sebb $ */ public abstract class AbstractLinkedListTest extends AbstractListTest { public AbstractLinkedListTest(final String testName) { super(testName); } @Override public abstract LinkedList makeObject(); /** * Returns the {@link #collection} field cast to a {@link LinkedList}. * * @return the collection field as a List */ @Override public LinkedList getCollection() { return (LinkedList) super.getCollection(); } /** * Returns the {@link #confirmed} field cast to a {@link LinkedList}. * * @return the confirmed field as a List */ protected LinkedList getConfirmedLinkedList() { return (LinkedList) getConfirmed(); } /** * Tests {@link LinkedList#addFirst(Object)}. */ @SuppressWarnings("unchecked") public void testLinkedListAddFirst() { if (!isAddSupported()) { return; } final T o = (T) "hello"; resetEmpty(); getCollection().addFirst(o); getConfirmedLinkedList().addFirst(o); verify(); resetFull(); getCollection().addFirst(o); getConfirmedLinkedList().addFirst(o); verify(); } /** * Tests {@link LinkedList#addLast(Object)}. */ @SuppressWarnings("unchecked") public void testLinkedListAddLast() { if (!isAddSupported()) { return; } final T o = (T) "hello"; resetEmpty(); getCollection().addLast(o); getConfirmedLinkedList().addLast(o); verify(); resetFull(); getCollection().addLast(o); getConfirmedLinkedList().addLast(o); verify(); } /** * Tests {@link LinkedList#getFirst()}. */ public void testLinkedListGetFirst() { resetEmpty(); try { getCollection().getFirst(); fail("getFirst() should throw a NoSuchElementException for an " + "empty list."); } catch (final NoSuchElementException e) { // This is correct } verify(); resetFull(); final Object first = getCollection().getFirst(); final Object confirmedFirst = getConfirmedLinkedList().getFirst(); assertEquals("Result returned by getFirst() was wrong.", confirmedFirst, first); verify(); } /** * Tests {@link LinkedList#getLast()}. */ public void testLinkedListGetLast() { resetEmpty(); try { getCollection().getLast(); fail("getLast() should throw a NoSuchElementException for an " + "empty list."); } catch (final NoSuchElementException e) { // This is correct } verify(); resetFull(); final Object last = getCollection().getLast(); final Object confirmedLast = getConfirmedLinkedList().getLast(); assertEquals("Result returned by getLast() was wrong.", confirmedLast, last); verify(); } /** * Tests {@link LinkedList#removeFirst()}. */ public void testLinkedListRemoveFirst() { if (!isRemoveSupported()) { return; } resetEmpty(); try { getCollection().removeFirst(); fail("removeFirst() should throw a NoSuchElementException for " + "an empty list."); } catch (final NoSuchElementException e) { // This is correct } verify(); resetFull(); final Object first = getCollection().removeFirst(); final Object confirmedFirst = getConfirmedLinkedList().removeFirst(); assertEquals("Result returned by removeFirst() was wrong.", confirmedFirst, first); verify(); } /** * Tests {@link LinkedList#removeLast()}. */ public void testLinkedListRemoveLast() { if (!isRemoveSupported()) { return; } resetEmpty(); try { getCollection().removeLast(); fail("removeLast() should throw a NoSuchElementException for " + "an empty list."); } catch (final NoSuchElementException e) { // This is correct } verify(); resetFull(); final Object last = getCollection().removeLast(); final Object confirmedLast = getConfirmedLinkedList().removeLast(); assertEquals("Result returned by removeLast() was wrong.", confirmedLast, last); verify(); } /** * Returns an empty {@link LinkedList}. */ @Override public Collection makeConfirmedCollection() { return new LinkedList(); } /** * Returns a full {@link LinkedList}. */ @Override public Collection makeConfirmedFullCollection() { final List list = new LinkedList(); list.addAll(Arrays.asList(getFullElements())); return list; } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java100664 24464 12243235516 31156 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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 org.apache.commons.collections4.functors.ConstantFactory; import org.apache.commons.collections4.functors.ExceptionFactory; import org.junit.Test; /** * Tests the org.apache.commons.collections.FactoryUtils class. * * @since 3.0 * @version $Id: FactoryUtilsTest.java 1540705 2013-11-11 13:22:32Z ebourg $ */ public class FactoryUtilsTest extends junit.framework.TestCase { /** * Set up instance variables required by this test case. */ @Override public void setUp() { } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() { } // exceptionFactory //------------------------------------------------------------------ public void testExceptionFactory() { assertNotNull(FactoryUtils.exceptionFactory()); assertSame(FactoryUtils.exceptionFactory(), FactoryUtils.exceptionFactory()); try { FactoryUtils.exceptionFactory().create(); } catch (final FunctorException ex) { try { FactoryUtils.exceptionFactory().create(); } catch (final FunctorException ex2) { return; } } fail(); } // nullFactory //------------------------------------------------------------------ public void testNullFactory() { final Factory factory = FactoryUtils.nullFactory(); assertNotNull(factory); final Object created = factory.create(); assertNull(created); } // constantFactory //------------------------------------------------------------------ public void testConstantFactoryNull() { final Factory factory = FactoryUtils.constantFactory(null); assertNotNull(factory); final Object created = factory.create(); assertNull(created); } public void testConstantFactoryConstant() { final Integer constant = Integer.valueOf(9); final Factory factory = FactoryUtils.constantFactory(constant); assertNotNull(factory); final Integer created = factory.create(); assertSame(constant, created); } // prototypeFactory //------------------------------------------------------------------ public void testPrototypeFactoryNull() { assertSame(ConstantFactory.NULL_INSTANCE, FactoryUtils.prototypeFactory(null)); } public void testPrototypeFactoryPublicCloneMethod() throws Exception { final Date proto = new Date(); final Factory factory = FactoryUtils.prototypeFactory(proto); assertNotNull(factory); final Date created = factory.create(); assertTrue(proto != created); assertEquals(proto, created); // check serialisation works final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(factory); out.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); in.readObject(); in.close(); } public void testPrototypeFactoryPublicCopyConstructor() throws Exception { final Mock1 proto = new Mock1(6); Factory factory = FactoryUtils.prototypeFactory(proto); assertNotNull(factory); final 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 (final NotSerializableException ex) { out.close(); } factory = FactoryUtils.prototypeFactory(new Mock2("S")); buffer = new ByteArrayOutputStream(); out = new ObjectOutputStream(buffer); out.writeObject(factory); out.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); in.readObject(); in.close(); } public void testPrototypeFactoryPublicSerialization() throws Exception { final Integer proto = Integer.valueOf(9); final Factory factory = FactoryUtils.prototypeFactory(proto); assertNotNull(factory); final Integer created = factory.create(); assertTrue(proto != created); assertEquals(proto, created); // check serialisation works final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(factory); out.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); in.readObject(); in.close(); } public void testPrototypeFactoryPublicSerializationError() { final Mock2 proto = new Mock2(new Object()); final Factory factory = FactoryUtils.prototypeFactory(proto); assertNotNull(factory); try { factory.create(); } catch (final FunctorException ex) { assertTrue(ex.getCause() instanceof IOException); return; } fail(); } public void testPrototypeFactoryPublicBad() { final Object proto = new Object(); try { FactoryUtils.prototypeFactory(proto); } catch (final IllegalArgumentException ex) { return; } fail(); } public static class Mock1 { private final int iVal; public Mock1(final int val) { iVal = val; } public Mock1(final Mock1 mock) { iVal = mock.iVal; } @Override public boolean equals(final Object obj) { if (obj instanceof Mock1) { if (iVal == ((Mock1) obj).iVal) { return true; } } return false; } @Override public int hashCode() { // please Findbugs return super.hashCode(); } } public static class Mock2 implements Serializable { /** * Generated serial version ID. */ private static final long serialVersionUID = 4899282162482588924L; private final Object iVal; public Mock2(final Object val) { iVal = val; } @Override public boolean equals(final Object obj) { if (obj instanceof Mock2) { if (iVal == ((Mock2) obj).iVal) { return true; } } return false; } @Override public int hashCode() { // please Findbugs return super.hashCode(); } } public static class Mock3 { private static int cCounter = 0; private final int iVal; public Mock3() { iVal = cCounter++; } public int getValue() { return iVal; } } // instantiateFactory //------------------------------------------------------------------ @Test(expected=IllegalArgumentException.class) public void instantiateFactoryNull() { FactoryUtils.instantiateFactory(null); } @Test public void instantiateFactorySimple() { final Factory factory = FactoryUtils.instantiateFactory(Mock3.class); assertNotNull(factory); Mock3 created = factory.create(); assertEquals(0, created.getValue()); created = factory.create(); assertEquals(1, created.getValue()); } @Test(expected=IllegalArgumentException.class) public void instantiateFactoryMismatch() { FactoryUtils.instantiateFactory(Date.class, null, new Object[] {null}); } @Test(expected=IllegalArgumentException.class) public void instantiateFactoryNoConstructor() { FactoryUtils.instantiateFactory(Date.class, new Class[] {Long.class}, new Object[] {null}); } @Test public void instantiateFactoryComplex() { TimeZone.setDefault(TimeZone.getTimeZone("GMT")); // 2nd Jan 1970 final Factory factory = FactoryUtils.instantiateFactory(Date.class, new Class[] {Integer.TYPE, Integer.TYPE, Integer.TYPE}, new Object[] {Integer.valueOf(70), Integer.valueOf(0), Integer.valueOf(2)}); assertNotNull(factory); final Date created = factory.create(); // long time of 1 day (== 2nd Jan 1970) assertEquals(new Date(1000 * 60 * 60 * 24), created); } // misc tests //------------------------------------------------------------------ /** * Test that all Factory singletones hold singleton pattern in * serialization/deserialization process. */ public void testSingletonPatternInSerialization() { final Object[] singletones = new Object[] { ExceptionFactory.INSTANCE, }; for (final Object original : singletones) { TestUtils.assertSameAfterSerialization( "Singletone patern broken for " + original.getClass(), original ); } } } ././@LongLink100644 0 0 167 12243235652 10263 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableOrderedBidiMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableOrder100664 6354 12243235516 31723 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.Map; import java.util.TreeMap; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.OrderedBidiMap; import org.apache.commons.collections4.Unmodifiable; /** * JUnit tests. * * @version $Id: UnmodifiableOrderedBidiMapTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class UnmodifiableOrderedBidiMapTest, V extends Comparable> extends AbstractOrderedBidiMapTest { public static Test suite() { return BulkTest.makeSuite(UnmodifiableOrderedBidiMapTest.class); } public UnmodifiableOrderedBidiMapTest(final String testName) { super(testName); } @Override public OrderedBidiMap makeObject() { return UnmodifiableOrderedBidiMap.unmodifiableOrderedBidiMap(new TreeBidiMap()); } @Override public OrderedBidiMap makeFullMap() { final OrderedBidiMap bidi = new TreeBidiMap(); addSampleMappings(bidi); return UnmodifiableOrderedBidiMap.unmodifiableOrderedBidiMap(bidi); } @Override public Map makeConfirmedMap() { return new TreeMap(); } /** * Override to prevent infinite recursion of tests. */ @Override public String[] ignoredTests() { return new String[] {"UnmodifiableOrderedBidiMapTest.bulkTestInverseMap.bulkTestInverseMap"}; } @Override public boolean isAllowNullKey() { return false; } @Override public boolean isAllowNullValue() { return false; } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isPutChangeSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { final OrderedBidiMap map = makeFullMap(); assertSame(map, UnmodifiableOrderedBidiMap.unmodifiableOrderedBidiMap(map)); try { UnmodifiableOrderedBidiMap.unmodifiableOrderedBidiMap(null); fail(); } catch (final IllegalArgumentException ex) {} } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/AbstractOrderedBidiMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/AbstractOrderedBi100664 15357 12243235516 31677 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.BulkTest; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.OrderedBidiMap; import org.apache.commons.collections4.iterators.AbstractMapIteratorTest; /** * Abstract test class for {@link OrderedBidiMap} methods and contracts. * * @version $Id: AbstractOrderedBidiMapTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractOrderedBidiMapTest extends AbstractBidiMapTest { public AbstractOrderedBidiMapTest(final String testName) { super(testName); } public AbstractOrderedBidiMapTest() { super(); } //----------------------------------------------------------------------- public void testFirstKey() { resetEmpty(); OrderedBidiMap bidi = getMap(); try { bidi.firstKey(); fail(); } catch (final NoSuchElementException ex) {} resetFull(); bidi = getMap(); final K confirmedFirst = confirmed.keySet().iterator().next(); assertEquals(confirmedFirst, bidi.firstKey()); } public void testLastKey() { resetEmpty(); OrderedBidiMap bidi = getMap(); try { bidi.lastKey(); fail(); } catch (final NoSuchElementException ex) {} resetFull(); bidi = getMap(); K confirmedLast = null; for (final 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()) { try { assertEquals(null, bidi.nextKey(null)); // this is allowed too } catch (final NullPointerException ex) {} } else { assertEquals(null, bidi.nextKey(null)); } resetFull(); bidi = (OrderedBidiMap) map; final Iterator it = confirmed.keySet().iterator(); K confirmedLast = it.next(); while (it.hasNext()) { final K confirmedObject = it.next(); assertEquals(confirmedObject, bidi.nextKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, bidi.nextKey(confirmedLast)); if (!isAllowNullKey()) { try { bidi.nextKey(null); fail(); } catch (final NullPointerException ex) {} } else { assertEquals(null, bidi.nextKey(null)); } } public void testPreviousKey() { resetEmpty(); OrderedBidiMap bidi = getMap(); assertEquals(null, bidi.previousKey(getOtherKeys()[0])); if (!isAllowNullKey()) { try { assertEquals(null, bidi.previousKey(null)); // this is allowed too } catch (final NullPointerException ex) {} } else { assertEquals(null, bidi.previousKey(null)); } resetFull(); bidi = getMap(); final List list = new ArrayList(confirmed.keySet()); Collections.reverse(list); final Iterator it = list.iterator(); K confirmedLast = it.next(); while (it.hasNext()) { final K confirmedObject = it.next(); assertEquals(confirmedObject, bidi.previousKey(confirmedLast)); confirmedLast = confirmedObject; } assertEquals(null, bidi.previousKey(confirmedLast)); if (!isAllowNullKey()) { try { bidi.previousKey(null); fail(); } catch (final NullPointerException ex) {} } else { assertEquals(null, bidi.previousKey(null)); } } //----------------------------------------------------------------------- public BulkTest bulkTestOrderedMapIterator() { return new TestBidiOrderedMapIterator(); } /** * {@inheritDoc} */ @Override public OrderedBidiMap getMap() { return (OrderedBidiMap) super.getMap(); } public class TestBidiOrderedMapIterator extends AbstractMapIteratorTest { public TestBidiOrderedMapIterator() { super("TestBidiOrderedMapIterator"); } @Override public V[] addSetValues() { return AbstractOrderedBidiMapTest.this.getNewSampleValues(); } @Override public boolean supportsRemove() { return AbstractOrderedBidiMapTest.this.isRemoveSupported(); } @Override public boolean supportsSetValue() { return AbstractOrderedBidiMapTest.this.isSetValueSupported(); } @Override public MapIterator makeEmptyIterator() { resetEmpty(); return AbstractOrderedBidiMapTest.this.getMap().mapIterator(); } @Override public MapIterator makeObject() { resetFull(); return AbstractOrderedBidiMapTest.this.getMap().mapIterator(); } @Override public Map getMap() { // assumes makeFullMapIterator() called first return AbstractOrderedBidiMapTest.this.map; } @Override public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return AbstractOrderedBidiMapTest.this.confirmed; } @Override public void verify() { super.verify(); AbstractOrderedBidiMapTest.this.verify(); } } } ././@LongLink100644 0 0 174 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/AbstractOrderedBidiMapDecoratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/AbstractOrderedBi100664 4766 12243235516 31661 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.collections4.OrderedBidiMap; /** * Test class for AbstractOrderedBidiMapDecorator. * * @version $Id: AbstractOrderedBidiMapDecoratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class AbstractOrderedBidiMapDecoratorTest extends AbstractOrderedBidiMapTest { public AbstractOrderedBidiMapDecoratorTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @Override public OrderedBidiMap makeObject() { return new TestOrderedBidiMap(); } @Override public SortedMap makeConfirmedMap() { return new TreeMap(); } @Override public boolean isAllowNullKey() { return false; } @Override public boolean isAllowNullValue() { return false; } @Override 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(final OrderedBidiMap map) { super(map); } @Override public OrderedBidiMap inverseBidiMap() { if (inverse == null) { inverse = new TestOrderedBidiMap(decorated().inverseBidiMap()); inverse.inverse = this; } return inverse; } } } ././@LongLink100644 0 0 166 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableSortedBidiMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableSorte100664 7032 12243235516 31736 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.SortedMap; import java.util.TreeMap; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.SortedBidiMap; import org.apache.commons.collections4.Unmodifiable; /** * JUnit tests. * * @version $Id: UnmodifiableSortedBidiMapTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class UnmodifiableSortedBidiMapTest, V extends Comparable> extends AbstractSortedBidiMapTest { public static Test suite() { return BulkTest.makeSuite(UnmodifiableSortedBidiMapTest.class); } public UnmodifiableSortedBidiMapTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public SortedBidiMap makeObject() { return UnmodifiableSortedBidiMap.unmodifiableSortedBidiMap(new DualTreeBidiMap()); } @Override public SortedBidiMap makeFullMap() { final SortedBidiMap bidi = new DualTreeBidiMap(); addSampleMappings(bidi); return UnmodifiableSortedBidiMap.unmodifiableSortedBidiMap(bidi); } @Override public SortedMap makeConfirmedMap() { return new TreeMap(); } @Override public boolean isSubMapViewsSerializable() { // TreeMap sub map views have a bug in deserialization. return false; } @Override public String[] ignoredTests() { // Override to prevent infinite recursion of tests. return new String[] {"UnmodifiableSortedBidiMapTest.bulkTestInverseMap.bulkTestInverseMap"}; } //----------------------------------------------------------------------- @Override public boolean isAllowNullKey() { return false; } @Override public boolean isAllowNullValue() { return false; } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isPutChangeSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { final SortedBidiMap map = makeFullMap(); assertSame(map, UnmodifiableSortedBidiMap.unmodifiableSortedBidiMap(map)); try { UnmodifiableSortedBidiMap.unmodifiableSortedBidiMap(null); fail(); } catch (final IllegalArgumentException ex) {} } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/DualLinkedHashBidiMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/DualLinkedHashBid100664 4236 12243235516 31565 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * JUnit tests. * * @version $Id: DualLinkedHashBidiMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class DualLinkedHashBidiMapTest extends AbstractBidiMapTest { public static Test suite() { return BulkTest.makeSuite(DualLinkedHashBidiMapTest.class); } public DualLinkedHashBidiMapTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @Override public DualLinkedHashBidiMap makeObject() { return new DualLinkedHashBidiMap(); } @Override public String getCompatibilityVersion() { return "4"; } /** * Override to prevent infinite recursion of tests. */ @Override public String[] ignoredTests() { return new String[] { "DualLinkedHashBidiMapTest.bulkTestInverseMap.bulkTestInverseMap" }; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/DualLinkedHashBidiMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/DualLinkedHashBidiMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/AbstractBidiMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/AbstractBidiMapTe100664 50675 12243235516 31640 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.BidiMap; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.iterators.AbstractMapIteratorTest; import org.apache.commons.collections4.map.AbstractIterableMapTest; /** * Abstract test class for {@link BidiMap} methods and contracts. * * @version $Id: AbstractBidiMapTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractBidiMapTest extends AbstractIterableMapTest { public AbstractBidiMapTest(final String testName) { super(testName); } public AbstractBidiMapTest() { super("Inverse"); } //----------------------------------------------------------------------- /** * Override to create a full BidiMap other than the default. * * @return a full BidiMap implementation. */ @Override public BidiMap makeFullMap() { return (BidiMap) super.makeFullMap(); } /** * Override to return the empty BidiMap. */ @Override public abstract BidiMap makeObject(); /** * Override to indicate to AbstractTestMap this is a BidiMap. */ @Override public boolean isAllowDuplicateValues() { return false; } /** * Override as DualHashBidiMap didn't exist until version 3. */ @Override public String getCompatibilityVersion() { return "4"; } // BidiPut //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testBidiPut() { if (!isPutAddSupported() || !isPutChangeSupported()) { return; } final BidiMap map = makeObject(); final BidiMap inverse = map.inverseBidiMap(); assertEquals(0, map.size()); assertEquals(map.size(), inverse.size()); map.put((K) "A", (V) "B"); assertEquals(1, map.size()); assertEquals(map.size(), inverse.size()); assertEquals("B", map.get("A")); assertEquals("A", inverse.get("B")); map.put((K) "A", (V) "C"); assertEquals(1, map.size()); assertEquals(map.size(), inverse.size()); assertEquals("C", map.get("A")); assertEquals("A", inverse.get("C")); map.put((K) "B", (V) "C"); assertEquals(1, map.size()); assertEquals(map.size(), inverse.size()); assertEquals("C", map.get("B")); assertEquals("B", inverse.get("C")); map.put((K) "E", (V) "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. */ @Override public void verify() { verifyInverse(); super.verify(); } public void verifyInverse() { assertEquals(map.size(), ((BidiMap) map).inverseBidiMap().size()); final Map map1 = new HashMap(map); final Map map2 = new HashMap(((BidiMap) map).inverseBidiMap()); final Set keys1 = map1.keySet(); final Set keys2 = map2.keySet(); final Collection values1 = map1.values(); final 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(makeFullMap(), getSampleKeys()[0], getSampleValues()[0]); } public void testBidiGetKeyInverse() { doTestGetKey( makeFullMap().inverseBidiMap(), getSampleValues()[0], getSampleKeys()[0]); } private void doTestGetKey(final BidiMap map, final Object key, final 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 = makeFullMap(); final BidiMap inverseMap = map.inverseBidiMap(); assertSame( "Inverse of inverse is not equal to original.", map, inverseMap.inverseBidiMap()); assertEquals( "Value not found for key.", getSampleKeys()[0], inverseMap.get(getSampleValues()[0])); assertEquals( "Key not found for value.", getSampleValues()[0], inverseMap.getKey(getSampleKeys()[0])); } //----------------------------------------------------------------------- public void testBidiModifyEntrySet() { if (!isSetValueSupported()) { return; } modifyEntrySet(makeFullMap()); modifyEntrySet(makeFullMap().inverseBidiMap()); } @SuppressWarnings("unchecked") private void modifyEntrySet(final BidiMap map) { // Gets first entry final Map.Entry 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((T) 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()) { try { makeFullMap().clear(); fail(); } catch(final UnsupportedOperationException ex) {} return; } BidiMap map = makeFullMap(); map.clear(); assertTrue("Map was not cleared.", map.isEmpty()); assertTrue("Inverse map was not cleared.", map.inverseBidiMap().isEmpty()); // Tests clear on inverse map = makeFullMap().inverseBidiMap(); map.clear(); assertTrue("Map was not cleared.", map.isEmpty()); assertTrue("Inverse map was not cleared.", map.inverseBidiMap().isEmpty()); } //----------------------------------------------------------------------- public void testBidiRemove() { if (!isRemoveSupported()) { try { makeFullMap().remove(getSampleKeys()[0]); fail(); } catch(final UnsupportedOperationException ex) {} try { makeFullMap().removeValue(getSampleValues()[0]); fail(); } catch(final UnsupportedOperationException ex) {} return; } remove(makeFullMap(), getSampleKeys()[0]); remove(makeFullMap().inverseBidiMap(), getSampleValues()[0]); removeValue(makeFullMap(), getSampleValues()[0]); removeValue(makeFullMap().inverseBidiMap(), getSampleKeys()[0]); assertEquals(null, makeFullMap().removeValue("NotPresent")); } private void remove(final BidiMap map, final 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 void removeValue(final BidiMap map, final 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(); final Iterator keys = map.keySet().iterator(); final Iterator values = map.values().iterator(); for (; keys.hasNext() && values.hasNext();) { final K key = keys.next(); final V value = values.next(); assertSame(map.get(key), value); } assertEquals(false, keys.hasNext()); assertEquals(false, values.hasNext()); } //----------------------------------------------------------------------- public void testBidiRemoveByKeySet() { if (!isRemoveSupported()) { return; } removeByKeySet(makeFullMap(), getSampleKeys()[0], getSampleValues()[0]); removeByKeySet(makeFullMap().inverseBidiMap(), getSampleValues()[0], getSampleKeys()[0]); } private void removeByKeySet(final BidiMap map, final Object key, final 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()) { return; } removeByEntrySet(makeFullMap(), getSampleKeys()[0], getSampleValues()[0]); removeByEntrySet(makeFullMap().inverseBidiMap(), getSampleValues()[0], getSampleKeys()[0]); } private void removeByEntrySet(final BidiMap map, final Object key, final Object value) { final 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)); } /** * {@inheritDoc} */ @Override public BidiMap getMap() { return (BidiMap) super.getMap(); } //----------------------------------------------------------------------- @Override public BulkTest bulkTestMapEntrySet() { return new TestBidiMapEntrySet(); } public class TestBidiMapEntrySet extends TestMapEntrySet { public TestBidiMapEntrySet() { super(); } public void testMapEntrySetIteratorEntrySetValueCrossCheck() { final K key1 = getSampleKeys()[0]; final K key2 = getSampleKeys()[1]; final V newValue1 = getNewSampleValues()[0]; final V newValue2 = getNewSampleValues()[1]; resetFull(); // explicitly get entries as sample values/keys are connected for some maps // such as BeanMap Iterator> it = TestBidiMapEntrySet.this.getCollection().iterator(); final Map.Entry entry1 = getEntry(it, key1); it = TestBidiMapEntrySet.this.getCollection().iterator(); final Map.Entry entry2 = getEntry(it, key2); Iterator> itConfirmed = TestBidiMapEntrySet.this.getConfirmed().iterator(); final Map.Entry entryConfirmed1 = getEntry(itConfirmed, key1); itConfirmed = TestBidiMapEntrySet.this.getConfirmed().iterator(); final Map.Entry entryConfirmed2 = getEntry(itConfirmed, key2); TestBidiMapEntrySet.this.verify(); if (!isSetValueSupported()) { try { entry1.setValue(newValue1); } catch (final 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 (final IllegalArgumentException ex) { return; // simplest way of dealing with tricky situation } entryConfirmed2.setValue(newValue1); AbstractBidiMapTest.this.getConfirmed().remove(key1); assertEquals(newValue1, entry2.getValue()); assertEquals(true, AbstractBidiMapTest.this.getMap().containsKey(entry2.getKey())); assertEquals(true, AbstractBidiMapTest.this.getMap().containsValue(newValue1)); assertEquals(newValue1, AbstractBidiMapTest.this.getMap().get(entry2.getKey())); assertEquals(false, AbstractBidiMapTest.this.getMap().containsKey(key1)); assertEquals(false, AbstractBidiMapTest.this.getMap().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 AbstractBidiMapTest { final AbstractBidiMapTest main; public TestInverseBidiMap(final AbstractBidiMapTest main) { super(); this.main = main; } @Override public BidiMap makeObject() { return main.makeObject().inverseBidiMap(); } @Override public BidiMap makeFullMap() { return main.makeFullMap().inverseBidiMap(); } @Override public V[] getSampleKeys() { return main.getSampleValues(); } @Override public K[] getSampleValues() { return main.getSampleKeys(); } @Override public String getCompatibilityVersion() { return main.getCompatibilityVersion(); } @Override public boolean isAllowNullKey() { return main.isAllowNullKey(); } @Override public boolean isAllowNullValue() { return main.isAllowNullValue(); } @Override public boolean isPutAddSupported() { return main.isPutAddSupported(); } @Override public boolean isPutChangeSupported() { return main.isPutChangeSupported(); } @Override public boolean isSetValueSupported() { return main.isSetValueSupported(); } @Override public boolean isRemoveSupported() { return main.isRemoveSupported(); } } //----------------------------------------------------------------------- public BulkTest bulkTestBidiMapIterator() { return new TestBidiMapIterator(); } public class TestBidiMapIterator extends AbstractMapIteratorTest { public TestBidiMapIterator() { super("TestBidiMapIterator"); } @Override public V[] addSetValues() { return AbstractBidiMapTest.this.getNewSampleValues(); } @Override public boolean supportsRemove() { return AbstractBidiMapTest.this.isRemoveSupported(); } @Override public boolean supportsSetValue() { return AbstractBidiMapTest.this.isSetValueSupported(); } @Override public MapIterator makeEmptyIterator() { resetEmpty(); return AbstractBidiMapTest.this.getMap().mapIterator(); } @Override public MapIterator makeObject() { resetFull(); return AbstractBidiMapTest.this.getMap().mapIterator(); } @Override public BidiMap getMap() { // assumes makeFullMapIterator() called first return AbstractBidiMapTest.this.getMap(); } @Override public Map getConfirmedMap() { // assumes makeFullMapIterator() called first return AbstractBidiMapTest.this.getConfirmed(); } @Override public void verify() { super.verify(); AbstractBidiMapTest.this.verify(); } } //----------------------------------------------------------------------- public void testBidiMapIteratorSet() { final V newValue1 = getOtherValues()[0]; final V newValue2 = getOtherValues()[1]; resetFull(); final BidiMap bidi = getMap(); final MapIterator it = bidi.mapIterator(); assertEquals(true, it.hasNext()); final K key1 = it.next(); if (!isSetValueSupported()) { try { it.setValue(newValue1); fail(); } catch (final 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(); final K 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 (final IllegalArgumentException ex) { return; // simplest way of dealing with tricky situation } confirmed.put(key2, newValue1); AbstractBidiMapTest.this.getConfirmed().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(); } } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/DualHashBidiMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/DualHashBidiMapTe100664 4021 12243235516 31526 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * JUnit tests. * * @version $Id: DualHashBidiMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class DualHashBidiMapTest extends AbstractBidiMapTest { public static Test suite() { return BulkTest.makeSuite(DualHashBidiMapTest.class); } public DualHashBidiMapTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @Override public DualHashBidiMap makeObject() { return new DualHashBidiMap(); } /** * Override to prevent infinite recursion of tests. */ @Override public String[] ignoredTests() { return new String[] { "DualHashBidiMapTest.bulkTestInverseMap.bulkTestInverseMap" }; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/DualHashBidiMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/DualHashBidiMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/DualTreeBidiMap2Test.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/DualTreeBidiMap2T100664 17221 12243235516 31505 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.TreeMap; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.SortedBidiMap; import org.apache.commons.collections4.comparators.ComparableComparator; import org.apache.commons.collections4.comparators.ReverseComparator; /** * JUnit tests. * * @version $Id: DualTreeBidiMap2Test.java 1543252 2013-11-19 00:41:17Z ggregory $ */ @SuppressWarnings("boxing") public class DualTreeBidiMap2Test, V extends Comparable> extends AbstractSortedBidiMapTest { public static Test suite() { return BulkTest.makeSuite(DualTreeBidiMap2Test.class); } public DualTreeBidiMap2Test(final String testName) { super(testName); } @Override public DualTreeBidiMap makeObject() { return new DualTreeBidiMap( new ReverseComparator(ComparableComparator. comparableComparator()), new ReverseComparator(ComparableComparator. comparableComparator())); } @Override public TreeMap makeConfirmedMap() { return new TreeMap(new ReverseComparator(ComparableComparator.comparableComparator())); } public void testComparator() { resetEmpty(); final SortedBidiMap bidi = (SortedBidiMap) map; assertNotNull(bidi.comparator()); assertTrue(bidi.comparator() instanceof ReverseComparator); } public void testComparator2() { final DualTreeBidiMap dtbm = new DualTreeBidiMap( String.CASE_INSENSITIVE_ORDER, null); dtbm.put("two", 0); dtbm.put("one", 1); assertEquals("one", dtbm.firstKey()); assertEquals("two", dtbm.lastKey()); } public void testSerializeDeserializeCheckComparator() throws Exception { final SortedBidiMap obj = makeObject(); if (obj instanceof Serializable && isTestSerialization()) { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(obj); out.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); final Object dest = in.readObject(); in.close(); final SortedBidiMap bidi = (SortedBidiMap) dest; assertNotNull(obj.comparator()); assertNotNull(bidi.comparator()); assertTrue(bidi.comparator() instanceof ReverseComparator); } } private static class IntegerComparator implements Comparator, Serializable{ private static final long serialVersionUID = 1L; public int compare(final Integer o1, final Integer o2) { return o1.compareTo(o2); } } public void testCollections364() throws Exception { final DualTreeBidiMap original = new DualTreeBidiMap( String.CASE_INSENSITIVE_ORDER, new IntegerComparator()); final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(original); out.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); @SuppressWarnings("unchecked") final DualTreeBidiMap deserialised = (DualTreeBidiMap) in.readObject(); in.close(); assertNotNull(original.comparator()); assertNotNull(deserialised.comparator()); assertEquals(original.comparator().getClass(), deserialised.comparator().getClass()); assertEquals(original.valueComparator().getClass(), deserialised.valueComparator().getClass()); } public void testSortOrder() throws Exception { final SortedBidiMap sm = makeFullMap(); // Sort by the comparator used in the makeEmptyBidiMap() method List newSortedKeys = getAsList(getSampleKeys()); Collections.sort(newSortedKeys, new ReverseComparator(ComparableComparator.comparableComparator())); newSortedKeys = Collections.unmodifiableList(newSortedKeys); final Iterator mapIter = sm.keySet().iterator(); final Iterator expectedIter = newSortedKeys.iterator(); while (expectedIter.hasNext()) { final K expectedKey = expectedIter.next(); final K 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); } } @Override public String getCompatibilityVersion() { return "4.Test2"; } /** * Override to prevent infinite recursion of tests. */ @Override public String[] ignoredTests() { String recursiveTest = "DualTreeBidiMap2Test.bulkTestInverseMap.bulkTestInverseMap"; if (IBMJDK16) { final String preSub = "DualTreeBidiMap2Test.bulkTestSubMap."; final String preTail = "DualTreeBidiMap2Test.bulkTestTailMap."; return new String[] { recursiveTest, preSub + "bulkTestMapEntrySet.testCollectionIteratorRemove", preSub + "bulkTestMapValues.testCollectionIteratorRemove", preTail + "testMapRemove", preTail + "bulkTestMapEntrySet.testCollectionIteratorRemove", preTail + "bulkTestMapEntrySet.testCollectionRemoveAll", preTail + "bulkTestMapKeySet.testCollectionIteratorRemove", preTail + "bulkTestMapKeySet.testCollectionRemoveAll", preTail + "bulkTestMapValues.testCollectionClear", preTail + "bulkTestMapValues.testCollectionRemoveAll", preTail + "bulkTestMapValues.testCollectionRetainAll" }; } else { return new String[] { recursiveTest }; } } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/DualTreeBidiMap.emptyCollection.version4.Test2.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/DualTreeBidiMap.fullCollection.version4.Test2.obj"); // } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/TreeBidiMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/TreeBidiMapTest.j100664 4770 12243235516 31546 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.TreeMap; import junit.framework.Test; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.BulkTest; /** * JUnit tests. * * @version $Id: TreeBidiMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class TreeBidiMapTest, V extends Comparable> extends AbstractOrderedBidiMapTest { public static Test suite() { return BulkTest.makeSuite(TreeBidiMapTest.class); } public TreeBidiMapTest(final String testName) { super(testName); } @Override public BidiMap makeObject() { return new TreeBidiMap(); } @Override public TreeMap makeConfirmedMap() { return new TreeMap(); } /** * Override to prevent infinite recursion of tests. */ @Override public String[] ignoredTests() { return new String[] {"TreeBidiMapTest.bulkTestInverseMap.bulkTestInverseMap"}; } @Override public boolean isAllowNullKey() { return false; } @Override public boolean isAllowNullValue() { return false; } @Override public boolean isSetValueSupported() { return false; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/TreeBidiMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/TreeBidiMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableBidiMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableBidiM100664 5644 12243235516 31635 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.HashMap; import java.util.Map; import junit.framework.Test; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.Unmodifiable; /** * JUnit tests. * * @version $Id: UnmodifiableBidiMapTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class UnmodifiableBidiMapTest extends AbstractBidiMapTest { public static Test suite() { return BulkTest.makeSuite(UnmodifiableBidiMapTest.class); } public UnmodifiableBidiMapTest(final String testName) { super(testName); } @Override public BidiMap makeObject() { return UnmodifiableBidiMap.unmodifiableBidiMap(new DualHashBidiMap()); } @Override public BidiMap makeFullMap() { final BidiMap bidi = new DualHashBidiMap(); addSampleMappings(bidi); return UnmodifiableBidiMap.unmodifiableBidiMap(bidi); } @Override public Map makeConfirmedMap() { return new HashMap(); } /** * Override to prevent infinite recursion of tests. */ @Override public String[] ignoredTests() { return new String[] {"UnmodifiableBidiMapTest.bulkTestInverseMap.bulkTestInverseMap"}; } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isPutChangeSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { final BidiMap map = makeFullMap(); assertSame(map, UnmodifiableBidiMap.unmodifiableBidiMap(map)); try { UnmodifiableBidiMap.unmodifiableBidiMap(null); fail(); } catch (final IllegalArgumentException ex) {} } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/DualTreeBidiMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/DualTreeBidiMapTe100664 6214 12243235516 31550 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * JUnit tests. * * @version $Id: DualTreeBidiMapTest.java 1542074 2013-11-14 20:57:02Z tn $ */ public class DualTreeBidiMapTest, V extends Comparable> extends AbstractSortedBidiMapTest { public static Test suite() { return BulkTest.makeSuite(DualTreeBidiMapTest.class); } public DualTreeBidiMapTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @Override public DualTreeBidiMap makeObject() { return new DualTreeBidiMap(); } /** * Override to prevent infinite recursion of tests. */ @Override public String[] ignoredTests() { final String recursiveTest = "DualTreeBidiMapTest.bulkTestInverseMap.bulkTestInverseMap"; if (IBMJDK16) { final String preSub = "DualTreeBidiMapTest.bulkTestSubMap."; final String preTail = "DualTreeBidiMapTest.bulkTestTailMap."; return new String[] { recursiveTest, preSub + "bulkTestMapEntrySet.testCollectionIteratorRemove", preSub + "bulkTestMapValues.testCollectionIteratorRemove", preTail + "testMapRemove", preTail + "bulkTestMapEntrySet.testCollectionIteratorRemove", preTail + "bulkTestMapEntrySet.testCollectionRemoveAll", preTail + "bulkTestMapKeySet.testCollectionIteratorRemove", preTail + "bulkTestMapKeySet.testCollectionRemoveAll", preTail + "bulkTestMapValues.testCollectionClear", preTail + "bulkTestMapValues.testCollectionRemoveAll", preTail + "bulkTestMapValues.testCollectionRetainAll" }; } else { return new String[] { recursiveTest }; } } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/DualTreeBidiMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) map, "src/test/resources/data/test/DualTreeBidiMap.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/AbstractSortedBidiMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/bidimap/AbstractSortedBid100664 67125 12243235516 31717 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.ArrayList; 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.collections4.BulkTest; import org.apache.commons.collections4.SortedBidiMap; import org.apache.commons.collections4.map.AbstractSortedMapTest; /** * Abstract test class for {@link SortedBidiMap} methods and contracts. * * @version $Id: AbstractSortedBidiMapTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractSortedBidiMapTest, V extends Comparable> extends AbstractOrderedBidiMapTest { protected List sortedKeys; protected List sortedValues = new ArrayList(); protected SortedSet sortedNewValues = new TreeSet(); public AbstractSortedBidiMapTest(final String testName) { super(testName); sortedKeys = getAsList(getSampleKeys()); Collections.sort(sortedKeys); sortedKeys = Collections.unmodifiableList(sortedKeys); final Map map = new TreeMap(); addSampleMappings(map); sortedValues.addAll(map.values()); sortedValues = Collections.unmodifiableList(sortedValues); sortedNewValues.addAll(this. getAsList(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())); // } //----------------------------------------------------------------------- @Override public boolean isAllowNullKey() { return false; } @Override public boolean isAllowNullValue() { return false; } /** * {@inheritDoc} */ @Override public abstract SortedBidiMap makeObject(); /** * {@inheritDoc} */ @Override public SortedBidiMap makeFullMap() { return (SortedBidiMap) super.makeFullMap(); } @Override public SortedMap makeConfirmedMap() { return new TreeMap(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- public void testBidiHeadMapContains() { // extra test as other tests get complex final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); final K first = it.next(); final K toKey = it.next(); final K second = it.next(); final V firstValue = sm.get(first); final V secondValue = sm.get(second); final 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()) { return; } // extra test as other tests get complex final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); final K first = it.next(); final K second = it.next(); final K toKey = it.next(); final V firstValue = sm.get(first); final V secondValue = sm.get(second); final V toKeyValue = sm.get(toKey); final SortedMap sub = sm.headMap(toKey); final 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()) { return; } // extra test as other tests get complex final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); final K first = it.next(); final K second = it.next(); final K toKey = it.next(); final int size = sm.size(); final 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)); final V 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)); final V 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()) { return; } // extra test as other tests get complex final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); final K first = it.next(); final K second = it.next(); final K toKey = it.next(); final int size = sm.size(); final SortedMap sub = sm.headMap(toKey); final Set> set = sub.entrySet(); assertEquals(2, sub.size()); assertEquals(2, set.size()); final Iterator> it2 = set.iterator(); final Map.Entry firstEntry = cloneMapEntry(it2.next()); final Map.Entry secondEntry = cloneMapEntry(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 final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); final K first = it.next(); final K fromKey = it.next(); final K second = it.next(); final V firstValue = sm.get(first); final V fromKeyValue = sm.get(fromKey); final V secondValue = sm.get(second); final 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()) { return; } // extra test as other tests get complex final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); it.next(); it.next(); final K first = it.next(); final K fromKey = it.next(); final K second = it.next(); final V firstValue = sm.get(first); final V fromKeyValue = sm.get(fromKey); final V secondValue = sm.get(second); final SortedMap sub = sm.tailMap(fromKey); final 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()) { return; } // extra test as other tests get complex final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); it.next(); it.next(); final K fromKey = it.next(); final K first = it.next(); final K second = it.next(); final int size = sm.size(); final 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)); final 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)); final 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()) { return; } // extra test as other tests get complex final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); it.next(); it.next(); final K fromKey = it.next(); final K first = it.next(); final K second = it.next(); final int size = sm.size(); final SortedMap sub = sm.tailMap(fromKey); final Set> set = sub.entrySet(); final Iterator> it2 = set.iterator(); it2.next(); final Map.Entry firstEntry = cloneMapEntry(it2.next()); final Map.Entry secondEntry = cloneMapEntry(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 final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); final K first = it.next(); final K fromKey = it.next(); final K second = it.next(); final K toKey = it.next(); final K third = it.next(); final V firstValue = sm.get(first); final V fromKeyValue = sm.get(fromKey); final V secondValue = sm.get(second); final V thirdValue = sm.get(third); final 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()) { return; } // extra test as other tests get complex final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); it.next(); final K fromKey = it.next(); final K first = it.next(); final K second = it.next(); final K toKey = it.next(); final V fromKeyValue = sm.get(fromKey); final V firstValue = sm.get(first); final V secondValue = sm.get(second); final V toKeyValue = sm.get(toKey); final SortedMap sub = sm.subMap(fromKey, toKey); final 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()) { return; } // extra test as other tests get complex final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); it.next(); it.next(); final K fromKey = it.next(); final K first = it.next(); final K second = it.next(); final K toKey = it.next(); final int size = sm.size(); final 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)); final V 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)); final V 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()) { return; } // extra test as other tests get complex final SortedBidiMap sm = makeFullMap(); final Iterator it = sm.keySet().iterator(); it.next(); it.next(); final K fromKey = it.next(); final K first = it.next(); final K second = it.next(); final K toKey = it.next(); final int size = sm.size(); final SortedMap sub = sm.subMap(fromKey, toKey); final Set> set = sub.entrySet(); assertEquals(3, set.size()); final Iterator> it2 = set.iterator(); it2.next(); final Map.Entry firstEntry = cloneMapEntry(it2.next()); final Map.Entry secondEntry = cloneMapEntry(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 AbstractSortedMapTest.TestHeadMap(this); } public BulkTest bulkTestTailMap() { return new AbstractSortedMapTest.TestTailMap(this); } public BulkTest bulkTestSubMap() { return new AbstractSortedMapTest.TestSubMap(this); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/TestUtils.java100664 6243 12243235516 27601 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import static org.junit.Assert.assertSame; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public final class TestUtils { private TestUtils() {} /** * Asserts that deserialization of the object returns the same object as the * one that was serialized. Object is first serialized, then deserialized * and finally check is performed to see if original and deserialized * object references are the same. *

* This method is especially good for testing singleton pattern on classes * that support serialization. * * @param msg the identifying message for the AssertionError. * @param o object that will be tested. * @see #assertSameAfterSerialization(Object) */ public static void assertSameAfterSerialization(final String msg, final Object o) { try { // write object to byte buffer final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(o); oos.close(); // read same object from byte buffer final InputStream is = new ByteArrayInputStream(baos.toByteArray()); final ObjectInputStream ois = new ObjectInputStream(is); final Object object = ois.readObject(); ois.close(); // assert that original object and deserialized objects are the same assertSame(msg, o, object); } catch (final IOException e) { // should never happen throw new RuntimeException(e); } catch (final ClassNotFoundException e) { // should never happen throw new RuntimeException(e); } } /** * Asserts that deserialization of the object returns the same object as the * one that was serialized. *

* Effect of method call is the same as: * assertSameAfterSerialization(null, o). * * @param o object that will be tested. * @see #assertSameAfterSerialization(String, Object) */ public static void assertSameAfterSerialization(final Object o) { assertSameAfterSerialization(null, o); } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/UnmodifiableListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/UnmodifiableListTest100664 13621 12243235516 32004 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * Extension of {@link AbstractListTest} for exercising the * {@link UnmodifiableList} implementation. * * @since 3.0 * @version $Id: UnmodifiableListTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class UnmodifiableListTest extends AbstractListTest { public UnmodifiableListTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public UnmodifiableList makeObject() { return new UnmodifiableList(new ArrayList()); } @Override public UnmodifiableList makeFullCollection() { final ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return new UnmodifiableList(list); } @Override public boolean isSetSupported() { return false; } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } //----------------------------------------------------------------------- protected UnmodifiableList list; protected ArrayList array; @SuppressWarnings("unchecked") protected void setupList() { list = makeFullCollection(); array = new ArrayList(); array.add((E) Integer.valueOf(1)); } /** * Verify that base list and sublists are not modifiable */ public void testUnmodifiable() { setupList(); verifyUnmodifiable(list); verifyUnmodifiable(list.subList(0, 2)); } public void testDecorateFactory() { final List list = makeObject(); assertSame(list, UnmodifiableList.unmodifiableList(list)); try { UnmodifiableList.unmodifiableList(null); fail(); } catch (final IllegalArgumentException ex) {} } @SuppressWarnings("unchecked") protected void verifyUnmodifiable(final List list) { try { list.add(0, (E) Integer.valueOf(0)); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { list.add((E) Integer.valueOf(0)); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { list.addAll(0, array); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { list.addAll(array); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { list.clear(); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { list.remove(0); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { list.remove(Integer.valueOf(0)); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { list.removeAll(array); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { list.retainAll(array); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { list.set(0, (E) Integer.valueOf(0)); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } } /** * Verify that iterator is not modifiable */ public void testUnmodifiableIterator() { setupList(); final Iterator iterator = list.iterator(); try { iterator.next(); iterator.remove(); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableList.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableList.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/CursorableLinkedListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/CursorableLinkedList100664 143513 12243235516 32022 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * Test class. * * @version $Id: CursorableLinkedListTest.java 1543270 2013-11-19 00:51:43Z ggregory $ */ public class CursorableLinkedListTest extends AbstractLinkedListTest { public CursorableLinkedListTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(CursorableLinkedListTest.class); } private CursorableLinkedList list; @Override public void setUp() { list = new CursorableLinkedList(); } @Override public CursorableLinkedList makeObject() { return new CursorableLinkedList(); } @SuppressWarnings("unchecked") public void testAdd() { assertEquals("[]",list.toString()); assertTrue(list.add((E) Integer.valueOf(1))); assertEquals("[1]",list.toString()); assertTrue(list.add((E) Integer.valueOf(2))); assertEquals("[1, 2]",list.toString()); assertTrue(list.add((E) Integer.valueOf(3))); assertEquals("[1, 2, 3]",list.toString()); assertTrue(list.addFirst((E) Integer.valueOf(0))); assertEquals("[0, 1, 2, 3]",list.toString()); assertTrue(list.addLast((E) Integer.valueOf(4))); assertEquals("[0, 1, 2, 3, 4]",list.toString()); list.add(0,(E) Integer.valueOf(-2)); assertEquals("[-2, 0, 1, 2, 3, 4]",list.toString()); list.add(1,(E) Integer.valueOf(-1)); assertEquals("[-2, -1, 0, 1, 2, 3, 4]",list.toString()); list.add(7,(E) Integer.valueOf(5)); assertEquals("[-2, -1, 0, 1, 2, 3, 4, 5]",list.toString()); final List list2 = new LinkedList(); list2.add((E) "A"); list2.add((E) "B"); list2.add((E) "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()); } @SuppressWarnings("unchecked") public void testClear() { assertEquals(0,list.size()); assertTrue(list.isEmpty()); list.clear(); assertEquals(0,list.size()); assertTrue(list.isEmpty()); list.add((E) "element"); assertEquals(1,list.size()); assertTrue(!list.isEmpty()); list.clear(); assertEquals(0,list.size()); assertTrue(list.isEmpty()); list.add((E) "element1"); list.add((E) "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((E) Integer.valueOf(i)); } assertEquals(1000, list.size()); assertTrue(!list.isEmpty()); list.clear(); assertEquals(0,list.size()); assertTrue(list.isEmpty()); } @SuppressWarnings("unchecked") public void testContains() { assertTrue(!list.contains("A")); assertTrue(list.add((E) "A")); assertTrue(list.contains("A")); assertTrue(list.add((E) "B")); assertTrue(list.contains("A")); assertTrue(list.addFirst((E) "a")); assertTrue(list.contains("A")); assertTrue(list.remove("a")); assertTrue(list.contains("A")); assertTrue(list.remove("A")); assertTrue(!list.contains("A")); } @SuppressWarnings("unchecked") public void testContainsAll() { assertTrue(list.containsAll(list)); final java.util.List list2 = new java.util.LinkedList(); assertTrue(list.containsAll(list2)); list2.add((E) "A"); assertTrue(!list.containsAll(list2)); list.add((E) "B"); list.add((E) "A"); assertTrue(list.containsAll(list2)); list2.add((E) "B"); assertTrue(list.containsAll(list2)); list2.add((E) "C"); assertTrue(!list.containsAll(list2)); list.add((E) "C"); assertTrue(list.containsAll(list2)); list2.add((E) "C"); assertTrue(list.containsAll(list2)); assertTrue(list.containsAll(list)); } @SuppressWarnings("unchecked") public void testCursorNavigation() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "5"); final 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(); } @SuppressWarnings("unchecked") public void testCursorSet() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "5"); final CursorableLinkedList.Cursor it = list.cursor(); assertEquals("1", it.next()); it.set((E) "a"); assertEquals("a", it.previous()); it.set((E) "A"); assertEquals("A", it.next()); assertEquals("2", it.next()); it.set((E) "B"); assertEquals("3", it.next()); assertEquals("4", it.next()); it.set((E) "D"); assertEquals("5", it.next()); it.set((E) "E"); assertEquals("[A, B, 3, D, E]", list.toString()); it.close(); } @SuppressWarnings("unchecked") public void testCursorRemove() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "5"); final CursorableLinkedList.Cursor it = list.cursor(); try { it.remove(); fail(); } catch (final 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 (final 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(); } @SuppressWarnings("unchecked") public void testCursorAdd() { final CursorableLinkedList.Cursor it = list.cursor(); it.add((E) "1"); assertEquals("[1]", list.toString()); it.add((E) "3"); assertEquals("[1, 3]", list.toString()); it.add((E) "5"); assertEquals("[1, 3, 5]", list.toString()); assertEquals("5", it.previous()); it.add((E) "4"); assertEquals("[1, 3, 4, 5]", list.toString()); assertEquals("4", it.previous()); assertEquals("3", it.previous()); it.add((E) "2"); assertEquals("[1, 2, 3, 4, 5]", list.toString()); it.close(); } @SuppressWarnings("unchecked") public void testCursorConcurrentModification() { // this test verifies that cursors remain valid when the list // is modified via other means. list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "5"); list.add((E) "7"); list.add((E) "9"); final CursorableLinkedList.Cursor c1 = list.cursor(); final CursorableLinkedList.Cursor c2 = list.cursor(); final 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((E) "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, (E) "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, (E) "8"); assertEquals("8", c1.next()); assertEquals("9", c1.next()); c1.add((E) "10"); assertEquals("7", c2.next()); assertEquals("8", c2.next()); assertEquals("9", c2.next()); assertEquals("10", c2.next()); try { c2.next(); fail(); } catch (final NoSuchElementException nse) { } try { li.next(); fail(); } catch (final ConcurrentModificationException cme) { } c1.close(); // not necessary c2.close(); // not necessary } @SuppressWarnings("unchecked") public void testCursorNextIndexMid() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "5"); final CursorableLinkedList.Cursor c1 = list.cursor(); final 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()); } @SuppressWarnings("unchecked") public void testCursorNextIndexFirst() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "5"); final 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()); } @SuppressWarnings("unchecked") public void testCursorNextIndexAddBefore() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "5"); final CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals(0, c1.nextIndex()); assertEquals("1", c1.next()); list.add(0, (E) "0"); assertEquals(2, c1.nextIndex()); assertEquals("2", c1.next()); } @SuppressWarnings("unchecked") public void testCursorNextIndexAddNext() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "5"); final CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals(0, c1.nextIndex()); list.add(0, (E) "0"); assertEquals(0, c1.nextIndex()); assertEquals("0", c1.next()); assertEquals(1, c1.nextIndex()); assertEquals("1", c1.next()); } @SuppressWarnings("unchecked") public void testCursorNextIndexAddAfter() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "5"); final CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals(0, c1.nextIndex()); list.add(1, (E) "0"); assertEquals(0, c1.nextIndex()); assertEquals("1", c1.next()); assertEquals(1, c1.nextIndex()); assertEquals("0", c1.next()); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextPreviousRemoveIndex1ByList() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final 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 (final IllegalStateException ex) {} } @SuppressWarnings("unchecked") public void testInternalState_CursorNextRemoveIndex1ByList() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final 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 (final IllegalStateException ex) {} } @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextRemoveIndex1ByList() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final 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 (final IllegalStateException ex) {} } @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextNextRemoveIndex1ByList() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); list.add((E) "D"); final 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 (final IllegalStateException ex) {} } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextPreviousRemoveByIterator() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final 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 (final IllegalStateException ex) {} } @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextRemoveByIterator() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final 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 (final IllegalStateException ex) {} } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextPreviousAddIndex1ByList() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); assertEquals("B", c1.previous()); list.add(1, (E) "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 (final IllegalStateException ex) {} } @SuppressWarnings("unchecked") public void testInternalState_CursorNextAddIndex1ByList() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); list.add(1, (E) "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 (final IllegalStateException ex) {} } @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextAddIndex1ByList() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); list.add(1, (E) "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 (final IllegalStateException ex) {} } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextPreviousAddByIterator() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); assertEquals("B", c1.previous()); c1.add((E) "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 (final IllegalStateException ex) {} } @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextAddByIterator() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); c1.add((E) "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 (final IllegalStateException ex) {} } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextRemoveByListSetByIterator() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final 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((E) "Z"); fail(); } catch (final IllegalStateException ex) {} } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextPreviousSetByIterator() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); assertEquals("B", c1.previous()); c1.set((E) "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 (final IllegalStateException ex) {} } @SuppressWarnings("unchecked") public void testInternalState_CursorNextNextSetByIterator() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final CursorableLinkedList.Cursor c1 = list.cursor(); assertEquals("A", c1.next()); assertEquals("B", c1.next()); c1.set((E) "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 (final IllegalStateException ex) {} } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testEqualsAndHashCode() { assertTrue(list.equals(list)); assertEquals(list.hashCode(),list.hashCode()); list.add((E) "A"); assertTrue(list.equals(list)); assertEquals(list.hashCode(),list.hashCode()); final CursorableLinkedList list2 = new CursorableLinkedList(); assertTrue(!list.equals(list2)); assertTrue(!list2.equals(list)); final 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((E) "A"); assertTrue(list.equals(list2)); assertTrue(list2.equals(list)); assertTrue(!list2.equals(list3)); assertTrue(!list3.equals(list2)); list3.add((E) "A"); assertTrue(list2.equals(list3)); assertTrue(list3.equals(list2)); assertEquals(list2.hashCode(),list3.hashCode()); list.add((E) "B"); assertTrue(list.equals(list)); assertTrue(!list.equals(list2)); assertTrue(!list2.equals(list)); assertTrue(!list.equals(list3)); assertTrue(!list3.equals(list)); list2.add((E) "B"); list3.add((E) "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((E) "C"); list2.add((E) "C"); list3.add((E) "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((E) "D"); list2.addFirst((E) "D"); assertTrue(list.equals(list)); assertTrue(!list.equals(list2)); assertTrue(!list2.equals(list)); } @SuppressWarnings("unchecked") public void testGet() { try { list.get(0); fail("shouldn't get here"); } catch(final IndexOutOfBoundsException e) { // expected } assertTrue(list.add((E) "A")); assertEquals("A",list.get(0)); assertTrue(list.add((E) "B")); assertEquals("A",list.get(0)); assertEquals("B",list.get(1)); try { list.get(-1); fail("shouldn't get here"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.get(2); fail("shouldn't get here"); } catch(final IndexOutOfBoundsException e) { // expected } } @SuppressWarnings("unchecked") public void testIndexOf() { assertEquals(-1,list.indexOf("A")); assertEquals(-1,list.lastIndexOf("A")); list.add((E) "A"); assertEquals(0,list.indexOf("A")); assertEquals(0,list.lastIndexOf("A")); assertEquals(-1,list.indexOf("B")); assertEquals(-1,list.lastIndexOf("B")); list.add((E) "B"); assertEquals(0,list.indexOf("A")); assertEquals(0,list.lastIndexOf("A")); assertEquals(1,list.indexOf("B")); assertEquals(1,list.lastIndexOf("B")); list.addFirst((E) "B"); assertEquals(1,list.indexOf("A")); assertEquals(1,list.lastIndexOf("A")); assertEquals(0,list.indexOf("B")); assertEquals(2,list.lastIndexOf("B")); } @SuppressWarnings("unchecked") public void testIsEmpty() { assertTrue(list.isEmpty()); list.add((E) "element"); assertTrue(!list.isEmpty()); list.remove("element"); assertTrue(list.isEmpty()); list.add((E) "element"); assertTrue(!list.isEmpty()); list.clear(); assertTrue(list.isEmpty()); } @SuppressWarnings("unchecked") public void testIterator() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "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()); } @SuppressWarnings("unchecked") public void testListIteratorNavigation() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "5"); final 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()); } @Override @SuppressWarnings("unchecked") public void testListIteratorSet() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "5"); final ListIterator it = list.listIterator(); assertEquals("1", it.next()); it.set((E) "a"); assertEquals("a", it.previous()); it.set((E) "A"); assertEquals("A", it.next()); assertEquals("2", it.next()); it.set((E) "B"); assertEquals("3", it.next()); assertEquals("4", it.next()); it.set((E) "D"); assertEquals("5", it.next()); it.set((E) "E"); assertEquals("[A, B, 3, D, E]", list.toString()); } @SuppressWarnings("unchecked") public void testListIteratorRemove() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "5"); final ListIterator it = list.listIterator(); try { it.remove(); } catch(final 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(final 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()); } @Override @SuppressWarnings("unchecked") public void testListIteratorAdd() { final ListIterator it = list.listIterator(); it.add((E) "1"); assertEquals("[1]", list.toString()); it.add((E) "3"); assertEquals("[1, 3]", list.toString()); it.add((E) "5"); assertEquals("[1, 3, 5]", list.toString()); assertEquals("5", it.previous()); it.add((E) "4"); assertEquals("[1, 3, 4, 5]", list.toString()); assertEquals("4", it.previous()); assertEquals("3", it.previous()); it.add((E) "2"); assertEquals("[1, 2, 3, 4, 5]", list.toString()); } @SuppressWarnings("unchecked") public void testRemoveAll() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "5"); final HashSet set = new HashSet(); set.add((E) "A"); set.add((E) "2"); set.add((E) "C"); set.add((E) "4"); set.add((E) "D"); assertTrue(list.removeAll(set)); assertEquals("[1, 3, 5]", list.toString()); assertTrue(!list.removeAll(set)); } @SuppressWarnings("unchecked") public void testRemoveByIndex() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "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()); } @SuppressWarnings("unchecked") public void testRemove() { list.add((E) "1"); list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "5"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "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()); } @SuppressWarnings("unchecked") public void testRetainAll() { list.add((E) "1"); list.add((E) "1"); list.add((E) "2"); list.add((E) "2"); list.add((E) "3"); list.add((E) "3"); list.add((E) "4"); list.add((E) "4"); list.add((E) "5"); list.add((E) "5"); final HashSet set = new HashSet(); set.add((E) "A"); set.add((E) "2"); set.add((E) "C"); set.add((E) "4"); set.add((E) "D"); assertTrue(list.retainAll(set)); assertEquals("[2, 2, 4, 4]", list.toString()); assertTrue(!list.retainAll(set)); } @SuppressWarnings("unchecked") public void testSet() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "5"); assertEquals("[1, 2, 3, 4, 5]", list.toString()); list.set(0, (E) "A"); assertEquals("[A, 2, 3, 4, 5]", list.toString()); list.set(1, (E) "B"); assertEquals("[A, B, 3, 4, 5]", list.toString()); list.set(2, (E) "C"); assertEquals("[A, B, C, 4, 5]", list.toString()); list.set(3, (E) "D"); assertEquals("[A, B, C, D, 5]", list.toString()); list.set(4, (E) "E"); assertEquals("[A, B, C, D, E]", list.toString()); } @SuppressWarnings("unchecked") public void testSubList() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); list.add((E) "D"); list.add((E) "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()); } @SuppressWarnings("unchecked") public void testSubListAddEnd() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); list.add((E) "D"); list.add((E) "E"); final List sublist = list.subList(5, 5); sublist.add((E) "F"); assertEquals("[A, B, C, D, E, F]", list.toString()); assertEquals("[F]", sublist.toString()); sublist.add((E) "G"); assertEquals("[A, B, C, D, E, F, G]", list.toString()); assertEquals("[F, G]", sublist.toString()); } @SuppressWarnings("unchecked") public void testSubListAddBegin() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); list.add((E) "D"); list.add((E) "E"); final List sublist = list.subList(0, 0); sublist.add((E) "a"); assertEquals("[a, A, B, C, D, E]", list.toString()); assertEquals("[a]", sublist.toString()); sublist.add((E) "b"); assertEquals("[a, b, A, B, C, D, E]", list.toString()); assertEquals("[a, b]", sublist.toString()); } @SuppressWarnings("unchecked") public void testSubListAddMiddle() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); list.add((E) "D"); list.add((E) "E"); final List sublist = list.subList(1, 3); sublist.add((E) "a"); assertEquals("[A, B, C, a, D, E]", list.toString()); assertEquals("[B, C, a]", sublist.toString()); sublist.add((E) "b"); assertEquals("[A, B, C, a, b, D, E]", list.toString()); assertEquals("[B, C, a, b]", sublist.toString()); } @SuppressWarnings("unchecked") public void testSubListRemove() { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); list.add((E) "D"); list.add((E) "E"); final 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()); } @SuppressWarnings("unchecked") public void testToArray() { list.add((E) "1"); list.add((E) "2"); list.add((E) "3"); list.add((E) "4"); list.add((E) "5"); final 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); final String[] elts2 = 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); final 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); final String[] elts4 = new String[3]; final String[] elts4b = 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); } @SuppressWarnings("unchecked") public void testSerialization() throws Exception { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); list.add((E) "D"); list.add((E) "E"); final java.io.ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream(); final java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(buf); out.writeObject(list); out.flush(); out.close(); final java.io.ByteArrayInputStream bufin = new java.io.ByteArrayInputStream(buf.toByteArray()); final java.io.ObjectInputStream in = new java.io.ObjectInputStream(bufin); final Object list2 = in.readObject(); assertTrue(list != list2); assertTrue(list2.equals(list)); assertTrue(list.equals(list2)); } @SuppressWarnings("unchecked") public void testSerializationWithOpenCursor() throws Exception { list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); list.add((E) "D"); list.add((E) "E"); final java.io.ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream(); final java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(buf); out.writeObject(list); out.flush(); out.close(); final java.io.ByteArrayInputStream bufin = new java.io.ByteArrayInputStream(buf.toByteArray()); final java.io.ObjectInputStream in = new java.io.ObjectInputStream(bufin); final Object list2 = in.readObject(); assertTrue(list != list2); assertTrue(list2.equals(list)); assertTrue(list.equals(list2)); } @SuppressWarnings("unchecked") 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((E) Integer.valueOf(i)); } final java.io.ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream(); final java.io.ObjectOutputStream out = new java.io.ObjectOutputStream(buf); out.writeObject(list); out.flush(); out.close(); final java.io.ByteArrayInputStream bufin = new java.io.ByteArrayInputStream(buf.toByteArray()); final java.io.ObjectInputStream in = new java.io.ObjectInputStream(bufin); final 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 */ @Override public String[] ignoredTests() { final ArrayList list = new ArrayList(); final String prefix = "CursorableLinkedListTest"; final String bulk = ".bulkTestSubList"; final String[] ignored = new String[] { ".testEmptyListSerialization", ".testFullListSerialization", ".testEmptyListCompatibility", ".testFullListCompatibility", ".testSimpleSerialization", ".testCanonicalEmptyCollectionExists", ".testCanonicalFullCollectionExists", ".testSerializeDeserializeThenCompare" }; for (final String element : ignored) { list.add(prefix + bulk + element); list.add(prefix + bulk + bulk + element); } return list.toArray(new String[0]); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CursorableLinkedList.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CursorableLinkedList.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/TransformedListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/TransformedListTest.100664 12421 12243235516 31745 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.collection.TransformedCollectionTest; /** * Extension of {@link AbstractListTest} for exercising the {@link TransformedList} * implementation. * * @since 3.0 * @version $Id: TransformedListTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class TransformedListTest extends AbstractListTest { public TransformedListTest(final String testName) { super(testName); } @Override public List makeConfirmedCollection() { return new ArrayList(); } @Override public List makeConfirmedFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } @Override @SuppressWarnings("unchecked") public List makeObject() { return TransformedList.transformingList(new ArrayList(), (Transformer) TransformedCollectionTest.NOOP_TRANSFORMER); } @Override @SuppressWarnings("unchecked") public List makeFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return TransformedList.transformingList(list, (Transformer) TransformedCollectionTest.NOOP_TRANSFORMER); } @SuppressWarnings("unchecked") public void testTransformedList() { final List list = TransformedList.transformingList(new ArrayList(), (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, list.size()); final E[] els = (E[]) 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(Integer.valueOf((String) els[i]))); assertEquals(false, list.contains(els[i])); } assertEquals(false, list.remove(els[0])); assertEquals(true, list.remove(Integer.valueOf((String) els[0]))); list.clear(); for (int i = 0; i < els.length; i++) { list.add(0, els[i]); assertEquals(i + 1, list.size()); assertEquals(Integer.valueOf((String) els[i]), list.get(0)); } list.set(0, (E) "22"); assertEquals(Integer.valueOf(22), list.get(0)); final ListIterator it = list.listIterator(); it.next(); it.set((E) "33"); assertEquals(Integer.valueOf(33), list.get(0)); it.add((E) "44"); assertEquals(Integer.valueOf(44), list.get(1)); final List adds = new ArrayList(); adds.add((E) "1"); adds.add((E) "2"); list.clear(); list.addAll(adds); assertEquals(Integer.valueOf(1), list.get(0)); assertEquals(Integer.valueOf(2), list.get(1)); adds.clear(); adds.add((E) "3"); list.addAll(1, adds); assertEquals(Integer.valueOf(1), list.get(0)); assertEquals(Integer.valueOf(3), list.get(1)); assertEquals(Integer.valueOf(2), list.get(2)); } public void testTransformedList_decorateTransform() { final List originalList = new ArrayList(); final Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; for (final Object el : els) { originalList.add(el); } final List list = TransformedList.transformedList(originalList, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(els.length, list.size()); for (final Object el : els) { assertEquals(true, list.contains(Integer.valueOf((String) el))); assertEquals(false, list.contains(el)); } assertEquals(false, list.remove(els[0])); assertEquals(true, list.remove(Integer.valueOf((String) els[0]))); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/TransformedList.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/TransformedList.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/PredicatedListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/PredicatedListTest.j100664 12147 12243235516 31704 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.TruePredicate; /** * Extension of {@link AbstractListTest} for exercising the * {@link PredicatedList} implementation. * * @since 3.0 * @version $Id: PredicatedListTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class PredicatedListTest extends AbstractListTest { public PredicatedListTest(final String testName) { super(testName); } //------------------------------------------------------------------- protected Predicate truePredicate = TruePredicate.truePredicate(); protected List decorateList(final List list, final Predicate predicate) { return PredicatedList.predicatedList(list, predicate); } @Override public List makeObject() { return decorateList(new ArrayList(), truePredicate); } @Override @SuppressWarnings("unchecked") public E[] getFullElements() { return (E[]) new Object[] { "1", "3", "5", "7", "2", "4", "6" }; } //-------------------------------------------------------------------- protected Predicate testPredicate = new Predicate() { public boolean evaluate(final E o) { return o instanceof String; } }; public List makeTestList() { return decorateList(new ArrayList(), testPredicate); } @SuppressWarnings("unchecked") public void testIllegalAdd() { final List list = makeTestList(); final Integer i = Integer.valueOf(3); try { list.add((E) i); fail("Integer should fail string predicate."); } catch (final IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !list.contains(i)); } @SuppressWarnings("unchecked") public void testIllegalAddAll() { final List list = makeTestList(); final List elements = new ArrayList(); elements.add((E) "one"); elements.add((E) "two"); elements.add((E) Integer.valueOf(3)); elements.add((E) "four"); try { list.addAll(0, elements); fail("Integer should fail string predicate."); } catch (final 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(Integer.valueOf(3))); assertTrue("List shouldn't contain illegal element", !list.contains("four")); } @SuppressWarnings("unchecked") public void testIllegalSet() { final List list = makeTestList(); try { list.set(0, (E) Integer.valueOf(3)); fail("Integer should fail string predicate."); } catch (final IllegalArgumentException e) { // expected } } @SuppressWarnings("unchecked") public void testLegalAddAll() { final List list = makeTestList(); list.add((E) "zero"); final List elements = new ArrayList(); elements.add((E) "one"); elements.add((E) "two"); elements.add((E) "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")); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/PredicatedList.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/PredicatedList.fullCollection.version4.obj"); // } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/TreeListTest.java100664 25442 12243235516 31231 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * JUnit tests * * @since 3.1 * @version $Id: TreeListTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class TreeListTest extends AbstractListTest { public TreeListTest(final 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()); // System.out.print("\n NodeCachingLinkedList = "); // benchmark(new NodeCachingLinkedList()); // } public static Test suite() { return BulkTest.makeSuite(TreeListTest.class); } public static void benchmark(final List l) { long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { l.add(Integer.valueOf(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++) { final 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++) { final int j = (int) (Math.random() * 100000); l.add(j, Integer.valueOf(-j)); } System.out.print(System.currentTimeMillis() - start + ";"); start = System.currentTimeMillis(); for (int i = 0; i < 50000; i++) { final 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++) { final int j = (int) (Math.random() * 100000); l.indexOf(Integer.valueOf(j)); } System.out.print(System.currentTimeMillis() - start + ";"); start = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { final int j = (int) (Math.random() * 100000); l.remove(j); } System.out.print(System.currentTimeMillis() - start + ";"); } //----------------------------------------------------------------------- @Override public TreeList makeObject() { return new TreeList(); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testAddMultiple() { final List l = makeObject(); l.add((E) "hugo"); l.add((E) "erna"); l.add((E) "daniel"); l.add((E) "andres"); l.add((E) "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)); } @SuppressWarnings("unchecked") public void testRemove() { final List l = makeObject(); l.add((E) "hugo"); l.add((E) "erna"); l.add((E) "daniel"); l.add((E) "andres"); l.add((E) "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++)); } @SuppressWarnings("unchecked") public void testInsertBefore() { final List l = makeObject(); l.add((E) "erna"); l.add(0, (E) "hugo"); assertEquals("hugo", l.get(0)); assertEquals("erna", l.get(1)); } @SuppressWarnings("unchecked") public void testIndexOf() { final List l = makeObject(); l.add((E) "0"); l.add((E) "1"); l.add((E) "2"); l.add((E) "3"); l.add((E) "4"); l.add((E) "5"); l.add((E) "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, (E) "0"); assertEquals(0, l.indexOf("0")); l.set(3, (E) "3"); assertEquals(3, l.indexOf("3")); l.set(2, (E) "3"); assertEquals(2, l.indexOf("3")); l.set(1, (E) "3"); assertEquals(1, l.indexOf("3")); l.set(0, (E) "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() { final Object objectToRemove = Integer.valueOf(3); final List treelist = new TreeList(); treelist.add(Integer.valueOf(0)); treelist.add(Integer.valueOf(1)); treelist.add(Integer.valueOf(2)); treelist.add(Integer.valueOf(3)); treelist.add(Integer.valueOf(4)); // this cause inconsistence of ListIterator() treelist.remove(objectToRemove); final ListIterator li = treelist.listIterator(); assertEquals(Integer.valueOf(0), li.next()); assertEquals(Integer.valueOf(0), li.previous()); assertEquals(Integer.valueOf(0), li.next()); assertEquals(Integer.valueOf(1), li.next()); // this caused error in bug 35258 assertEquals(Integer.valueOf(1), li.previous()); assertEquals(Integer.valueOf(1), li.next()); assertEquals(Integer.valueOf(2), li.next()); assertEquals(Integer.valueOf(2), li.previous()); assertEquals(Integer.valueOf(2), li.next()); assertEquals(Integer.valueOf(4), li.next()); assertEquals(Integer.valueOf(4), li.previous()); assertEquals(Integer.valueOf(4), li.next()); assertEquals(false, li.hasNext()); } public void testBugCollections447() { final List treeList = new TreeList(); treeList.add("A"); treeList.add("B"); treeList.add("C"); treeList.add("D"); final ListIterator li = treeList.listIterator(); assertEquals("A", li.next()); assertEquals("B", li.next()); assertEquals("B", li.previous()); li.remove(); // Deletes "B" // previous() after remove() should move to // the element before the one just removed assertEquals("A", li.previous()); } @SuppressWarnings("boxing") // OK in test code public void testIterationOrder() { // COLLECTIONS-433: // ensure that the iteration order of elements is correct // when initializing the TreeList with another collection for (int size = 1; size < 1000; size++) { List other = new ArrayList(size); for (int i = 0; i < size; i++) { other.add(i); } TreeList l = new TreeList(other); ListIterator it = l.listIterator(); int i = 0; while (it.hasNext()) { Integer val = it.next(); assertEquals(i++, val.intValue()); } while (it.hasPrevious()) { Integer val = it.previous(); assertEquals(--i, val.intValue()); } } } @SuppressWarnings("boxing") // OK in test code public void testIterationOrderAfterAddAll() { // COLLECTIONS-433: // ensure that the iteration order of elements is correct // when calling addAll on the TreeList // to simulate different cases in addAll, do different runs where // the number of elements already in the list and being added by addAll differ int size = 1000; for (int i = 0; i < 100; i++) { List other = new ArrayList(size); for (int j = i; j < size; j++) { other.add(j); } TreeList l = new TreeList(); for (int j = 0; j < i; j++) { l.add(j); } l.addAll(other); ListIterator it = l.listIterator(); int cnt = 0; while (it.hasNext()) { Integer val = it.next(); assertEquals(cnt++, val.intValue()); } while (it.hasPrevious()) { Integer val = it.previous(); assertEquals(--cnt, val.intValue()); } } } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/FixedSizeListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/FixedSizeListTest.ja100664 4345 12243235516 31654 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Extension of {@link AbstractListTest} for exercising the {@link FixedSizeList} * implementation. * * @since 3.0 * @version $Id: FixedSizeListTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class FixedSizeListTest extends AbstractListTest { public FixedSizeListTest(final String testName) { super(testName); } @Override public List makeObject() { return FixedSizeList.fixedSizeList(new ArrayList()); } @Override public List makeFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return FixedSizeList.fixedSizeList(list); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/FixedSizeList.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/FixedSizeList.fullCollection.version4.obj"); // } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/GrowthListTest.java100664 12674 12243235516 31607 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; /** * Extension of {@link AbstractListTest} for exercising the {@link GrowthList}. * * @since 3.2 * @version $Id: GrowthListTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class GrowthListTest extends AbstractListTest { public GrowthListTest(final String testName) { super(testName); } @Override public List makeObject() { return new GrowthList(); } @Override public List makeFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return GrowthList.growthList(list); } //----------------------------------------------------------------------- public void testGrowthAdd() { final Integer one = Integer.valueOf(1); final 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() { final Integer one = Integer.valueOf(1); final Integer two = Integer.valueOf(2); final Collection coll = new ArrayList(); coll.add(one); coll.add(two); final 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() { final Integer one = Integer.valueOf(1); final 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() { final Integer one = Integer.valueOf(1); final GrowthList grower = new GrowthList(); assertEquals(0, grower.size()); grower.set(0, one); assertEquals(1, grower.size()); assertEquals(one, grower.get(0)); } //----------------------------------------------------------------------- /** * Override. */ @Override public void testListAddByIndexBoundsChecking() { List list; final E element = getOtherElements()[0]; try { list = makeObject(); list.add(-1, element); fail("List.add should throw IndexOutOfBoundsException [-1]"); } catch (final IndexOutOfBoundsException e) { // expected } } /** * Override. */ @Override public void testListAddByIndexBoundsChecking2() { List list; final E element = getOtherElements()[0]; try { list = makeFullCollection(); list.add(-1, element); fail("List.add should throw IndexOutOfBoundsException [-1]"); } catch (final IndexOutOfBoundsException e) { // expected } } /** * Override. */ @Override public void testListSetByIndexBoundsChecking() { final List list = makeObject(); final E element = getOtherElements()[0]; try { list.set(-1, element); fail("List.set should throw IndexOutOfBoundsException [-1]"); } catch (final IndexOutOfBoundsException e) { // expected } } /** * Override. */ @Override public void testListSetByIndexBoundsChecking2() { final List list = makeFullCollection(); final E element = getOtherElements()[0]; try { list.set(-1, element); fail("List.set should throw IndexOutOfBoundsException [-1]"); } catch(final IndexOutOfBoundsException e) { // expected } } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/GrowthList.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/GrowthList.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/AbstractLinkedListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/AbstractLinkedListTe100664 15243 12243235516 31733 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.Arrays; /** * Test case for {@link AbstractLinkedList}. * * @version $Id: AbstractLinkedListTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractLinkedListTest extends AbstractListTest { public AbstractLinkedListTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testRemoveFirst() { resetEmpty(); final AbstractLinkedList list = getCollection(); if (!isRemoveSupported()) { try { list.removeFirst(); } catch (final UnsupportedOperationException ex) {} } list.addAll(Arrays.asList((E[]) new String[] { "value1", "value2" })); assertEquals("value1", list.removeFirst()); checkNodes(); list.addLast((E) "value3"); checkNodes(); assertEquals("value2", list.removeFirst()); assertEquals("value3", list.removeFirst()); checkNodes(); list.addLast((E) "value4"); checkNodes(); assertEquals("value4", list.removeFirst()); checkNodes(); } @SuppressWarnings("unchecked") public void testRemoveLast() { resetEmpty(); final AbstractLinkedList list = getCollection(); if (!isRemoveSupported()) { try { list.removeLast(); } catch (final UnsupportedOperationException ex) {} } list.addAll(Arrays.asList((E[]) new String[] { "value1", "value2" })); assertEquals("value2", list.removeLast()); list.addFirst((E) "value3"); checkNodes(); assertEquals("value1", list.removeLast()); assertEquals("value3", list.removeLast()); list.addFirst((E) "value4"); checkNodes(); assertEquals("value4", list.removeFirst()); } @SuppressWarnings("unchecked") public void testAddNodeAfter() { resetEmpty(); final AbstractLinkedList list = getCollection(); if (!isAddSupported()) { try { list.addFirst(null); } catch (final UnsupportedOperationException ex) {} } list.addFirst((E) "value1"); list.addNodeAfter(list.getNode(0, false), (E) "value2"); assertEquals("value1", list.getFirst()); assertEquals("value2", list.getLast()); list.removeFirst(); checkNodes(); list.addNodeAfter(list.getNode(0, false), (E) "value3"); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value3", list.getLast()); list.addNodeAfter(list.getNode(0, false), (E) "value4"); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value3", list.getLast()); assertEquals("value4", list.get(1)); list.addNodeAfter(list.getNode(2, false), (E) "value5"); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value4", list.get(1)); assertEquals("value3", list.get(2)); assertEquals("value5", list.getLast()); } @SuppressWarnings("unchecked") public void testRemoveNode() { resetEmpty(); if (!isAddSupported() || !isRemoveSupported()) { return; } final AbstractLinkedList list = getCollection(); list.addAll(Arrays.asList((E[]) new String[] { "value1", "value2" })); list.removeNode(list.getNode(0, false)); checkNodes(); assertEquals("value2", list.getFirst()); assertEquals("value2", list.getLast()); list.addFirst((E) "value1"); list.addFirst((E) "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(); } @SuppressWarnings("unchecked") public void testGetNode() { resetEmpty(); final AbstractLinkedList list = getCollection(); // get marker assertEquals(list.getNode(0, true).previous, list.getNode(0, true).next); try { list.getNode(0, false); fail("Expecting IndexOutOfBoundsException."); } catch (final IndexOutOfBoundsException ex) { // expected } list.addAll( Arrays.asList((E[]) new String[]{"value1", "value2"})); checkNodes(); list.addFirst((E) "value0"); checkNodes(); list.removeNode(list.getNode(1, false)); checkNodes(); try { list.getNode(2, false); fail("Expecting IndexOutOfBoundsException."); } catch (final IndexOutOfBoundsException ex) { // expected } try { list.getNode(-1, false); fail("Expecting IndexOutOfBoundsException."); } catch (final IndexOutOfBoundsException ex) { // expected } try { list.getNode(3, true); fail("Expecting IndexOutOfBoundsException."); } catch (final IndexOutOfBoundsException ex) { // expected } } protected void checkNodes() { final AbstractLinkedList list = getCollection(); 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)); } } } /** * {@inheritDoc} */ @Override public AbstractLinkedList getCollection() { return (AbstractLinkedList) super.getCollection(); } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/AbstractListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/AbstractListTest.jav100664 126545 12243235516 31762 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.BulkTest; import org.apache.commons.collections4.collection.AbstractCollectionTest; import org.apache.commons.collections4.iterators.AbstractListIteratorTest; /** * Abstract test class for {@link java.util.List} methods and contracts. *

* To use, simply extend this class, and implement * the {@link #makeObject} 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 AbstractCollectionTest. * * @version $Id: AbstractListTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractListTest extends AbstractCollectionTest { /** * JUnit constructor. * * @param testName the test class name */ public AbstractListTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * Returns true if the collections produced by * {@link #makeObject()} 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. */ @Override @SuppressWarnings("unchecked") public void verify() { super.verify(); final List list1 = getCollection(); final List list2 = getConfirmed(); 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; final Iterator iterator1 = list1.iterator(); final Iterator iterator2 = list2.iterator(); final E[] array = (E[]) list1.toArray(); while (iterator2.hasNext()) { assertTrue("List iterator should have next", iterator1.hasNext()); final 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. */ @Override public boolean isEqualsCheckable() { return true; } /** * Returns an empty {@link ArrayList}. */ @Override public Collection makeConfirmedCollection() { final ArrayList list = new ArrayList(); return list; } /** * Returns a full {@link ArrayList}. */ @Override public Collection makeConfirmedFullCollection() { final ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } /** * Returns {@link #makeObject()}. * * @return an empty list to be used for testing */ @Override public abstract List makeObject(); /** * {@inheritDoc} */ @Override public List makeFullCollection() { // only works if list supports optional "addAll(Collection)" final List list = makeObject(); list.addAll(Arrays.asList(getFullElements())); return list; } //----------------------------------------------------------------------- /** * Returns the {@link #collection} field cast to a {@link List}. * * @return the collection field as a List */ @Override public List getCollection() { return (List) super.getCollection(); } /** * Returns the {@link #confirmed} field cast to a {@link List}. * * @return the confirmed field as a List */ @Override public List getConfirmed() { return (List) super.getConfirmed(); } //----------------------------------------------------------------------- /** * Tests bounds checking for {@link List#add(int, Object)} on an * empty list. */ public void testListAddByIndexBoundsChecking() { if (!isAddSupported()) { return; } List list; final E element = getOtherElements()[0]; try { list = makeObject(); list.add(Integer.MIN_VALUE, element); fail("List.add should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list = makeObject(); list.add(-1, element); fail("List.add should throw IndexOutOfBoundsException [-1]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list = makeObject(); list.add(1, element); fail("List.add should throw IndexOutOfBoundsException [1]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list = makeObject(); list.add(Integer.MAX_VALUE, element); fail("List.add should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch (final IndexOutOfBoundsException e) { // expected } } /** * Tests bounds checking for {@link List#add(int, Object)} on a * full list. */ public void testListAddByIndexBoundsChecking2() { if (!isAddSupported()) { return; } List list; final E element = getOtherElements()[0]; try { list = makeFullCollection(); list.add(Integer.MIN_VALUE, element); fail("List.add should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list = makeFullCollection(); list.add(-1, element); fail("List.add should throw IndexOutOfBoundsException [-1]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list = makeFullCollection(); list.add(list.size() + 1, element); fail("List.add should throw IndexOutOfBoundsException [size + 1]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list = makeFullCollection(); list.add(Integer.MAX_VALUE, element); fail("List.add should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch (final IndexOutOfBoundsException e) { // expected } } /** * Tests {@link List#add(int,Object)}. */ public void testListAddByIndex() { if (!isAddSupported()) { return; } final E element = getOtherElements()[0]; final int max = getFullElements().length; for (int i = 0; i <= max; i++) { resetFull(); getCollection().add(i, element); getConfirmed().add(i, element); verify(); } } /** * Tests {@link List#equals(Object)}. */ public void testListEquals() { resetEmpty(); List list = getCollection(); assertEquals("Empty lists should be equal", true, list.equals(getConfirmed())); 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 = getCollection(); assertEquals("Full lists should be equal", true, list.equals(getConfirmed())); verify(); assertEquals("Full list should equal self", true, list.equals(list)); verify(); list2 = makeObject(); 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())); getConfirmed().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 = getCollection(); assertEquals("List shouldn't equal String", false, list.equals("")); verify(); final List listForC = Arrays.asList(getFullElements()); final Collection c = new AbstractCollection() { @Override public int size() { return listForC.size(); } @Override 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 = getCollection().hashCode(); int hash2 = getConfirmed().hashCode(); assertEquals("Empty lists should have equal hashCodes", hash1, hash2); verify(); resetFull(); hash1 = getCollection().hashCode(); hash2 = getConfirmed().hashCode(); assertEquals("Full lists should have equal hashCodes", hash1, hash2); verify(); } /** * Tests {@link List#get(int)}. */ public void testListGetByIndex() { resetFull(); final List list = getCollection(); final E[] 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() { final List list = makeObject(); try { list.get(Integer.MIN_VALUE); fail("List.get should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.get(-1); fail("List.get should throw IndexOutOfBoundsException [-1]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.get(0); fail("List.get should throw IndexOutOfBoundsException [0]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.get(1); fail("List.get should throw IndexOutOfBoundsException [1]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.get(Integer.MAX_VALUE); fail("List.get should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch (final IndexOutOfBoundsException e) { // expected } } /** * Tests bounds checking for {@link List#get(int)} on a * full list. */ public void testListGetByIndexBoundsChecking2() { final List list = makeFullCollection(); try { list.get(Integer.MIN_VALUE); fail("List.get should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.get(-1); fail("List.get should throw IndexOutOfBoundsException [-1]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.get(getFullElements().length); fail("List.get should throw IndexOutOfBoundsException [size]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.get(Integer.MAX_VALUE); fail("List.get should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch (final IndexOutOfBoundsException e) { // expected } } /** * Tests {@link List#indexOf}. */ public void testListIndexOf() { resetFull(); final List list1 = getCollection(); final List list2 = getConfirmed(); for (E element : list2) { assertEquals("indexOf should return correct result", list1.indexOf(element), list2.indexOf(element)); verify(); } final E[] other = getOtherElements(); for (final E element : other) { assertEquals("indexOf should return -1 for nonexistent element", -1, list1.indexOf(element)); verify(); } } /** * Tests {@link List#lastIndexOf}. */ public void testListLastIndexOf() { resetFull(); final List list1 = getCollection(); final List list2 = getConfirmed(); final Iterator iterator = list2.iterator(); while (iterator.hasNext()) { final E element = iterator.next(); assertEquals("lastIndexOf should return correct result", list1.lastIndexOf(element), list2.lastIndexOf(element)); verify(); } final E[] other = getOtherElements(); for (final E element : other) { assertEquals("lastIndexOf should return -1 for nonexistent " + "element", -1, list1.lastIndexOf(element)); verify(); } } /** * Tests bounds checking for {@link List#set(int,Object)} on an * empty list. */ public void testListSetByIndexBoundsChecking() { if (!isSetSupported()) { return; } final List list = makeObject(); final E element = getOtherElements()[0]; try { list.set(Integer.MIN_VALUE, element); fail("List.set should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.set(-1, element); fail("List.set should throw IndexOutOfBoundsException [-1]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.set(0, element); fail("List.set should throw IndexOutOfBoundsException [0]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.set(1, element); fail("List.set should throw IndexOutOfBoundsException [1]"); } catch (final IndexOutOfBoundsException e) { // expected } try { list.set(Integer.MAX_VALUE, element); fail("List.set should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch (final IndexOutOfBoundsException e) { // expected } } /** * Tests bounds checking for {@link List#set(int,Object)} on a * full list. */ public void testListSetByIndexBoundsChecking2() { if (!isSetSupported()) { return; } final List list = makeFullCollection(); final E element = getOtherElements()[0]; try { list.set(Integer.MIN_VALUE, element); fail("List.set should throw IndexOutOfBoundsException " + "[Integer.MIN_VALUE]"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.set(-1, element); fail("List.set should throw IndexOutOfBoundsException [-1]"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.set(getFullElements().length, element); fail("List.set should throw IndexOutOfBoundsException [size]"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.set(Integer.MAX_VALUE, element); fail("List.set should throw IndexOutOfBoundsException " + "[Integer.MAX_VALUE]"); } catch(final IndexOutOfBoundsException e) { // expected } } /** * Test {@link List#set(int,Object)}. */ public void testListSetByIndex() { if (!isSetSupported()) { return; } resetFull(); final E[] elements = getFullElements(); final E[] other = getOtherElements(); for (int i = 0; i < elements.length; i++) { final E n = other[i % other.length]; final E v = getCollection().set(i, n); assertEquals("Set should return correct element", elements[i], v); getConfirmed().set(i, n); verify(); } } /** * If {@link #isSetSupported()} returns false, tests that set operation * raises UnsupportedOperationException. */ public void testUnsupportedSet() { if (isSetSupported()) { return; } resetFull(); try { getCollection().set(0, getFullElements()[0]); fail("Emtpy collection should not support set."); } catch (final 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; } final List list = makeObject(); try { list.remove(Integer.MIN_VALUE); fail("List.remove should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.remove(-1); fail("List.remove should throw IndexOutOfBoundsException [-1]"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.remove(0); fail("List.remove should throw IndexOutOfBoundsException [0]"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.remove(1); fail("List.remove should throw IndexOutOfBoundsException [1]"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.remove(Integer.MAX_VALUE); fail("List.remove should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); } catch(final IndexOutOfBoundsException e) { // expected } } /** * Tests bounds checking for {@link List#remove(int)} on a * full list. */ public void testListRemoveByIndexBoundsChecking2() { if (!isRemoveSupported()) { return; } final List list = makeFullCollection(); try { list.remove(Integer.MIN_VALUE); fail("List.remove should throw IndexOutOfBoundsException " + "[Integer.MIN_VALUE]"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.remove(-1); fail("List.remove should throw IndexOutOfBoundsException [-1]"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.remove(getFullElements().length); fail("List.remove should throw IndexOutOfBoundsException [size]"); } catch(final IndexOutOfBoundsException e) { // expected } try { list.remove(Integer.MAX_VALUE); fail("List.remove should throw IndexOutOfBoundsException " + "[Integer.MAX_VALUE]"); } catch(final IndexOutOfBoundsException e) { // expected } } /** * Tests {@link List#remove(int)}. */ public void testListRemoveByIndex() { if (!isRemoveSupported()) { return; } final int max = getFullElements().length; for (int i = 0; i < max; i++) { resetFull(); final E o1 = getCollection().remove(i); final E o2 = getConfirmed().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(getCollection().listIterator(), 0); backwardTest(getCollection().listIterator(), 0); } /** * Tests the read-only bits of {@link List#listIterator(int)}. */ public void testListListIteratorByIndex() { resetFull(); try { getCollection().listIterator(-1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); try { getCollection().listIterator(getCollection().size() + 1); } catch (final IndexOutOfBoundsException ex) {} resetFull(); for (int i = 0; i <= getConfirmed().size(); i++) { forwardTest(getCollection().listIterator(i), i); backwardTest(getCollection().listIterator(i), i); } resetFull(); for (int i = 0; i <= getConfirmed().size(); i++) { backwardTest(getCollection().listIterator(i), i); } } //----------------------------------------------------------------------- /** * Tests remove on list iterator is correct. */ public void testListListIteratorPreviousRemoveNext() { if (!isRemoveSupported()) { return; } resetFull(); if (getCollection().size() < 4) { return; } final ListIterator it = getCollection().listIterator(); final E zero = it.next(); final E one = it.next(); final E two = it.next(); final E two2 = it.previous(); final E one2 = it.previous(); assertEquals(one, one2); assertEquals(two, two2); assertEquals(zero, getCollection().get(0)); assertEquals(one, getCollection().get(1)); assertEquals(two, getCollection().get(2)); it.remove(); // removed element at index 1 (one) assertEquals(zero, getCollection().get(0)); assertEquals(two, getCollection().get(1)); final E two3 = it.next(); // do next after remove assertEquals(two, two3); assertEquals(getCollection().size() > 2, it.hasNext()); assertEquals(true, it.hasPrevious()); } /** * Tests remove on list iterator is correct. */ public void testListListIteratorPreviousRemovePrevious() { if (!isRemoveSupported()) { return; } resetFull(); if (getCollection().size() < 4) { return; } final ListIterator it = getCollection().listIterator(); final E zero = it.next(); final E one = it.next(); final E two = it.next(); final E two2 = it.previous(); final E one2 = it.previous(); assertEquals(one, one2); assertEquals(two, two2); assertEquals(zero, getCollection().get(0)); assertEquals(one, getCollection().get(1)); assertEquals(two, getCollection().get(2)); it.remove(); // removed element at index 1 (one) assertEquals(zero, getCollection().get(0)); assertEquals(two, getCollection().get(1)); final E zero3 = it.previous(); // do previous after remove assertEquals(zero, zero3); assertEquals(false, it.hasPrevious()); assertEquals(getCollection().size() > 2, it.hasNext()); } /** * Tests remove on list iterator is correct. */ public void testListListIteratorNextRemoveNext() { if (!isRemoveSupported()) { return; } resetFull(); if (getCollection().size() < 4) { return; } final ListIterator it = getCollection().listIterator(); final E zero = it.next(); final E one = it.next(); final E two = it.next(); assertEquals(zero, getCollection().get(0)); assertEquals(one, getCollection().get(1)); assertEquals(two, getCollection().get(2)); final E three = getCollection().get(3); it.remove(); // removed element at index 2 (two) assertEquals(zero, getCollection().get(0)); assertEquals(one, getCollection().get(1)); final E three2 = it.next(); // do next after remove assertEquals(three, three2); assertEquals(getCollection().size() > 3, it.hasNext()); assertEquals(true, it.hasPrevious()); } /** * Tests remove on list iterator is correct. */ public void testListListIteratorNextRemovePrevious() { if (!isRemoveSupported()) { return; } resetFull(); if (getCollection().size() < 4) { return; } final ListIterator it = getCollection().listIterator(); final E zero = it.next(); final E one = it.next(); final E two = it.next(); assertEquals(zero, getCollection().get(0)); assertEquals(one, getCollection().get(1)); assertEquals(two, getCollection().get(2)); it.remove(); // removed element at index 2 (two) assertEquals(zero, getCollection().get(0)); assertEquals(one, getCollection().get(1)); final E 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(final ListIterator iter, int i) { final List list = getCollection(); final int max = getFullElements().length; while (i < max) { assertTrue("Iterator should have next", iter.hasNext()); assertEquals("Iterator.nextIndex should work", i, iter.nextIndex()); assertEquals("Iterator.previousIndex should work", i - 1, iter.previousIndex()); final 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", max, iter.nextIndex()); assertEquals("previousIndex should be size - 1", max - 1, iter.previousIndex()); try { iter.next(); fail("Exhausted iterator should raise NoSuchElement"); } catch (final 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(final ListIterator iter, int i) { final List list = getCollection(); while (i > 0) { assertTrue("Iterator should have previous, i:" + i, iter.hasPrevious()); assertEquals("Iterator.nextIndex should work, i:" + i, i, iter.nextIndex()); assertEquals("Iterator.previousIndex should work, i:" + i, i - 1, iter.previousIndex()); final E o = iter.previous(); assertEquals("Iterator returned correct element", list.get(i - 1), o); i--; } assertTrue("Iterator shouldn't have previous", !iter.hasPrevious()); final int nextIndex = iter.nextIndex(); assertEquals("nextIndex should be 0", 0, nextIndex); final int prevIndex = iter.previousIndex(); assertEquals("previousIndex should be -1", -1, prevIndex); try { iter.previous(); fail("Exhausted iterator should raise NoSuchElement"); } catch (final NoSuchElementException e) { // expected } } /** * Tests the {@link ListIterator#add(Object)} method of the list * iterator. */ public void testListIteratorAdd() { if (!isAddSupported()) { return; } resetEmpty(); final List list1 = getCollection(); final List list2 = getConfirmed(); final E[] elements = getFullElements(); ListIterator iter1 = list1.listIterator(); ListIterator iter2 = list2.listIterator(); for (final E element : elements) { iter1.add(element); iter2.add(element); verify(); } resetFull(); iter1 = getCollection().listIterator(); iter2 = getConfirmed().listIterator(); for (final E element : elements) { iter1.next(); iter2.next(); iter1.add(element); iter2.add(element); verify(); } } /** * Tests the {@link ListIterator#set(Object)} method of the list * iterator. */ public void testListIteratorSet() { if (!isSetSupported()) { return; } final E[] elements = getFullElements(); resetFull(); final ListIterator iter1 = getCollection().listIterator(); final ListIterator iter2 = getConfirmed().listIterator(); for (final E element : elements) { iter1.next(); iter2.next(); iter1.set(element); iter2.set(element); verify(); } } @SuppressWarnings("unchecked") public void testEmptyListSerialization() throws IOException, ClassNotFoundException { final List list = makeObject(); if (!(list instanceof Serializable && isTestSerialization())) { return; } final byte[] objekt = writeExternalFormToBytes((Serializable) list); final List list2 = (List) readExternalFormFromBytes(objekt); assertEquals("Both lists are empty", 0, list.size()); assertEquals("Both lists are empty", 0, list2.size()); } @SuppressWarnings("unchecked") public void testFullListSerialization() throws IOException, ClassNotFoundException { final List list = makeFullCollection(); final int size = getFullElements().length; if (!(list instanceof Serializable && isTestSerialization())) { return; } final byte[] objekt = writeExternalFormToBytes((Serializable) list); final List list2 = (List) readExternalFormFromBytes(objekt); assertEquals("Both lists are same size", size, list.size()); assertEquals("Both lists are same size", size, list2.size()); } /** * Compare the current serialized form of the List * against the canonical version in SVN. */ @SuppressWarnings("unchecked") 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 final List list = makeObject(); if (list instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final List list2 = (List) readExternalFormFromDisk(getCanonicalEmptyCollectionName(list)); assertEquals("List is empty", 0, list2.size()); assertEquals(list, list2); } } /** * Compare the current serialized form of the List * against the canonical version in SVN. */ @SuppressWarnings("unchecked") 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 final List list = makeFullCollection(); if(list instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final 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 AbstractListTest { private final AbstractListTest outer; public BulkTestSubList(final AbstractListTest outer) { super(""); this.outer = outer; } @Override @SuppressWarnings("unchecked") public E[] getFullElements() { final List l = Arrays.asList(outer.getFullElements()); return (E[]) l.subList(3, l.size() - 3).toArray(); } @Override public E[] getOtherElements() { return outer.getOtherElements(); } @Override public boolean isAddSupported() { return outer.isAddSupported(); } @Override public boolean isSetSupported() { return outer.isSetSupported(); } @Override public boolean isRemoveSupported() { return outer.isRemoveSupported(); } @Override public List makeObject() { return outer.makeFullCollection().subList(4, 4); } @Override public List makeFullCollection() { final int size = getFullElements().length; return outer.makeFullCollection().subList(3, size - 3); } @Override public void resetEmpty() { outer.resetFull(); this.setCollection(outer.getCollection().subList(4, 4)); this.setConfirmed(outer.getConfirmed().subList(4, 4)); } @Override public void resetFull() { outer.resetFull(); final int size = outer.getConfirmed().size(); this.setCollection(outer.getCollection().subList(3, size - 3)); this.setConfirmed(outer.getConfirmed().subList(3, size - 3)); } @Override public void verify() { super.verify(); outer.verify(); } @Override 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(); final int size = getCollection().size(); List sub = getCollection().subList(1, size); getCollection().add(getOtherElements()[0]); failFastAll(sub); resetFull(); sub = getCollection().subList(1, size); getCollection().add(0, getOtherElements()[0]); failFastAll(sub); resetFull(); sub = getCollection().subList(1, size); getCollection().addAll(Arrays.asList(getOtherElements())); failFastAll(sub); resetFull(); sub = getCollection().subList(1, size); getCollection().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(); final int size = getCollection().size(); List sub = getCollection().subList(1, size); getCollection().remove(0); failFastAll(sub); resetFull(); sub = getCollection().subList(1, size); getCollection().remove(getFullElements()[2]); failFastAll(sub); resetFull(); sub = getCollection().subList(1, size); getCollection().removeAll(Arrays.asList(getFullElements())); failFastAll(sub); resetFull(); sub = getCollection().subList(1, size); getCollection().retainAll(Arrays.asList(getOtherElements())); failFastAll(sub); resetFull(); sub = getCollection().subList(1, size); getCollection().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(final List list) { final Method[] methods = List.class.getMethods(); for (final Method method : methods) { failFastMethod(list, method); } } /** * 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(final List list, final Method m) { if (m.getName().equals("equals")) { return; } final E element = getOtherElements()[0]; final Collection c = Collections.singleton(element); final Class[] types = m.getParameterTypes(); final Object[] params = new Object[types.length]; for (int i = 0; i < params.length; i++) { if (types[i] == Integer.TYPE) { params[i] = Integer.valueOf(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 (final IllegalAccessException e) { // impossible } catch (final InvocationTargetException e) { final 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 AbstractListIteratorTest { public TestListIterator() { super("TestListIterator"); } @Override public E addSetValue() { return AbstractListTest.this.getOtherElements()[0]; } @Override public boolean supportsRemove() { return AbstractListTest.this.isRemoveSupported(); } @Override public boolean supportsAdd() { return AbstractListTest.this.isAddSupported(); } @Override public boolean supportsSet() { return AbstractListTest.this.isSetSupported(); } @Override public ListIterator makeEmptyIterator() { resetEmpty(); return AbstractListTest.this.getCollection().listIterator(); } @Override public ListIterator makeObject() { resetFull(); return AbstractListTest.this.getCollection().listIterator(); } } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/SetUniqueListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/SetUniqueListTest.ja100664 52012 12243235516 31716 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Set; /** * JUnit tests. * * @since 3.0 * @version $Id: SetUniqueListTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class SetUniqueListTest extends AbstractListTest { public SetUniqueListTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public List makeObject() { return new SetUniqueList(new ArrayList(), new HashSet()); } //----------------------------------------------------------------------- @Override public void testListIteratorSet() { // override to block resetFull(); final ListIterator it = getCollection().listIterator(); it.next(); try { it.set(null); fail(); } catch (final UnsupportedOperationException ex) {} } @Override @SuppressWarnings("unchecked") public E[] getFullNonNullElements() { // override to avoid duplicate "One" return (E[]) new Object[] { new String(""), new String("One"), Integer.valueOf(2), "Three", Integer.valueOf(4), new Double(5), new Float(6), "Seven", "Eight", new String("Nine"), Integer.valueOf(10), new Short((short)11), new Long(12), "Thirteen", "14", "15", new Byte((byte)16) }; } @Override public void testListIteratorAdd() { // override to cope with Set behaviour resetEmpty(); final List list1 = getCollection(); final List list2 = getConfirmed(); final E[] elements = getOtherElements(); // changed here ListIterator iter1 = list1.listIterator(); ListIterator iter2 = list2.listIterator(); for (final E element : elements) { iter1.add(element); iter2.add(element); super.verify(); // changed here } resetFull(); iter1 = getCollection().listIterator(); iter2 = getConfirmed().listIterator(); for (final E element : elements) { iter1.next(); iter2.next(); iter1.add(element); iter2.add(element); super.verify(); // changed here } } @Override public void testCollectionAddAll() { // override for set behaviour resetEmpty(); E[] elements = getFullElements(); boolean r = getCollection().addAll(Arrays.asList(elements)); getConfirmed().addAll(Arrays.asList(elements)); verify(); assertTrue("Empty collection should change after addAll", r); for (final E element : elements) { assertTrue("Collection should contain added element", getCollection().contains(element)); } resetFull(); final int size = getCollection().size(); elements = getOtherElements(); r = getCollection().addAll(Arrays.asList(elements)); getConfirmed().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, getCollection().contains(elements[i])); } assertEquals("Size should increase after addAll", size + elements.length, getCollection().size()); } public void testIntCollectionAddAll() { // make a SetUniqueList with one element final List list = new SetUniqueList(new ArrayList(), new HashSet()); final Integer existingElement = Integer.valueOf(1); list.add(existingElement); // add two new unique elements at index 0 final Integer firstNewElement = Integer.valueOf(2); final Integer secondNewElement = Integer.valueOf(3); Collection collection = Arrays.asList(firstNewElement, secondNewElement); list.addAll(0, collection); assertEquals("Unique elements should be added.", 3, list.size()); assertEquals("First new element should be at index 0", firstNewElement, list.get(0)); assertEquals("Second new element should be at index 1", secondNewElement, list.get(1)); assertEquals("Existing element should shift to index 2", existingElement, list.get(2)); // add a duplicate element and a unique element at index 0 final Integer thirdNewElement = Integer.valueOf(4); collection = Arrays.asList(existingElement, thirdNewElement); list.addAll(0, collection); assertEquals("Duplicate element should not be added, unique element should be added.", 4, list.size()); assertEquals("Third new element should be at index 0", thirdNewElement, list.get(0)); } @Override @SuppressWarnings("unchecked") public void testListSetByIndex() { // override for set behaviour resetFull(); final int size = getCollection().size(); getCollection().set(0, (E) new Long(1000)); assertEquals(size, getCollection().size()); getCollection().set(2, (E) new Long(1000)); assertEquals(size - 1, getCollection().size()); assertEquals(new Long(1000), getCollection().get(1)); // set into 2, but shifted down to 1 } boolean extraVerify = true; @Override public void testCollectionIteratorRemove() { try { extraVerify = false; super.testCollectionIteratorRemove(); } finally { extraVerify = true; } } @Override @SuppressWarnings("unchecked") public void verify() { super.verify(); if (extraVerify) { final int size = getCollection().size(); getCollection().add((E) new Long(1000)); assertEquals(size + 1, getCollection().size()); getCollection().add((E) new Long(1000)); assertEquals(size + 1, getCollection().size()); assertEquals(new Long(1000), getCollection().get(size)); getCollection().remove(size); } } //----------------------------------------------------------------------- public void testFactory() { final Integer[] array = new Integer[] { Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(1) }; final ArrayList list = new ArrayList(Arrays.asList(array)); final SetUniqueList lset = SetUniqueList.setUniqueList(list); assertEquals("Duplicate element was added.", 2, lset.size()); assertEquals(Integer.valueOf(1), lset.get(0)); assertEquals(Integer.valueOf(2), lset.get(1)); assertEquals(Integer.valueOf(1), list.get(0)); assertEquals(Integer.valueOf(2), list.get(1)); } @SuppressWarnings("unchecked") public void testAdd() { final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); // Duplicate element final E obj = (E) Integer.valueOf(1); lset.add(obj); lset.add(obj); assertEquals("Duplicate element was added.", 1, lset.size()); // Unique element lset.add((E) Integer.valueOf(2)); assertEquals("Unique element was not added.", 2, lset.size()); } @SuppressWarnings("unchecked") public void testAddAll() { final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); lset.addAll( Arrays.asList((E[]) new Integer[] { Integer.valueOf(1), Integer.valueOf(1)})); assertEquals("Duplicate element was added.", 1, lset.size()); } @SuppressWarnings("unchecked") public void testSet() { final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); // Duplicate element final E obj1 = (E) Integer.valueOf(1); final E obj2 = (E) Integer.valueOf(2); final E obj3 = (E) Integer.valueOf(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)); } @SuppressWarnings("unchecked") public void testListIterator() { final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); final E obj1 = (E) Integer.valueOf(1); final E obj2 = (E) Integer.valueOf(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()); } @SuppressWarnings("unchecked") public void testUniqueListReInsert() { final List l = SetUniqueList.setUniqueList(new LinkedList()); l.add((E) new Object()); l.add((E) new Object()); final E 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()); } @SuppressWarnings("unchecked") public void testUniqueListDoubleInsert() { final List l = SetUniqueList.setUniqueList(new LinkedList()); l.add((E) new Object()); l.add((E) 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()); } @SuppressWarnings("unchecked") public void testSetDownwardsInList() { /* * Checks the following semantics * [a,b] * set(0,b): [b]->a * So UniqList contains [b] and a is returned */ final ArrayList l = new ArrayList(); final HashSet s = new HashSet(); final SetUniqueList ul = new SetUniqueList(l, s); final E a = (E) new Object(); final E b = (E) 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)); } @SuppressWarnings("unchecked") 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 */ final ArrayList l = new ArrayList(); final HashSet s = new HashSet(); final SetUniqueList ul = new SetUniqueList(l, s); final E a = (E) new Object(); final E b = (E) new Object(); final E c = (E) 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)); } @SuppressWarnings("unchecked") 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 */ final ArrayList l = new ArrayList(); final HashSet s = new HashSet(); final SetUniqueList ul = new SetUniqueList(l, s); final E a = (E) new String("A"); final E b = (E) new String("B"); final E c = (E) 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 void testCollections304() { final List list = new LinkedList(); final SetUniqueList decoratedList = SetUniqueList.setUniqueList(list); final String s1 = "Apple"; final String s2 = "Lemon"; final String s3 = "Orange"; final String s4 = "Strawberry"; decoratedList.add(s1); decoratedList.add(s2); decoratedList.add(s3); assertEquals(3, decoratedList.size()); decoratedList.set(1, s4); assertEquals(3, decoratedList.size()); decoratedList.add(1, s4); assertEquals(3, decoratedList.size()); decoratedList.add(1, s2); assertEquals(4, decoratedList.size()); } public void testSubListIsUnmodifiable() { resetFull(); List subList = getCollection().subList(1, 3); try { subList.remove(0); fail("subList should be unmodifiable"); } catch (UnsupportedOperationException e) { // expected } } @SuppressWarnings("unchecked") public void testCollections307() { List list = new ArrayList(); List uniqueList = SetUniqueList.setUniqueList(list); final String hello = "Hello"; final String world = "World"; uniqueList.add((E) hello); uniqueList.add((E) world); List subList = list.subList(0, 0); List subUniqueList = uniqueList.subList(0, 0); assertFalse(subList.contains(world)); // passes assertFalse(subUniqueList.contains(world)); // fails List worldList = new ArrayList(); worldList.add((E) world); assertFalse(subList.contains("World")); // passes assertFalse(subUniqueList.contains("World")); // fails // repeat the test with a different class than HashSet; // which means subclassing SetUniqueList below list = new ArrayList(); uniqueList = new SetUniqueList307(list, new java.util.TreeSet()); uniqueList.add((E) hello); uniqueList.add((E) world); subList = list.subList(0, 0); subUniqueList = uniqueList.subList(0, 0); assertFalse(subList.contains(world)); // passes assertFalse(subUniqueList.contains(world)); // fails worldList = new ArrayList(); worldList.add((E) world); assertFalse(subList.contains("World")); // passes assertFalse(subUniqueList.contains("World")); // fails } @SuppressWarnings("unchecked") public void testRetainAll() { final List list = new ArrayList(10); final SetUniqueList uniqueList = SetUniqueList.setUniqueList(list); for (int i = 0; i < 10; ++i) { uniqueList.add((E)Integer.valueOf(i)); } final Collection retained = new ArrayList(5); for (int i = 0; i < 5; ++i) { retained.add((E)Integer.valueOf(i * 2)); } assertTrue(uniqueList.retainAll(retained)); assertEquals(5, uniqueList.size()); assertTrue(uniqueList.contains(Integer.valueOf(0))); assertTrue(uniqueList.contains(Integer.valueOf(2))); assertTrue(uniqueList.contains(Integer.valueOf(4))); assertTrue(uniqueList.contains(Integer.valueOf(6))); assertTrue(uniqueList.contains(Integer.valueOf(8))); } @SuppressWarnings("unchecked") public void testRetainAllWithInitialList() { // initialized with empty list final List list = new ArrayList(10); for (int i = 0; i < 5; ++i) { list.add((E)Integer.valueOf(i)); } final SetUniqueList uniqueList = SetUniqueList.setUniqueList(list); for (int i = 5; i < 10; ++i) { uniqueList.add((E)Integer.valueOf(i)); } final Collection retained = new ArrayList(5); for (int i = 0; i < 5; ++i) { retained.add((E)Integer.valueOf(i * 2)); } assertTrue(uniqueList.retainAll(retained)); assertEquals(5, uniqueList.size()); assertTrue(uniqueList.contains(Integer.valueOf(0))); assertTrue(uniqueList.contains(Integer.valueOf(2))); assertTrue(uniqueList.contains(Integer.valueOf(4))); assertTrue(uniqueList.contains(Integer.valueOf(6))); assertTrue(uniqueList.contains(Integer.valueOf(8))); } /* * test case for https://issues.apache.org/jira/browse/COLLECTIONS-427 */ @SuppressWarnings("boxing") // OK in test code public void testRetainAllCollections427() { final int size = 50000; final ArrayList list = new ArrayList(); for (int i = 0; i < size; i++) { list.add(i); } final SetUniqueList uniqueList = SetUniqueList.setUniqueList(list); final ArrayList toRetain = new ArrayList(); for (int i = size; i < 2*size; i++) { toRetain.add(i); } final long start = System.currentTimeMillis(); uniqueList.retainAll(toRetain); final long stop = System.currentTimeMillis(); // make sure retainAll completes under 5 seconds // TODO if test is migrated to JUnit 4, add a Timeout rule. // http://kentbeck.github.com/junit/javadoc/latest/org/junit/rules/Timeout.html assertTrue(stop - start < 5000); } public void testSetCollections444() { final SetUniqueList lset = new SetUniqueList(new ArrayList(), new HashSet()); // Duplicate element final Integer obj1 = Integer.valueOf(1); final Integer obj2 = Integer.valueOf(2); lset.add(obj1); lset.add(obj2); lset.set(0, obj1); assertEquals(2, lset.size()); assertSame(obj1, lset.get(0)); assertSame(obj2, lset.get(1)); assertTrue(lset.contains(obj1)); assertTrue(lset.contains(obj2)); } class SetUniqueList307 extends SetUniqueList { /** * Generated serial version ID. */ private static final long serialVersionUID = 1415013031022962158L; public SetUniqueList307(final List list, final Set set) { super(list, set); } } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/SetUniqueList.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/SetUniqueList.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/NodeCachingLinkedListTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/list/NodeCachingLinkedLis100664 12473 12243235516 31657 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.Arrays; import java.util.LinkedList; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * Test class for NodeCachingLinkedList, a performance optimised LinkedList. * * @version $Id: NodeCachingLinkedListTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class NodeCachingLinkedListTest extends AbstractLinkedListTest { public NodeCachingLinkedListTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(NodeCachingLinkedListTest.class); } //----------------------------------------------------------------------- @Override public NodeCachingLinkedList makeObject() { return new NodeCachingLinkedList(); } @Override public String getCompatibilityVersion() { return "4"; } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testShrinkCache() { if (!isRemoveSupported() || !isAddSupported()) { return; } resetEmpty(); final NodeCachingLinkedList list = getCollection(); list.addAll(Arrays.asList((E[]) new String[] { "1", "2", "3", "4" })); list.removeAllNodes(); // Will dump all 4 elements into cache list.setMaximumCacheSize(2); // shrink cache list.addAll(Arrays.asList((E[]) 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((E[]) new String[] { "1", "2", "3", "4" })); checkNodes(); } //----------------------------------------------------------------------- public static void compareSpeed() { final NodeCachingLinkedList ncll = new NodeCachingLinkedList(); final LinkedList ll = new LinkedList(); final Object o1 = new Object(); final Object o2 = new Object(); final 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) getCollection(), // "src/test/resources/data/test/NodeCachingLinkedList.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), // "src/test/resources/data/test/NodeCachingLinkedList.fullCollection.version4.obj"); // } /** * {@inheritDoc} */ @Override public NodeCachingLinkedList getCollection() { return (NodeCachingLinkedList) super.getCollection(); } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/ComparatorChainTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/ComparatorCha100664 17106 12243235516 32016 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.comparators; import java.io.Serializable; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import org.junit.Test; /** * Tests for ComparatorChain. * * @version $Id: ComparatorChainTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ComparatorChainTest extends AbstractComparatorTest { public ComparatorChainTest(final String testName) { super(testName); } @Override public Comparator makeObject() { final 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; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/ComparatorChain.version4.obj"); // } @Test public void testNoopComparatorChain() { final ComparatorChain chain = new ComparatorChain(); final Integer i1 = Integer.valueOf(4); final Integer i2 = Integer.valueOf(6); chain.addComparator(new ComparableComparator()); final int correctValue = i1.compareTo(i2); assertTrue("Comparison returns the right order", chain.compare(i1, i2) == correctValue); } @Test public void testBadNoopComparatorChain() { final ComparatorChain chain = new ComparatorChain(); final Integer i1 = Integer.valueOf(4); final Integer i2 = Integer.valueOf(6); try { chain.compare(i1,i2); fail("An exception should be thrown when a chain contains zero comparators."); } catch (final UnsupportedOperationException e) { } } @Test public void testListComparatorChain() { final List> list = new LinkedList>(); list.add(new ComparableComparator()); final ComparatorChain chain = new ComparatorChain(list); final Integer i1 = Integer.valueOf(4); final Integer i2 = Integer.valueOf(6); final int correctValue = i1.compareTo(i2); assertTrue("Comparison returns the right order", chain.compare(i1, i2) == correctValue); } @Test public void testBadListComparatorChain() { final List> list = new LinkedList>(); final ComparatorChain chain = new ComparatorChain(list); final Integer i1 = Integer.valueOf(4); final Integer i2 = Integer.valueOf(6); try { chain.compare(i1, i2); fail("An exception should be thrown when a chain contains zero comparators."); } catch (final UnsupportedOperationException e) { } } @Test public void testComparatorChainOnMinvaluedCompatator() { // -1 * Integer.MIN_VALUE is less than 0, // test that ComparatorChain handles this edge case correctly final ComparatorChain chain = new ComparatorChain(); chain.addComparator(new Comparator() { public int compare(final Integer a, final Integer b) { final int result = a.compareTo(b); if (result < 0) { return Integer.MIN_VALUE; } if (result > 0) { return Integer.MAX_VALUE; } return 0; } }, true); assertTrue(chain.compare(Integer.valueOf(4), Integer.valueOf(5)) > 0); assertTrue(chain.compare(Integer.valueOf(5), Integer.valueOf(4)) < 0); assertTrue(chain.compare(Integer.valueOf(4), Integer.valueOf(4)) == 0); } @Override public List getComparableObjectsOrdered() { final 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 { /** * Generated serial version ID. */ private static final long serialVersionUID = 8085570439751032499L; public int cols[] = new int[3]; public PseudoRow(final int col1, final int col2, final int col3) { cols[0] = col1; cols[1] = col2; cols[2] = col3; } public int getColumn(final int colIndex) { return cols[colIndex]; } @Override public String toString() { final StringBuilder buf = new StringBuilder(); buf.append("["); buf.append(cols[0]); buf.append(","); buf.append(cols[1]); buf.append(","); buf.append(cols[2]); buf.append("]"); return buf.toString(); } @Override public boolean equals(final Object o) { if (!(o instanceof PseudoRow)) { return false; } final 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 { private static final long serialVersionUID = -2284880866328872105L; protected int colIndex = 0; public ColumnComparator(final int colIndex) { this.colIndex = colIndex; } public int compare(final PseudoRow o1, final PseudoRow o2) { final int col1 = o1.getColumn(colIndex); final int col2 = o2.getColumn(colIndex); if (col1 > col2) { return 1; } if (col1 < col2) { return -1; } return 0; } @Override public int hashCode() { return colIndex; } @Override public boolean equals(final Object that) { return that instanceof ColumnComparator && colIndex == ((ColumnComparator) that).colIndex; } } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/BooleanComparatorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/BooleanCompar100664 13423 12243235516 32012 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.comparators; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import org.junit.Test; /** * Tests for {@link BooleanComparator}. * * @version $Id: BooleanComparatorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("boxing") public class BooleanComparatorTest extends AbstractComparatorTest { // conventional // ------------------------------------------------------------------------ public BooleanComparatorTest(final String testName) { super(testName); } // collections testing framework // ------------------------------------------------------------------------ @Override public Comparator makeObject() { return new BooleanComparator(); } @Override public List getComparableObjectsOrdered() { final 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(true); return list; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/BooleanComparator.version4.obj"); // } // tests // ------------------------------------------------------------------------ @Test public void testConstructors() { allTests(false,new BooleanComparator()); allTests(false,new BooleanComparator(false)); allTests(true,new BooleanComparator(true)); } @Test public void testStaticFactoryMethods() { allTests(false,BooleanComparator.getFalseFirstComparator()); allTests(false,BooleanComparator.booleanComparator(false)); allTests(true,BooleanComparator.getTrueFirstComparator()); allTests(true,BooleanComparator.booleanComparator(true)); } @Test 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.booleanComparator(false)); assertEquals(new BooleanComparator(true),new BooleanComparator(true)); assertEquals(new BooleanComparator(true),BooleanComparator.getTrueFirstComparator()); assertSame(BooleanComparator.getTrueFirstComparator(),BooleanComparator.booleanComparator(true)); assertTrue(!new BooleanComparator().equals(new BooleanComparator(true))); assertTrue(!new BooleanComparator(true).equals(new BooleanComparator(false))); } // utilities // ------------------------------------------------------------------------ protected void allTests(final boolean trueFirst, final BooleanComparator comp) { orderIndependentTests(comp); if(trueFirst) { trueFirstTests(comp); } else { falseFirstTests(comp); } } protected void trueFirstTests(final BooleanComparator comp) { assertNotNull(comp); assertEquals(0,comp.compare(true, true)); assertEquals(0,comp.compare(false, false)); assertTrue(comp.compare(false, true) > 0); assertTrue(comp.compare(true, false) < 0); } protected void falseFirstTests(final BooleanComparator comp) { assertNotNull(comp); assertEquals(0,comp.compare(true, true)); assertEquals(0,comp.compare(false, false)); assertTrue(comp.compare(false, true) < 0); assertTrue(comp.compare(true, false) > 0); } protected void orderIndependentTests(final BooleanComparator comp) { nullArgumentTests(comp); } protected void nullArgumentTests(final BooleanComparator comp) { assertNotNull(comp); try { comp.compare(null,null); fail("Expected NullPointerException"); } catch(final NullPointerException e) { // expected } try { comp.compare(Boolean.TRUE,null); fail("Expected NullPointerException"); } catch(final NullPointerException e) { // expected } try { comp.compare(Boolean.FALSE,null); fail("Expected NullPointerException"); } catch(final NullPointerException e) { // expected } try { comp.compare(null,Boolean.TRUE); fail("Expected NullPointerException"); } catch(final NullPointerException e) { // expected } try { comp.compare(null,Boolean.FALSE); fail("Expected NullPointerException"); } catch(final NullPointerException e) { // expected } } } ././@LongLink100644 0 0 167 12243235652 10263 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/TransformingComparatorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/TransformingC100664 4464 12243235516 32032 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.comparators; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import org.apache.commons.collections4.ComparatorUtils; import org.apache.commons.collections4.TransformerUtils; /** * Test class for TransformingComparator. * * @version $Id: TransformingComparatorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class TransformingComparatorTest extends AbstractComparatorTest { // // Initialization and busywork // public TransformingComparatorTest(final String name) { super(name); } // // Set up and tear down // @Override public Comparator makeObject() { final Comparator decorated = new ComparableComparator(); return ComparatorUtils.transformedComparator(decorated, TransformerUtils.stringValueTransformer()); } @Override @SuppressWarnings("boxing") // OK in test code public List getComparableObjectsOrdered() { final List list = new LinkedList(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); return list; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/TransformingComparator.version4.obj"); // } // // The tests // } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/AbstractComparatorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/AbstractCompa100664 15752 12243235516 32023 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.AbstractObjectTest; import org.junit.Test; /** * Abstract test class for testing the Comparator interface. *

* Concrete subclasses declare the comparator to be tested. * They also declare certain aspects of the tests. */ public abstract class AbstractComparatorTest extends AbstractObjectTest { /** * JUnit constructor. * * @param testName the test class name */ public AbstractComparatorTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * 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 */ @Override public abstract Comparator makeObject(); /** * Overrides superclass to block tests. */ @Override public boolean supportsEmptyCollections() { return false; } /** * Overrides superclass to block tests. */ @Override public boolean supportsFullCollections() { return false; } //----------------------------------------------------------------------- /** * Reverse the list. */ protected void reverseObjects(final List list) { Collections.reverse(list); } /** * Randomize the list. */ protected void randomizeObjects(final List list) { Collections.shuffle(list); } /** * Sort the list. */ protected void sortObjects(final List list, final Comparator comparator) { Collections.sort(list, comparator); } //----------------------------------------------------------------------- /** * Test sorting an empty list */ @Test public void testEmptyListSort() { final List list = new LinkedList(); sortObjects(list, makeObject()); final List list2 = new LinkedList(); assertTrue("Comparator cannot sort empty lists", list2.equals(list)); } /** * Test sorting a reversed list. */ @Test public void testReverseListSort() { final Comparator comparator = makeObject(); final List randomList = getComparableObjectsOrdered(); reverseObjects(randomList); sortObjects(randomList, comparator); final List orderedList = getComparableObjectsOrdered(); assertTrue("Comparator did not reorder the List correctly", orderedList.equals(randomList)); } /** * Test sorting a random list. */ @Test public void testRandomListSort() { final Comparator comparator = makeObject(); final List randomList = getComparableObjectsOrdered(); randomizeObjects(randomList); sortObjects(randomList,comparator); final 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. */ @Test public void testComparatorIsSerializable() { final Comparator comparator = makeObject(); assertTrue("This comparator should be Serializable.", comparator instanceof Serializable); } public String getCanonicalComparatorName(final Object object) { final StringBuilder retval = new StringBuilder(); retval.append(TEST_DATA_PATH); 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 SVN. */ @SuppressWarnings("unchecked") @Test 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(makeObject())); } catch (final FileNotFoundException exception) { final boolean autoCreateSerialized = false; if (autoCreateSerialized) { comparator = makeObject(); final 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 final List randomList = getComparableObjectsOrdered(); reverseObjects(randomList); sortObjects(randomList, comparator); final List orderedList = getComparableObjectsOrdered(); assertTrue("Comparator did not reorder the List correctly", orderedList.equals(randomList)); } } } ././@LongLink100644 0 0 165 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/ComparableComparatorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/ComparableCom100664 3632 12243235516 31756 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.comparators; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Tests for ComparableComparator. * * @version $Id: ComparableComparatorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ * */ @SuppressWarnings("boxing") public class ComparableComparatorTest extends AbstractComparatorTest { public ComparableComparatorTest(final String testName) { super(testName); } @Override public Comparator makeObject() { return new ComparableComparator(); } @Override public List getComparableObjectsOrdered() { final List list = new LinkedList(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); return list; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/ComparableComparator.version4.obj"); // } } ././@LongLink100644 0 0 167 12243235652 10263 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/AbstractNullComparatorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/AbstractNullC100664 10173 12243235516 31771 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 $Id: AbstractNullComparatorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public abstract class AbstractNullComparatorTest extends AbstractComparatorTest { public AbstractNullComparatorTest(final String testName) { super(testName); } public static Test suite() { final TestSuite suite = new TestSuite(AbstractNullComparatorTest.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 AbstractNullComparatorTest { public TestNullComparator1(final String testName) { super(testName); } @Override public Comparator makeObject() { return new NullComparator(); } @Override public List getComparableObjectsOrdered() { final List list = new LinkedList(); list.add(Integer.valueOf(1)); list.add(Integer.valueOf(2)); list.add(Integer.valueOf(3)); list.add(Integer.valueOf(4)); list.add(Integer.valueOf(5)); list.add(null); return list; } @Override public String getCanonicalComparatorName(final Object object) { return super.getCanonicalComparatorName(object) + "1"; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/NullComparator.version4.obj1"); // } } /** * Test the NullComparator with nulls low using the comparable comparator **/ public static class TestNullComparator2 extends AbstractNullComparatorTest { public TestNullComparator2(final String testName) { super(testName); } @Override public Comparator makeObject() { return new NullComparator(false); } @Override public List getComparableObjectsOrdered() { final List list = new LinkedList(); list.add(null); list.add(Integer.valueOf(1)); list.add(Integer.valueOf(2)); list.add(Integer.valueOf(3)); list.add(Integer.valueOf(4)); list.add(Integer.valueOf(5)); return list; } @Override public String getCanonicalComparatorName(final Object object) { return super.getCanonicalComparatorName(object) + "2"; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/NullComparator.version4.obj2"); // } } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/ReverseComparatorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/ReverseCompar100664 6636 12243235516 32036 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 org.junit.Test; /** * Tests for ReverseComparator. * * @version $Id: ReverseComparatorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ReverseComparatorTest extends AbstractComparatorTest { public ReverseComparatorTest(final String testName) { super(testName); } /** * 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 SVN. * * @return Comparator that returns "natural" order */ @Override public Comparator makeObject() { return new ReverseComparator(Collections.reverseOrder()); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/ReverseComparator.version4.obj"); // } @Override public List getComparableObjectsOrdered() { final List list = new LinkedList(); list.add(Integer.valueOf(1)); list.add(Integer.valueOf(2)); list.add(Integer.valueOf(3)); list.add(Integer.valueOf(4)); list.add(Integer.valueOf(5)); return list; } /** * Override this inherited test since Collections.reverseOrder * doesn't adhere to the "soft" Comparator contract, and we've * already "canonized" the comparator returned by makeComparator. */ @Override @Test public void testSerializeDeserializeThenCompare() throws Exception { final Comparator comp = new ReverseComparator(new ComparableComparator()); final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(comp); out.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); final Object dest = in.readObject(); in.close(); assertEquals("obj != deserialize(serialize(obj))",comp,dest); } } ././@LongLink100644 0 0 165 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/FixedOrderComparatorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/comparators/FixedOrderCom100664 20756 12243235516 31772 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.comparators; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.junit.Test; /** * Test class for FixedOrderComparator. * * @version $Id: FixedOrderComparatorTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class FixedOrderComparatorTest extends AbstractComparatorTest { /** * Top cities of the world, by population including metro areas. */ private 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 FixedOrderComparatorTest(final String name) { super(name); } // // Set up and tear down // @Override public Comparator makeObject() { final FixedOrderComparator comparator = new FixedOrderComparator(topCities); return comparator; } @Override public List getComparableObjectsOrdered() { return Arrays.asList(topCities); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/FixedOrderComparator.version4.obj"); // } // // The tests // /** * Tests that the constructor plus add method compares items properly. */ @Test public void testConstructorPlusAdd() { final FixedOrderComparator comparator = new FixedOrderComparator(); for (final String topCitie : topCities) { comparator.add(topCitie); } final String[] keys = topCities.clone(); assertComparatorYieldsOrder(keys, comparator); } /** * Tests that the array constructor compares items properly. */ @Test public void testArrayConstructor() { final String[] keys = topCities.clone(); final String[] topCitiesForTest = topCities.clone(); final 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. */ @Test public void testListConstructor() { final String[] keys = topCities.clone(); final List topCitiesForTest = new LinkedList(Arrays.asList(topCities)); final 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. */ @Test public void testAddAsEqual() { final 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. */ @Test public void testLock() { final 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 (final UnsupportedOperationException e) { // success -- ignore } try { comparator.addAsEqual("New York", "Minneapolis"); fail("Should have thrown an UnsupportedOperationException"); } catch (final UnsupportedOperationException e) { // success -- ignore } } @Test public void testUnknownObjectBehavior() { FixedOrderComparator comparator = new FixedOrderComparator(topCities); try { comparator.compare("New York", "Minneapolis"); fail("Should have thrown a IllegalArgumentException"); } catch (final IllegalArgumentException e) { // success-- ignore } try { comparator.compare("Minneapolis", "New York"); fail("Should have thrown a IllegalArgumentException"); } catch (final IllegalArgumentException e) { // success-- ignore } assertEquals(FixedOrderComparator.UnknownObjectBehavior.EXCEPTION, comparator.getUnknownObjectBehavior()); comparator = new FixedOrderComparator(topCities); comparator.setUnknownObjectBehavior(FixedOrderComparator.UnknownObjectBehavior.BEFORE); assertEquals(FixedOrderComparator.UnknownObjectBehavior.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.UnknownObjectBehavior.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(final String[] orderedObjects, final Comparator comparator) { final String[] keys = orderedObjects.clone(); // shuffle until the order changes. It's extremely rare that // this requires more than one shuffle. boolean isInNewOrder = false; final Random rand = new Random(); while (keys.length > 1 && !isInNewOrder) { // shuffle: for (int i = keys.length-1; i > 0; i--) { final String swap = keys[i]; final 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]); } } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/SplitMapUtilsTest.java100664 16025 12243235516 31272 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections4.functors.NOPTransformer; import org.apache.commons.collections4.map.HashedMap; import org.apache.commons.collections4.splitmap.TransformedSplitMap; /** * Tests for {@link TransformedSplitMap} * * @since 4.0 * @version $Id: SplitMapUtilsTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("boxing") public class SplitMapUtilsTest extends BulkTest { private Map backingMap; private TransformedSplitMap transformedMap; private final Transformer stringToInt = new Transformer() { public Integer transform(final String input) { return Integer.valueOf(input); } }; public SplitMapUtilsTest(final String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); backingMap = new HashMap(); transformedMap = TransformedSplitMap.transformingMap(backingMap, NOPTransformer. nopTransformer(), stringToInt); for (int i = 0; i < 10; i++) { transformedMap.put(String.valueOf(i), String.valueOf(i)); } } // ----------------------------------------------------------------------- public void testReadableMap() { final IterableMap map = SplitMapUtils.readableMap(transformedMap); // basic for (int i = 0; i < 10; i++) { assertFalse(map.containsValue(String.valueOf(i))); assertEquals(i, map.get(String.valueOf(i)).intValue()); } // mapIterator final MapIterator it = map.mapIterator(); while (it.hasNext()) { final String k = it.next(); assertEquals(k, it.getKey()); assertEquals(Integer.valueOf(k), it.getValue()); } // unmodifiable assertTrue(map instanceof Unmodifiable); // check individual operations int sz = map.size(); attemptPutOperation(new Runnable() { public void run() { map.clear(); } }); assertEquals(sz, map.size()); attemptPutOperation(new Runnable() { public void run() { map.put("foo", 100); } }); final HashMap m = new HashMap(); m.put("foo", 100); m.put("bar", 200); m.put("baz", 300); attemptPutOperation(new Runnable() { public void run() { map.putAll(m); } }); // equals, hashcode final IterableMap other = SplitMapUtils.readableMap(transformedMap); assertEquals(other, map); assertEquals(other.hashCode(), map.hashCode()); // remove for (int i = 0; i < 10; i++) { assertEquals(i, map.remove(String.valueOf(i)).intValue()); assertEquals(--sz, map.size()); } assertTrue(map.isEmpty()); assertSame(map, SplitMapUtils.readableMap(map)); } public void testAlreadyReadableMap() { final HashedMap hashedMap = new HashedMap(); assertSame(hashedMap, SplitMapUtils.readableMap(hashedMap)); } @SuppressWarnings("unchecked") public void testWritableMap() { final Map map = SplitMapUtils.writableMap(transformedMap); attemptGetOperation(new Runnable() { public void run() { map.get(null); } }); attemptGetOperation(new Runnable() { public void run() { map.entrySet(); } }); attemptGetOperation(new Runnable() { public void run() { map.keySet(); } }); attemptGetOperation(new Runnable() { public void run() { map.values(); } }); attemptGetOperation(new Runnable() { public void run() { map.size(); } }); attemptGetOperation(new Runnable() { public void run() { map.isEmpty(); } }); attemptGetOperation(new Runnable() { public void run() { map.containsKey(null); } }); attemptGetOperation(new Runnable() { public void run() { map.containsValue(null); } }); attemptGetOperation(new Runnable() { public void run() { map.remove(null); } }); // equals, hashcode final Map other = SplitMapUtils.writableMap(transformedMap); assertEquals(other, map); assertEquals(other.hashCode(), map.hashCode()); // put int sz = backingMap.size(); assertFalse(backingMap.containsKey("foo")); map.put("new", "66"); assertEquals(++sz, backingMap.size()); // putall final Map more = new HashMap(); more.put("foo", "77"); more.put("bar", "88"); more.put("baz", "99"); map.putAll(more); assertEquals(sz + more.size(), backingMap.size()); // clear map.clear(); assertTrue(backingMap.isEmpty()); assertSame(map, SplitMapUtils.writableMap((Put) map)); } public void testAlreadyWritableMap() { final HashedMap hashedMap = new HashedMap(); assertSame(hashedMap, SplitMapUtils.writableMap(hashedMap)); } private void attemptGetOperation(final Runnable r) { attemptMapOperation("Put exposed as writable Map must not allow Get operations", r); } private void attemptPutOperation(final Runnable r) { attemptMapOperation("Get exposed as writable Map must not allow Put operations", r); } private void attemptMapOperation(final String s, final Runnable r) { try { r.run(); fail(s); } catch (final UnsupportedOperationException e) { } } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/MockTestCase.java100664 4330 12243235516 30161 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import org.easymock.EasyMock; import org.easymock.IExpectationSetters; /** * Provides utilities for making mock-based tests. Most notable is the generic "type-safe" * {@link #createMock(Class)} method, and {@link #replay()} and {@link #verify()} methods * that call the respective methods on all created mock objects. */ public abstract class MockTestCase { private final List mockObjects = new ArrayList(); @SuppressWarnings("unchecked") protected T createMock(final Class name) { final T mock = (T) EasyMock.createMock(name); return registerMock(mock); } private T registerMock(final T mock) { mockObjects.add(mock); return mock; } protected IExpectationSetters expect(final T t) { return EasyMock.expect(t); } protected final void replay() { for (final Object o : mockObjects) { EasyMock.replay(o); } } protected final void verify() { for (final ListIterator i = mockObjects.listIterator(); i.hasNext();) { try { EasyMock.verify(i.next()); } catch (final AssertionError e) { throw new AssertionError(i.previousIndex() + 1 + "" + e.getMessage()); } } } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/splitmap/TransformedSplitMapTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/splitmap/TransformedSplit100664 17217 12243235516 32075 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.splitmap; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.math.BigInteger; import java.util.HashMap; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.functors.NOPTransformer; /** * Tests for {@link TransformedSplitMap} * * @since 4.0 * @version $Id: TransformedSplitMapTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("boxing") public class TransformedSplitMapTest extends BulkTest { private final Transformer intToString = new Transformer() { public String transform(final Integer input) { return String.valueOf(input); } }; private final Transformer> objectToClass = new Transformer>() { public java.lang.Class transform(final Object input) { return input == null ? null : input.getClass(); } }; private final Transformer stringToInt = new Transformer() { public Integer transform(final String input) { return Integer.valueOf(input); } }; public TransformedSplitMapTest(final String testName) { super(testName); } // ----------------------------------------------------------------------- public void testTransformedMap() { final TransformedSplitMap> map = TransformedSplitMap.transformingMap( new HashMap>(), intToString, objectToClass); final Integer[] k = new Integer[] { 0, 1, 2, 3, 4, 5, 6 }; final Object[] v = new Object[] { "", new Object(), new HashMap(), 0, BigInteger.TEN, null, new Object[0] }; assertEquals(0, map.size()); for (int i = 0; i < k.length; i++) { map.put(k[i], v[i]); assertEquals(i + 1, map.size()); assertTrue(map.containsKey(intToString.transform(k[i]))); assertFalse(map.containsKey(k[i])); assertTrue(map.containsValue(objectToClass.transform(v[i]))); assertTrue(objectToClass.transform(v[i]) != v[i] ^ map.containsValue(v[i])); assertEquals(objectToClass.transform(v[i]), map.get(intToString.transform(k[i]))); } int sz = map.size(); assertEquals(null, map.remove(k[0])); assertEquals(sz, map.size()); assertEquals(objectToClass.transform(v[0]), map.remove(intToString.transform(k[0]))); assertEquals(--sz, map.size()); final TransformedSplitMap map2 = TransformedSplitMap.transformingMap( new HashMap(), NOPTransformer. nopTransformer(), stringToInt); assertEquals(0, map2.size()); for (int i = 0; i < 6; i++) { map2.put(String.valueOf(i), String.valueOf(i)); assertEquals(i + 1, map2.size()); assertTrue(map2.containsValue(i)); assertFalse(map2.containsValue(String.valueOf(i))); assertTrue(map2.containsKey(String.valueOf(i))); assertEquals(i, map2.get(String.valueOf(i)).intValue()); } int sz2 = map2.size(); assertEquals(Integer.valueOf(0), map2.remove("0")); assertEquals(--sz2, map2.size()); } // ----------------------------------------------------------------------- public void testMapIterator() { final TransformedSplitMap map = TransformedSplitMap.transformingMap(new HashMap(), NOPTransformer. nopTransformer(), stringToInt); assertEquals(0, map.size()); for (int i = 0; i < 6; i++) { map.put(String.valueOf(i), String.valueOf(i)); } for (final MapIterator it = map.mapIterator(); it.hasNext();) { final String k = it.next(); assertEquals(k, it.getKey()); assertEquals(map.get(k), it.getValue()); } } public void testEmptyMap() throws IOException, ClassNotFoundException { final TransformedSplitMap map = TransformedSplitMap.transformingMap(new HashMap(), NOPTransformer.nopTransformer(), NOPTransformer.nopTransformer() ); final ObjectInputStream in = new ObjectInputStream( new FileInputStream( TEST_DATA_PATH+"/TransformedSplitMap.emptyCollection.version4.obj" ) ); final Object readObject = in.readObject(); in.close(); final TransformedSplitMap readMap = (TransformedSplitMap) readObject; assertTrue( "Map should be empty", readMap.size() == 0 ); assertEquals( map.entrySet(), readMap.entrySet() ); } public void testFullMap() throws IOException, ClassNotFoundException { final TransformedSplitMap map = TransformedSplitMap.transformingMap( new HashMap(), NOPTransformer.nopTransformer(), NOPTransformer.nopTransformer() ); map.put( "a", "b" ); map.put( "c", "d" ); map.put( "e", "f" ); map.put( "g", "h" ); final ObjectInputStream in = new ObjectInputStream( new FileInputStream( TEST_DATA_PATH+"TransformedSplitMap.fullCollection.version4.obj" ) ); final Object readObject = in.readObject(); in.close(); final TransformedSplitMap readMap = (TransformedSplitMap) readObject; assertFalse( "Map should not be empty", readMap.size() == 0 ); assertEquals( map.entrySet(), readMap.entrySet() ); } // public void testCreate() throws IOException { // TransformedSplitMap map = TransformedSplitMap.transformingMap( // new HashMap(), // NOPTransformer.nopTransformer(), // NOPTransformer.nopTransformer() ); // // ObjectOutputStream out = new ObjectOutputStream( // new FileOutputStream( "src/test/resources/data/test/TransformedSplitMap.emptyCollection.version4.obj" ) ); // out.writeObject( map ); // // map.put( "a", "b" ); // map.put( "c", "d" ); // map.put( "e", "f" ); // map.put( "g", "h" ); // // out = new ObjectOutputStream( // new FileOutputStream( "src/test/resources/data/test/TransformedSplitMap.fullCollection.version4.obj" ) ); // out.writeObject( map ); // } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/AbstractQueueTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/AbstractQueueTest.j100664 27531 12243235516 31730 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.queue; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Queue; import org.apache.commons.collections4.collection.AbstractCollectionTest; /** * Abstract test class for {@link java.util.Queue} methods and contracts. *

* To use, simply extend this class, and implement * the {@link #makeObject} method. *

* If your {@link Queue} fails one of these tests by design, * you may still use this base set of cases. Simply override the * test case (method) your {@link Queue} fails or override one of the * protected methods from AbstractCollectionTest. * * @since 4.0 * @version $Id: AbstractQueueTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractQueueTest extends AbstractCollectionTest { /** * JUnit constructor. * * @param testName the test class name */ public AbstractQueueTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * Returns true if the collections produced by * {@link #makeObject()} 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 queue implementation matches the confirmed queue * implementation. */ @Override public void verify() { super.verify(); final Iterator iterator1 = getCollection().iterator(); for (E e : getConfirmed()) { assertTrue(iterator1.hasNext()); final Object o1 = iterator1.next(); final Object o2 = e; assertEquals(o1, o2); } } //----------------------------------------------------------------------- /** * Returns an empty {@link ArrayList}. */ @Override public Collection makeConfirmedCollection() { final ArrayList list = new ArrayList(); return list; } /** * Returns a full {@link ArrayList}. */ @Override public Collection makeConfirmedFullCollection() { final ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } /** * Returns {@link #makeObject()}. * * @return an empty queue to be used for testing */ @Override public abstract Queue makeObject(); /** * {@inheritDoc} */ @Override public Queue makeFullCollection() { // only works if queue supports optional "addAll(Collection)" final Queue queue = makeObject(); queue.addAll(Arrays.asList(getFullElements())); return queue; } //----------------------------------------------------------------------- /** * Returns the {@link #collection} field cast to a {@link Queue}. * * @return the collection field as a Queue */ @Override public Queue getCollection() { return (Queue) super.getCollection(); } //----------------------------------------------------------------------- /** * Tests {@link Queue#offer(Object)}. */ public void testQueueOffer() { if (!isAddSupported()) { return; } final E[] elements = getFullElements(); for (final E element : elements) { resetEmpty(); final boolean r = getCollection().offer(element); getConfirmed().add(element); verify(); assertTrue("Empty queue changed after add", r); assertEquals("Queue size is 1 after first add", 1, getCollection().size()); } resetEmpty(); int size = 0; for (final E element : elements) { final boolean r = getCollection().offer(element); getConfirmed().add(element); verify(); if (r) { size++; } assertEquals("Queue size should grow after add", size, getCollection().size()); assertTrue("Queue should contain added element", getCollection().contains(element)); } } /** * Tests {@link Queue#element()}. */ public void testQueueElement() { resetEmpty(); try { getCollection().element(); fail("Queue.element should throw NoSuchElementException"); } catch (final NoSuchElementException e) { // expected } resetFull(); assertTrue(getConfirmed().contains(getCollection().element())); if (!isRemoveSupported()) { return; } final int max = getFullElements().length; for (int i = 0; i < max; i++) { final E element = getCollection().element(); if (!isNullSupported()) { assertNotNull(element); } assertTrue(getConfirmed().contains(element)); getCollection().remove(element); getConfirmed().remove(element); verify(); } try { getCollection().element(); fail("Queue.element should throw NoSuchElementException"); } catch (final NoSuchElementException e) { // expected } } /** * Tests {@link Queue#peek()}. */ public void testQueuePeek() { if (!isRemoveSupported()) { return; } resetEmpty(); E element = getCollection().peek(); assertNull(element); resetFull(); final int max = getFullElements().length; for (int i = 0; i < max; i++) { element = getCollection().peek(); if (!isNullSupported()) { assertNotNull(element); } assertTrue(getConfirmed().contains(element)); getCollection().remove(element); getConfirmed().remove(element); verify(); } element = getCollection().peek(); assertNull(element); } /** * Tests {@link Queue#remove()}. */ public void testQueueRemove() { if (!isRemoveSupported()) { return; } resetEmpty(); try { getCollection().remove(); fail("Queue.remove should throw NoSuchElementException"); } catch (final NoSuchElementException e) { // expected } resetFull(); final int max = getFullElements().length; for (int i = 0; i < max; i++) { final E element = getCollection().remove(); final boolean success = getConfirmed().remove(element); assertTrue("remove should return correct element", success); verify(); } try { getCollection().element(); fail("Queue.remove should throw NoSuchElementException"); } catch (final NoSuchElementException e) { // expected } } /** * Tests {@link Queue#poll()}. */ public void testQueuePoll() { if (!isRemoveSupported()) { return; } resetEmpty(); E element = getCollection().poll(); assertNull(element); resetFull(); final int max = getFullElements().length; for (int i = 0; i < max; i++) { element = getCollection().poll(); final boolean success = getConfirmed().remove(element); assertTrue("poll should return correct element", success); verify(); } element = getCollection().poll(); assertNull(element); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testEmptyQueueSerialization() throws IOException, ClassNotFoundException { final Queue queue = makeObject(); if (!(queue instanceof Serializable && isTestSerialization())) { return; } final byte[] objekt = writeExternalFormToBytes((Serializable) queue); final Queue queue2 = (Queue) readExternalFormFromBytes(objekt); assertEquals("Both queues are empty", 0, queue.size()); assertEquals("Both queues are empty", 0, queue2.size()); } @SuppressWarnings("unchecked") public void testFullQueueSerialization() throws IOException, ClassNotFoundException { final Queue queue = makeFullCollection(); final int size = getFullElements().length; if (!(queue instanceof Serializable && isTestSerialization())) { return; } final byte[] objekt = writeExternalFormToBytes((Serializable) queue); final Queue queue2 = (Queue) readExternalFormFromBytes(objekt); assertEquals("Both queues are same size", size, queue.size()); assertEquals("Both queues are same size", size, queue2.size()); } /** * Compare the current serialized form of the Queue * against the canonical version in SVN. */ @SuppressWarnings("unchecked") public void testEmptyQueueCompatibility() throws IOException, ClassNotFoundException { /** * Create canonical objects with this code Queue queue = makeEmptyQueue(); if (!(queue instanceof Serializable)) return; writeExternalFormToDisk((Serializable) queue, getCanonicalEmptyCollectionName(queue)); */ // test to make sure the canonical form has been preserved final Queue queue = makeObject(); if (queue instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final Queue queue2 = (Queue) readExternalFormFromDisk(getCanonicalEmptyCollectionName(queue)); assertEquals("Queue is empty", 0, queue2.size()); } } /** * Compare the current serialized form of the Queue * against the canonical version in SVN. */ @SuppressWarnings("unchecked") public void testFullQueueCompatibility() throws IOException, ClassNotFoundException { /** * Create canonical objects with this code Queue queue = makeFullQueue(); if (!(queue instanceof Serializable)) return; writeExternalFormToDisk((Serializable) queue, getCanonicalFullCollectionName(queue)); */ // test to make sure the canonical form has been preserved final Queue queue = makeFullCollection(); if(queue instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final Queue queue2 = (Queue) readExternalFormFromDisk(getCanonicalFullCollectionName(queue)); assertEquals("Queues are not the right size", queue.size(), queue2.size()); } } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/PredicatedQueueTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/PredicatedQueueTest100664 7602 12243235516 31756 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.queue; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Queue; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.collection.PredicatedCollectionTest; import org.apache.commons.collections4.functors.TruePredicate; /** * Extension of {@link PredicatedCollectionTest} for exercising the * {@link PredicatedQueue} implementation. * * @since 4.0 * @version $Id: PredicatedQueueTest.java 1543250 2013-11-19 00:40:27Z ggregory $ */ public class PredicatedQueueTest extends AbstractQueueTest { public PredicatedQueueTest(final String testName) { super(testName); } //--------------------------------------------------------------- protected Predicate truePredicate = TruePredicate.truePredicate(); protected Queue decorateCollection(final Queue queue, final Predicate predicate) { return PredicatedQueue.predicatedQueue(queue, predicate); } @Override public Queue makeObject() { return decorateCollection(new LinkedList(), truePredicate); } @Override public Queue makeFullCollection() { final Queue queue = new LinkedList(); queue.addAll(Arrays.asList(getFullElements())); return decorateCollection(queue, truePredicate); } @Override public Collection makeConfirmedCollection() { return new LinkedList(); } @Override public Collection makeConfirmedFullCollection() { final List list = new LinkedList(); list.addAll(Arrays.asList(getFullElements())); return list; } //------------------------------------------------------------ protected Predicate testPredicate = new Predicate() { public boolean evaluate(final E o) { return o instanceof String; } }; public Queue makeTestQueue() { return decorateCollection(new LinkedList(), testPredicate); } @SuppressWarnings("unchecked") public void testGet() { final Queue queue = makeTestQueue(); assertNull(queue.peek()); queue.add((E) "one"); queue.add((E) "two"); queue.add((E) "three"); assertEquals("Queue get", "one", queue.peek()); } @SuppressWarnings("unchecked") public void testRemove() { final Queue queue = makeTestQueue(); queue.add((E) "one"); assertEquals("Queue get", "one", queue.poll()); assertNull(queue.peek()); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/PredicatedQueue.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/PredicatedQueue.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/TransformedQueueTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/TransformedQueueTes100664 11076 12243235516 32032 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.queue; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.Queue; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.collection.AbstractCollectionTest; import org.apache.commons.collections4.collection.TransformedCollectionTest; /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link TransformedQueue} implementation. * * @since 4.0 * @version $Id: TransformedQueueTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class TransformedQueueTest extends AbstractQueueTest { public TransformedQueueTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public Queue makeConfirmedCollection() { return new LinkedList(); } @Override public Queue makeConfirmedFullCollection() { final Queue list = new LinkedList(); list.addAll(Arrays.asList(getFullElements())); return list; } @Override @SuppressWarnings("unchecked") public Queue makeObject() { return TransformedQueue.transformingQueue(new LinkedList(), (Transformer) TransformedCollectionTest.NOOP_TRANSFORMER); } @Override @SuppressWarnings("unchecked") public Queue makeFullCollection() { final Queue list = new LinkedList(); list.addAll(Arrays.asList(getFullElements())); return TransformedQueue.transformingQueue(list, (Transformer) TransformedCollectionTest.NOOP_TRANSFORMER); } //----------------------------------------------------------------------- public void testTransformedQueue() { final Queue queue = TransformedQueue.transformingQueue(new LinkedList(), TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, queue.size()); final Object[] elements = new Object[] { "1", "3", "5", "7", "2", "4", "6" }; for (int i = 0; i < elements.length; i++) { queue.add(elements[i]); assertEquals(i + 1, queue.size()); assertEquals(true, queue.contains(Integer.valueOf((String) elements[i]))); assertEquals(false, queue.contains(elements[i])); } assertEquals(false, queue.remove(elements[0])); assertEquals(true, queue.remove(Integer.valueOf((String) elements[0]))); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void testTransformedQueue_decorateTransform() { final Queue originalQueue = new LinkedList(); final Object[] elements = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; Collections.addAll(originalQueue, elements); final Queue queue = TransformedQueue.transformedQueue(originalQueue, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(elements.length, queue.size()); for (final Object el : elements) { assertEquals(true, queue.contains(Integer.valueOf((String) el))); assertEquals(false, queue.contains(el)); } assertEquals(false, queue.remove(elements[0])); assertEquals(true, queue.remove(Integer.valueOf((String) elements[0]))); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/TransformedQueue.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/TransformedQueue.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/CircularFifoQueueTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/CircularFifoQueueTe100664 33341 12243235516 31732 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.queue; 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 java.util.NoSuchElementException; import java.util.Queue; /** * Test cases for CircularFifoQueue. * * @since 4.0 * @version $Id: CircularFifoQueueTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class CircularFifoQueueTest extends AbstractQueueTest { public CircularFifoQueueTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * Runs through the regular verifications, but also verifies that * the buffer contains the same elements in the same sequence as the * list. */ @Override public void verify() { super.verify(); final Iterator iterator1 = getCollection().iterator(); for (E e : getConfirmed()) { assertTrue(iterator1.hasNext()); final Object o1 = iterator1.next(); final Object o2 = e; assertEquals(o1, o2); } } //----------------------------------------------------------------------- /** * Overridden because CircularFifoQueue doesn't allow null elements. * @return false */ @Override public boolean isNullSupported() { return false; } /** * Overridden because CircularFifoQueue isn't fail fast. * @return false */ @Override public boolean isFailFastSupported() { return false; } //----------------------------------------------------------------------- /** * Returns an empty ArrayList. * * @return an empty ArrayList */ @Override public Collection makeConfirmedCollection() { return new ArrayList(); } /** * Returns a full ArrayList. * * @return a full ArrayList */ @Override public Collection makeConfirmedFullCollection() { final Collection c = makeConfirmedCollection(); c.addAll(java.util.Arrays.asList(getFullElements())); return c; } /** * Returns an empty CircularFifoQueue that won't overflow. * * @return an empty CircularFifoQueue */ @Override public Queue makeObject() { return new CircularFifoQueue(100); } //----------------------------------------------------------------------- /** * Tests that the removal operation actually removes the first element. */ @SuppressWarnings("unchecked") public void testCircularFifoQueueCircular() { final List list = new ArrayList(); list.add((E) "A"); list.add((E) "B"); list.add((E) "C"); final Queue queue = new CircularFifoQueue(list); assertEquals(true, queue.contains("A")); assertEquals(true, queue.contains("B")); assertEquals(true, queue.contains("C")); queue.add((E) "D"); assertEquals(false, queue.contains("A")); assertEquals(true, queue.contains("B")); assertEquals(true, queue.contains("C")); assertEquals(true, queue.contains("D")); assertEquals("B", queue.peek()); assertEquals("B", queue.remove()); assertEquals("C", queue.remove()); assertEquals("D", queue.remove()); } /** * Tests that the removal operation actually removes the first element. */ public void testCircularFifoQueueRemove() { resetFull(); final int size = getConfirmed().size(); for (int i = 0; i < size; i++) { final Object o1 = getCollection().remove(); final Object o2 = ((List) getConfirmed()).remove(0); assertEquals("Removed objects should be equal", o1, o2); verify(); } try { getCollection().remove(); fail("Empty queue should raise Underflow."); } catch (final NoSuchElementException e) { // expected } } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException1() { try { new CircularFifoQueue(0); } catch (final IllegalArgumentException ex) { return; } fail(); } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException2() { try { new CircularFifoQueue(-20); } catch (final IllegalArgumentException ex) { return; } fail(); } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException3() { try { new CircularFifoQueue(null); } catch (final NullPointerException ex) { return; } fail(); } @SuppressWarnings("unchecked") public void testRemoveError1() throws Exception { // based on bug 33071 final CircularFifoQueue fifo = new CircularFifoQueue(5); fifo.add((E) "1"); fifo.add((E) "2"); fifo.add((E) "3"); fifo.add((E) "4"); fifo.add((E) "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()); } @SuppressWarnings("unchecked") public void testRemoveError2() throws Exception { // based on bug 33071 final CircularFifoQueue fifo = new CircularFifoQueue(5); fifo.add((E) "1"); fifo.add((E) "2"); fifo.add((E) "3"); fifo.add((E) "4"); fifo.add((E) "5"); fifo.add((E) "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()); } @SuppressWarnings("unchecked") public void testRemoveError3() throws Exception { // based on bug 33071 final CircularFifoQueue fifo = new CircularFifoQueue(5); fifo.add((E) "1"); fifo.add((E) "2"); fifo.add((E) "3"); fifo.add((E) "4"); fifo.add((E) "5"); assertEquals("[1, 2, 3, 4, 5]", fifo.toString()); fifo.remove("3"); assertEquals("[1, 2, 4, 5]", fifo.toString()); fifo.add((E) "6"); fifo.add((E) "7"); assertEquals("[2, 4, 5, 6, 7]", fifo.toString()); fifo.remove("4"); assertEquals("[2, 5, 6, 7]", fifo.toString()); } @SuppressWarnings("unchecked") public void testRemoveError4() throws Exception { // based on bug 33071 final CircularFifoQueue fifo = new CircularFifoQueue(5); fifo.add((E) "1"); fifo.add((E) "2"); fifo.add((E) "3"); fifo.add((E) "4"); fifo.add((E) "5"); // end=0 fifo.add((E) "6"); // end=1 fifo.add((E) "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()); } @SuppressWarnings("unchecked") public void testRemoveError5() throws Exception { // based on bug 33071 final CircularFifoQueue fifo = new CircularFifoQueue(5); fifo.add((E) "1"); fifo.add((E) "2"); fifo.add((E) "3"); fifo.add((E) "4"); fifo.add((E) "5"); // end=0 fifo.add((E) "6"); // end=1 fifo.add((E) "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()); } @SuppressWarnings("unchecked") public void testRemoveError6() throws Exception { // based on bug 33071 final CircularFifoQueue fifo = new CircularFifoQueue(5); fifo.add((E) "1"); fifo.add((E) "2"); fifo.add((E) "3"); fifo.add((E) "4"); fifo.add((E) "5"); // end=0 fifo.add((E) "6"); // end=1 fifo.add((E) "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()); } @SuppressWarnings("unchecked") public void testRemoveError7() throws Exception { // based on bug 33071 final CircularFifoQueue fifo = new CircularFifoQueue(5); fifo.add((E) "1"); fifo.add((E) "2"); fifo.add((E) "3"); fifo.add((E) "4"); fifo.add((E) "5"); // end=0 fifo.add((E) "6"); // end=1 fifo.add((E) "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()); } @SuppressWarnings("unchecked") public void testRemoveError8() throws Exception { // based on bug 33071 final CircularFifoQueue fifo = new CircularFifoQueue(5); fifo.add((E) "1"); fifo.add((E) "2"); fifo.add((E) "3"); fifo.add((E) "4"); fifo.add((E) "5"); // end=0 fifo.add((E) "6"); // end=1 fifo.add((E) "7"); // end=2 fifo.add((E) "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()); } @SuppressWarnings("unchecked") public void testRemoveError9() throws Exception { // based on bug 33071 final CircularFifoQueue fifo = new CircularFifoQueue(5); fifo.add((E) "1"); fifo.add((E) "2"); fifo.add((E) "3"); fifo.add((E) "4"); fifo.add((E) "5"); // end=0 fifo.add((E) "6"); // end=1 fifo.add((E) "7"); // end=2 fifo.add((E) "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()); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testRepeatedSerialization() throws Exception { // bug 31433 final CircularFifoQueue b = new CircularFifoQueue(2); b.add((E) "a"); assertEquals(1, b.size()); assertEquals(true, b.contains("a")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); new ObjectOutputStream(bos).writeObject(b); final CircularFifoQueue b2 = (CircularFifoQueue) new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())).readObject(); assertEquals(1, b2.size()); assertEquals(true, b2.contains("a")); b2.add((E) "b"); assertEquals(2, b2.size()); assertEquals(true, b2.contains("a")); assertEquals(true, b2.contains("b")); bos = new ByteArrayOutputStream(); new ObjectOutputStream(bos).writeObject(b2); final CircularFifoQueue b3 = (CircularFifoQueue) new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())).readObject(); assertEquals(2, b3.size()); assertEquals(true, b3.contains("a")); assertEquals(true, b3.contains("b")); b3.add((E) "c"); assertEquals(2, b3.size()); assertEquals(true, b3.contains("b")); assertEquals(true, b3.contains("c")); } public void testGetIndex() { resetFull(); final CircularFifoQueue queue = getCollection(); final List confirmed = (List) getConfirmed(); for (int i = 0; i < confirmed.size(); i++) { assertEquals(confirmed.get(i), queue.get(i)); } // remove the first two elements and check again queue.remove(); queue.remove(); for (int i = 0; i < queue.size(); i++) { assertEquals(confirmed.get(i + 2), queue.get(i)); } } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CircularFifoQueue.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CircularFifoQueue.fullCollection.version4.obj"); // } /** * {@inheritDoc} */ @Override public CircularFifoQueue getCollection() { return (CircularFifoQueue) super.getCollection(); } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/UnmodifiableQueueTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/queue/UnmodifiableQueueTe100664 7527 12243235516 31747 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.queue; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.Queue; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.collection.AbstractCollectionTest; /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link UnmodifiableQueue} implementation. * * @since 4.0 * @version $Id: UnmodifiableQueueTest.java 1543168 2013-11-18 21:22:43Z ggregory $ */ public class UnmodifiableQueueTest extends AbstractQueueTest { public UnmodifiableQueueTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public Queue makeObject() { return UnmodifiableQueue.unmodifiableQueue(new LinkedList()); } @Override public Queue makeFullCollection() { final Queue queue = new LinkedList(); queue.addAll(Arrays.asList(getFullElements())); return UnmodifiableQueue.unmodifiableQueue(queue); } @Override public Collection makeConfirmedCollection() { return new LinkedList(); } @Override public Collection makeConfirmedFullCollection() { final LinkedList list = new LinkedList(); list.addAll(Arrays.asList(getFullElements())); return list; } @Override public Queue getCollection() { return super.getCollection(); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public boolean isNullSupported() { return false; } //----------------------------------------------------------------------- @Override public void testQueueRemove() { resetEmpty(); try { getCollection().remove(); fail(); } catch (final UnsupportedOperationException ex) {} } public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullCollection() instanceof Unmodifiable); } public void testDecorateFactory() { final Queue queue = makeFullCollection(); assertSame(queue, UnmodifiableQueue.unmodifiableQueue(queue)); try { UnmodifiableQueue.unmodifiableQueue(null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableQueue.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableQueue.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/sequence/SequencesComparatorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/sequence/SequencesCompara100664 16500 12243235516 32004 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.sequence; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class SequencesComparatorTest { private List before; private List after; private int[] length; @Test public void testLength() { for (int i = 0; i < before.size(); ++i) { final SequencesComparator comparator = new SequencesComparator(sequence(before.get(i)), sequence(after.get(i))); Assert.assertEquals(length[i], comparator.getScript().getModifications()); } } @Test public void testExecution() { final ExecutionVisitor ev = new ExecutionVisitor(); for (int i = 0; i < before.size(); ++i) { ev.setList(sequence(before.get(i))); new SequencesComparator(sequence(before.get(i)), sequence(after.get(i))).getScript().visit(ev); Assert.assertEquals(after.get(i), ev.getString()); } } @Test public void testMinimal() { final String[] shadokAlph = new String[] { new String("GA"), new String("BU"), new String("ZO"), new String("MEU") }; final List sentenceBefore = new ArrayList(); final List sentenceAfter = new ArrayList(); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[2]); sentenceBefore.add(shadokAlph[3]); sentenceBefore.add(shadokAlph[1]); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[2]); sentenceBefore.add(shadokAlph[1]); sentenceBefore.add(shadokAlph[3]); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[2]); sentenceBefore.add(shadokAlph[1]); sentenceBefore.add(shadokAlph[3]); sentenceBefore.add(shadokAlph[2]); sentenceBefore.add(shadokAlph[2]); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[1]); sentenceBefore.add(shadokAlph[3]); sentenceBefore.add(shadokAlph[0]); sentenceBefore.add(shadokAlph[3]); final Random random = new Random(4564634237452342L); for (int nbCom = 0; nbCom <= 40; nbCom+=5) { sentenceAfter.clear(); sentenceAfter.addAll(sentenceBefore); for (int i = 0; i comparator = new SequencesComparator(sentenceBefore, sentenceAfter); Assert.assertTrue(comparator.getScript().getModifications() <= nbCom); } } @Test public void testShadok() { final int lgMax = 5; final String[] shadokAlph = new String[] { new String("GA"), new String("BU"), new String("ZO"), new String("MEU") }; List> shadokSentences = new ArrayList>(); for (int lg=0; lg> newTab = new ArrayList>(); newTab.add(new ArrayList()); for (final String element : shadokAlph) { for (final List sentence : shadokSentences) { final List newSentence = new ArrayList(sentence); newSentence.add(element); newTab.add(newSentence); } } shadokSentences = newTab; } final ExecutionVisitor ev = new ExecutionVisitor(); for (int i = 0; i < shadokSentences.size(); ++i) { for (List shadokSentence : shadokSentences) { ev.setList(shadokSentences.get(i)); new SequencesComparator(shadokSentences.get(i), shadokSentence).getScript().visit(ev); final StringBuilder concat = new StringBuilder(); for (final String s : shadokSentence) { concat.append(s); } Assert.assertEquals(concat.toString(), ev.getString()); } } } private List sequence(final String string) { final List list = new ArrayList(); for (int i = 0; i < string.length(); ++i) { list.add(new Character(string.charAt(i))); } return list; } private class ExecutionVisitor implements CommandVisitor { private List v; private int index; public void setList(final List array) { v = new ArrayList(array); index = 0; } public void visitInsertCommand(final T object) { v.add(index++, object); } public void visitKeepCommand(final T object) { ++index; } public void visitDeleteCommand(final T object) { v.remove(index); } public String getString() { final StringBuilder buffer = new StringBuilder(); for (final T c : v) { buffer.append(c); } return buffer.toString(); } } @Before public void setUp() { before = Arrays.asList( "bottle", "nematode knowledge", "", "aa", "prefixed string", "ABCABBA", "glop glop", "coq", "spider-man"); after = Arrays.asList( "noodle", "empty bottle", "", "C", "prefix", "CBABAC", "pas glop pas glop", "ane", "klingon"); length = new int[] { 6, 16, 0, 3, 9, 5, 8, 6, 13 }; } @After public void tearDown() { before = null; after = null; length = null; } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/MapPerformance.java100664 13736 12243235516 30565 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.map.Flat3Map; /** * MapPerformanceTest is designed to perform basic Map performance tests. * * @version $Id: MapPerformance.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class MapPerformance { /** The total number of runs for each test */ private static final int RUNS = 20000000; /** * Main method */ public static void main(final String[] args) { testAll(); } private static void testAll() { final Map dummyMap = new DummyMap(); final Map hashMap = new HashMap(); // hashMap.put("Alpha", "A"); // hashMap.put("Beta", "B"); // hashMap.put("Gamma", "C"); // hashMap.put("Delta", "D"); final 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 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(final Map map, final 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(final Object key) { return false; } public boolean containsValue(final Object value) { return false; } public Set> entrySet() { return null; } public V get(final Object key) { return null; } public boolean isEmpty() { return false; } public Set keySet() { return null; } public V put(final K key, final V value) { return null; } public void putAll(final Map t) { } public V remove(final Object key) { return null; } public int size() { return 0; } public Collection values() { return null; } } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/trie/UnmodifiableTrieTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/trie/UnmodifiableTrieTest100664 7633 12243235516 31752 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.trie; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.Trie; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.map.AbstractSortedMapTest; /** * Extension of {@link AbstractSortedMapTest} for exercising the * {@link UnmodifiableTrie} implementation. * * @since 4.0 * @version $Id: UnmodifiableTrieTest.java 1542074 2013-11-14 20:57:02Z tn $ */ public class UnmodifiableTrieTest extends AbstractSortedMapTest { public UnmodifiableTrieTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(UnmodifiableTrieTest.class); } //------------------------------------------------------------------- @Override public Trie makeObject() { return UnmodifiableTrie.unmodifiableTrie(new PatriciaTrie()); } @Override public boolean isPutChangeSupported() { return false; } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public Trie makeFullMap() { final Trie m = new PatriciaTrie(); addSampleMappings(m); return UnmodifiableTrie.unmodifiableTrie(m); } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { final Trie trie = makeFullMap(); assertSame(trie, UnmodifiableTrie.unmodifiableTrie(trie)); try { UnmodifiableTrie.unmodifiableTrie(null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- /** * Override to prevent infinite recursion of tests. */ @Override public String[] ignoredTests() { if (IBMJDK16) { final String prefix = "UnmodifiableTrieTest."; return new String[] { prefix + "bulkTestHeadMap.bulkTestMapEntrySet.testCollectionToArray2", prefix + "bulkTestTailMap.bulkTestMapEntrySet.testCollectionToArray2", prefix + "bulkTestSubMap.bulkTestMapEntrySet.testCollectionToArray2" }; } else { return null; } } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/UnmodifiableTrie.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/UnmodifiableTrie.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/trie/PatriciaTrieTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/trie/PatriciaTrieTest.jav100775 33300 12243235516 31700 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.trie; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.SortedMap; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.map.AbstractSortedMapTest; import org.junit.Assert; /** * JUnit tests for the PatriciaTrie. * * @since 4.0 * @version $Id: PatriciaTrieTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class PatriciaTrieTest extends AbstractSortedMapTest { public PatriciaTrieTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(PatriciaTrieTest.class); } @Override public SortedMap makeObject() { return new PatriciaTrie(); } @Override public boolean isAllowNullKey() { return false; } //----------------------------------------------------------------------- public void testPrefixMap() { final PatriciaTrie trie = new PatriciaTrie(); final String[] keys = new String[]{ "", "Albert", "Xavier", "XyZ", "Anna", "Alien", "Alberto", "Alberts", "Allie", "Alliese", "Alabama", "Banane", "Blabla", "Amber", "Ammun", "Akka", "Akko", "Albertoo", "Amma" }; for (final String key : keys) { trie.put(key, key); } SortedMap map; Iterator iterator; Iterator> entryIterator; Map.Entry entry; map = trie.prefixMap("Al"); Assert.assertEquals(8, map.size()); Assert.assertEquals("Alabama", map.firstKey()); Assert.assertEquals("Alliese", map.lastKey()); Assert.assertEquals("Albertoo", map.get("Albertoo")); Assert.assertNotNull(trie.get("Xavier")); Assert.assertNull(map.get("Xavier")); Assert.assertNull(trie.get("Alice")); Assert.assertNull(map.get("Alice")); iterator = map.values().iterator(); Assert.assertEquals("Alabama", iterator.next()); Assert.assertEquals("Albert", iterator.next()); Assert.assertEquals("Alberto", iterator.next()); Assert.assertEquals("Albertoo", iterator.next()); Assert.assertEquals("Alberts", iterator.next()); Assert.assertEquals("Alien", iterator.next()); Assert.assertEquals("Allie", iterator.next()); Assert.assertEquals("Alliese", iterator.next()); Assert.assertFalse(iterator.hasNext()); map = trie.prefixMap("Albert"); iterator = map.keySet().iterator(); Assert.assertEquals("Albert", iterator.next()); Assert.assertEquals("Alberto", iterator.next()); Assert.assertEquals("Albertoo", iterator.next()); Assert.assertEquals("Alberts", iterator.next()); Assert.assertFalse(iterator.hasNext()); Assert.assertEquals(4, map.size()); Assert.assertEquals("Albert", map.firstKey()); Assert.assertEquals("Alberts", map.lastKey()); Assert.assertNull(trie.get("Albertz")); map.put("Albertz", "Albertz"); Assert.assertEquals("Albertz", trie.get("Albertz")); Assert.assertEquals(5, map.size()); Assert.assertEquals("Albertz", map.lastKey()); iterator = map.keySet().iterator(); Assert.assertEquals("Albert", iterator.next()); Assert.assertEquals("Alberto", iterator.next()); Assert.assertEquals("Albertoo", iterator.next()); Assert.assertEquals("Alberts", iterator.next()); Assert.assertEquals("Albertz", iterator.next()); Assert.assertFalse(iterator.hasNext()); Assert.assertEquals("Albertz", map.remove("Albertz")); map = trie.prefixMap("Alberto"); Assert.assertEquals(2, map.size()); Assert.assertEquals("Alberto", map.firstKey()); Assert.assertEquals("Albertoo", map.lastKey()); entryIterator = map.entrySet().iterator(); entry = entryIterator.next(); Assert.assertEquals("Alberto", entry.getKey()); Assert.assertEquals("Alberto", entry.getValue()); entry = entryIterator.next(); Assert.assertEquals("Albertoo", entry.getKey()); Assert.assertEquals("Albertoo", entry.getValue()); Assert.assertFalse(entryIterator.hasNext()); trie.put("Albertoad", "Albertoad"); Assert.assertEquals(3, map.size()); Assert.assertEquals("Alberto", map.firstKey()); Assert.assertEquals("Albertoo", map.lastKey()); entryIterator = map.entrySet().iterator(); entry = entryIterator.next(); Assert.assertEquals("Alberto", entry.getKey()); Assert.assertEquals("Alberto", entry.getValue()); entry = entryIterator.next(); Assert.assertEquals("Albertoad", entry.getKey()); Assert.assertEquals("Albertoad", entry.getValue()); entry = entryIterator.next(); Assert.assertEquals("Albertoo", entry.getKey()); Assert.assertEquals("Albertoo", entry.getValue()); Assert.assertFalse(entryIterator.hasNext()); Assert.assertEquals("Albertoo", trie.remove("Albertoo")); Assert.assertEquals("Alberto", map.firstKey()); Assert.assertEquals("Albertoad", map.lastKey()); Assert.assertEquals(2, map.size()); entryIterator = map.entrySet().iterator(); entry = entryIterator.next(); Assert.assertEquals("Alberto", entry.getKey()); Assert.assertEquals("Alberto", entry.getValue()); entry = entryIterator.next(); Assert.assertEquals("Albertoad", entry.getKey()); Assert.assertEquals("Albertoad", entry.getValue()); Assert.assertFalse(entryIterator.hasNext()); Assert.assertEquals("Albertoad", trie.remove("Albertoad")); trie.put("Albertoo", "Albertoo"); map = trie.prefixMap("X"); Assert.assertEquals(2, map.size()); Assert.assertFalse(map.containsKey("Albert")); Assert.assertTrue(map.containsKey("Xavier")); Assert.assertFalse(map.containsKey("Xalan")); iterator = map.values().iterator(); Assert.assertEquals("Xavier", iterator.next()); Assert.assertEquals("XyZ", iterator.next()); Assert.assertFalse(iterator.hasNext()); map = trie.prefixMap("An"); Assert.assertEquals(1, map.size()); Assert.assertEquals("Anna", map.firstKey()); Assert.assertEquals("Anna", map.lastKey()); iterator = map.keySet().iterator(); Assert.assertEquals("Anna", iterator.next()); Assert.assertFalse(iterator.hasNext()); map = trie.prefixMap("Ban"); Assert.assertEquals(1, map.size()); Assert.assertEquals("Banane", map.firstKey()); Assert.assertEquals("Banane", map.lastKey()); iterator = map.keySet().iterator(); Assert.assertEquals("Banane", iterator.next()); Assert.assertFalse(iterator.hasNext()); map = trie.prefixMap("Am"); Assert.assertFalse(map.isEmpty()); Assert.assertEquals(3, map.size()); Assert.assertEquals("Amber", trie.remove("Amber")); iterator = map.keySet().iterator(); Assert.assertEquals("Amma", iterator.next()); Assert.assertEquals("Ammun", iterator.next()); Assert.assertFalse(iterator.hasNext()); iterator = map.keySet().iterator(); map.put("Amber", "Amber"); Assert.assertEquals(3, map.size()); try { iterator.next(); Assert.fail("CME expected"); } catch(final ConcurrentModificationException expected) {} Assert.assertEquals("Amber", map.firstKey()); Assert.assertEquals("Ammun", map.lastKey()); map = trie.prefixMap("Ak\0"); Assert.assertTrue(map.isEmpty()); map = trie.prefixMap("Ak"); Assert.assertEquals(2, map.size()); Assert.assertEquals("Akka", map.firstKey()); Assert.assertEquals("Akko", map.lastKey()); map.put("Ak", "Ak"); Assert.assertEquals("Ak", map.firstKey()); Assert.assertEquals("Akko", map.lastKey()); Assert.assertEquals(3, map.size()); trie.put("Al", "Al"); Assert.assertEquals(3, map.size()); Assert.assertEquals("Ak", map.remove("Ak")); Assert.assertEquals("Akka", map.firstKey()); Assert.assertEquals("Akko", map.lastKey()); Assert.assertEquals(2, map.size()); iterator = map.keySet().iterator(); Assert.assertEquals("Akka", iterator.next()); Assert.assertEquals("Akko", iterator.next()); Assert.assertFalse(iterator.hasNext()); Assert.assertEquals("Al", trie.remove("Al")); map = trie.prefixMap("Akka"); Assert.assertEquals(1, map.size()); Assert.assertEquals("Akka", map.firstKey()); Assert.assertEquals("Akka", map.lastKey()); iterator = map.keySet().iterator(); Assert.assertEquals("Akka", iterator.next()); Assert.assertFalse(iterator.hasNext()); map = trie.prefixMap("Ab"); Assert.assertTrue(map.isEmpty()); Assert.assertEquals(0, map.size()); try { final Object o = map.firstKey(); Assert.fail("got a first key: " + o); } catch(final NoSuchElementException nsee) {} try { final Object o = map.lastKey(); Assert.fail("got a last key: " + o); } catch(final NoSuchElementException nsee) {} iterator = map.values().iterator(); Assert.assertFalse(iterator.hasNext()); map = trie.prefixMap("Albertooo"); Assert.assertTrue(map.isEmpty()); Assert.assertEquals(0, map.size()); try { final Object o = map.firstKey(); Assert.fail("got a first key: " + o); } catch(final NoSuchElementException nsee) {} try { final Object o = map.lastKey(); Assert.fail("got a last key: " + o); } catch(final NoSuchElementException nsee) {} iterator = map.values().iterator(); Assert.assertFalse(iterator.hasNext()); map = trie.prefixMap(""); Assert.assertSame(trie, map); // stricter than necessary, but a good check map = trie.prefixMap("\0"); Assert.assertTrue(map.isEmpty()); Assert.assertEquals(0, map.size()); try { final Object o = map.firstKey(); Assert.fail("got a first key: " + o); } catch(final NoSuchElementException nsee) {} try { final Object o = map.lastKey(); Assert.fail("got a last key: " + o); } catch(final NoSuchElementException nsee) {} iterator = map.values().iterator(); Assert.assertFalse(iterator.hasNext()); } public void testPrefixMapRemoval() { final PatriciaTrie trie = new PatriciaTrie(); final String[] keys = new String[]{ "Albert", "Xavier", "XyZ", "Anna", "Alien", "Alberto", "Alberts", "Allie", "Alliese", "Alabama", "Banane", "Blabla", "Amber", "Ammun", "Akka", "Akko", "Albertoo", "Amma" }; for (final String key : keys) { trie.put(key, key); } SortedMap map = trie.prefixMap("Al"); Assert.assertEquals(8, map.size()); Iterator iter = map.keySet().iterator(); Assert.assertEquals("Alabama", iter.next()); Assert.assertEquals("Albert", iter.next()); Assert.assertEquals("Alberto", iter.next()); Assert.assertEquals("Albertoo", iter.next()); Assert.assertEquals("Alberts", iter.next()); Assert.assertEquals("Alien", iter.next()); iter.remove(); Assert.assertEquals(7, map.size()); Assert.assertEquals("Allie", iter.next()); Assert.assertEquals("Alliese", iter.next()); Assert.assertFalse(iter.hasNext()); map = trie.prefixMap("Ak"); Assert.assertEquals(2, map.size()); iter = map.keySet().iterator(); Assert.assertEquals("Akka", iter.next()); iter.remove(); Assert.assertEquals(1, map.size()); Assert.assertEquals("Akko", iter.next()); if(iter.hasNext()) { Assert.fail("shouldn't have next (but was: " + iter.next() + ")"); } Assert.assertFalse(iter.hasNext()); } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/PatriciaTrie.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/PatriciaTrie.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/trie/PatriciaTrie2Test.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/trie/PatriciaTrie2Test.ja100664 3445 12243235516 31560 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.trie; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.map.AbstractOrderedMapTest; /** * JUnit test of the OrderedMap interface of a PatriciaTrie. * * @since 4.0 * @version $Id: PatriciaTrie2Test.java 1492866 2013-06-13 21:01:00Z tn $ */ public class PatriciaTrie2Test extends AbstractOrderedMapTest { public PatriciaTrie2Test(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(PatriciaTrie2Test.class); } @Override public OrderedMap makeObject() { return new PatriciaTrie(); } @Override public boolean isAllowNullKey() { return false; } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/AbstractObjectTest.java100664 30017 12243235516 31407 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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 $Id: AbstractObjectTest.java 1477661 2013-04-30 14:27:35Z sebb $ */ public abstract class AbstractObjectTest extends BulkTest { /** Current major release for Collections */ public static final int COLLECTIONS_MAJOR_VERSION = 4; /** * JUnit constructor. * * @param testName the test class name */ public AbstractObjectTest(final 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() { final Object obj = makeObject(); assertEquals("A Object should equal itself", obj, obj); } public void testEqualsNull() { final Object obj = makeObject(); assertEquals(false, obj.equals(null)); // make sure this doesn't throw NPE either } public void testObjectHashCodeEqualsSelfHashCode() { final Object obj = makeObject(); assertEquals("hashCode should be repeatable", obj.hashCode(), obj.hashCode()); } public void testObjectHashCodeEqualsContract() { final Object obj1 = makeObject(); if (obj1.equals(obj1)) { assertEquals( "[1] When two objects are equal, their hashCodes should be also.", obj1.hashCode(), obj1.hashCode()); } final 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)); } } protected Object serializeDeserialize(final Object obj) throws Exception { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(obj); out.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); final Object dest = in.readObject(); in.close(); return dest; } public void testSerializeDeserializeThenCompare() throws Exception { final Object obj = makeObject(); if (obj instanceof Serializable && isTestSerialization()) { final Object dest = serializeDeserialize(obj); 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 { final Object o = makeObject(); if (o instanceof Serializable && isTestSerialization()) { final byte[] objekt = writeExternalFormToBytes((Serializable) o); readExternalFormFromBytes(objekt); } } /** * Tests serialization by comparing against a previously stored version in SVN. * If the test object is serializable, confirm that a canonical form exists. */ public void testCanonicalEmptyCollectionExists() { if (supportsEmptyCollections() && isTestSerialization() && !skipSerializedCanonicalTests()) { final Object object = makeObject(); if (object instanceof Serializable) { final String name = getCanonicalEmptyCollectionName(object); assertTrue( "Canonical empty collection (" + name + ") is not in SVN", new File(name).exists()); } } } /** * Tests serialization by comparing against a previously stored version in SVN. * If the test object is serializable, confirm that a canonical form exists. */ public void testCanonicalFullCollectionExists() { if (supportsFullCollections() && isTestSerialization() && !skipSerializedCanonicalTests()) { final Object object = makeObject(); if (object instanceof Serializable) { final String name = getCanonicalFullCollectionName(object); assertTrue( "Canonical full collection (" + name + ") is not in SVN", new File(name).exists()); } } } // protected implementation //----------------------------------------------------------------------- /** * Get the version of Collections that this object tries to * maintain serialization compatibility with. Defaults to 4, due to * the package change to collections4 introduced in version 4. * * This constant makes it possible for TestMap (and other subclasses, * if necessary) to automatically check SVN 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 "4"; } protected String getCanonicalEmptyCollectionName(final Object object) { final StringBuilder retval = new StringBuilder(); retval.append(TEST_DATA_PATH); 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(final Object object) { final StringBuilder retval = new StringBuilder(); retval.append(TEST_DATA_PATH); 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 SVN 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(final Serializable o, final String path) throws IOException { final 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(final Serializable o) throws IOException { final 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 SVN 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(final String path) throws IOException, ClassNotFoundException { final 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(final byte[] b) throws IOException, ClassNotFoundException { final 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(final InputStream stream) throws IOException, ClassNotFoundException { final ObjectInputStream oStream = new ObjectInputStream(stream); return oStream.readObject(); } private void writeExternalFormToStream(final Serializable o, final OutputStream stream) throws IOException { final ObjectOutputStream oStream = new ObjectOutputStream(stream); oStream.writeObject(o); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/BagUtilsTest.java100664 16225 12243235516 30234 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import junit.framework.Test; import org.apache.commons.collections4.bag.HashBag; import org.apache.commons.collections4.bag.PredicatedBag; import org.apache.commons.collections4.bag.PredicatedSortedBag; import org.apache.commons.collections4.bag.SynchronizedBag; import org.apache.commons.collections4.bag.SynchronizedSortedBag; import org.apache.commons.collections4.bag.TransformedBag; import org.apache.commons.collections4.bag.TransformedSortedBag; import org.apache.commons.collections4.bag.TreeBag; import org.apache.commons.collections4.bag.UnmodifiableBag; import org.apache.commons.collections4.bag.UnmodifiableSortedBag; import org.apache.commons.collections4.functors.TruePredicate; /** * Tests for BagUtils factory methods. * * @version $Id: BagUtilsTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class BagUtilsTest extends BulkTest { public BagUtilsTest(final String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(BagUtilsTest.class); } //---------------------------------------------------------------------- protected Class stringClass = this.getName().getClass(); protected Predicate truePredicate = TruePredicate.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 { BagUtils.synchronizedBag(null); fail("Expecting IllegalArgumentException for null bag."); } catch (final IllegalArgumentException ex) { // expected } } public void testUnmodifiableBag() { Bag bag = BagUtils.unmodifiableBag(new HashBag()); assertTrue("Returned object should be an UnmodifiableBag.", bag instanceof UnmodifiableBag); try { BagUtils.unmodifiableBag(null); fail("Expecting IllegalArgumentException for null bag."); } catch (final IllegalArgumentException ex) { // expected } assertSame("UnmodifiableBag shall not be decorated", bag, BagUtils.unmodifiableBag(bag)); } public void testPredicatedBag() { Bag bag = BagUtils.predicatedBag(new HashBag(), truePredicate); assertTrue("Returned object should be a PredicatedBag.", bag instanceof PredicatedBag); try { BagUtils.predicatedBag(null,truePredicate); fail("Expecting IllegalArgumentException for null bag."); } catch (final IllegalArgumentException ex) { // expected } try { BagUtils.predicatedBag(new HashBag(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (final IllegalArgumentException ex) { // expected } } public void testTransformedBag() { Bag bag = BagUtils.transformingBag(new HashBag(), nopTransformer); assertTrue("Returned object should be an TransformedBag.", bag instanceof TransformedBag); try { BagUtils.transformingBag(null, nopTransformer); fail("Expecting IllegalArgumentException for null bag."); } catch (final IllegalArgumentException ex) { // expected } try { BagUtils.transformingBag(new HashBag(), null); fail("Expecting IllegalArgumentException for null transformer."); } catch (final IllegalArgumentException ex) { // expected } } public void testSynchronizedSortedBag() { Bag bag = BagUtils.synchronizedSortedBag(new TreeBag()); assertTrue("Returned object should be a SynchronizedSortedBag.", bag instanceof SynchronizedSortedBag); try { BagUtils.synchronizedSortedBag(null); fail("Expecting IllegalArgumentException for null bag."); } catch (final IllegalArgumentException ex) { // expected } } public void testUnmodifiableSortedBag() { SortedBag bag = BagUtils.unmodifiableSortedBag(new TreeBag()); assertTrue("Returned object should be an UnmodifiableSortedBag.", bag instanceof UnmodifiableSortedBag); try { BagUtils.unmodifiableSortedBag(null); fail("Expecting IllegalArgumentException for null bag."); } catch (final IllegalArgumentException ex) { // expected } assertSame("UnmodifiableSortedBag shall not be decorated", bag, BagUtils.unmodifiableSortedBag(bag)); } public void testPredicatedSortedBag() { Bag bag = BagUtils.predicatedSortedBag(new TreeBag(), truePredicate); assertTrue("Returned object should be a PredicatedSortedBag.", bag instanceof PredicatedSortedBag); try { BagUtils.predicatedSortedBag(null, truePredicate); fail("Expecting IllegalArgumentException for null bag."); } catch (final IllegalArgumentException ex) { // expected } try { BagUtils.predicatedSortedBag(new TreeBag(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (final IllegalArgumentException ex) { // expected } } public void testTransformedSortedBag() { Bag bag = BagUtils.transformingSortedBag(new TreeBag(), nopTransformer); assertTrue("Returned object should be an TransformedSortedBag", bag instanceof TransformedSortedBag); try { BagUtils.transformingSortedBag(null, nopTransformer); fail("Expecting IllegalArgumentException for null bag."); } catch (final IllegalArgumentException ex) { // expected } try { BagUtils.transformingSortedBag(new TreeBag(), null); fail("Expecting IllegalArgumentException for null transformer."); } catch (final IllegalArgumentException ex) { // expected } } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/AbstractCollectionTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/AbstractCollec100664 145072 12243235516 32005 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.AbstractObjectTest; /** * 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 #makeObject()}, {@link #makeConfirmedCollection()} * and {@link #makeConfirmedFullCollection()} methods. * 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 org.apache.commons.collections4.map.AbstractMapTest 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 org.apache.commons.collections4.list.AbstractListTest AbstractListTest}, * {@link org.apache.commons.collections4.set.AbstractSetTest AbstractTestSet}, * or {@link org.apache.commons.collections4.bag.AbstractBagTest AbstractBagTest}, * 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 $Id: AbstractCollectionTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractCollectionTest extends AbstractObjectTest { // // 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. */ private 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. */ private Collection confirmed; /** * JUnit constructor. * * @param testName the test class name */ public AbstractCollectionTest(final 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 #makeObject()} 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 #makeObject()} 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; */ @Override public boolean isEqualsCheckable() { return false; } //----------------------------------------------------------------------- /** * Verifies that {@link #collection} and {@link #confirmed} have * identical state. */ public void verify() { final int confirmedSize = getConfirmed().size(); assertEquals("Collection size should match confirmed collection's", confirmedSize, getCollection().size()); assertEquals("Collection isEmpty() result should match confirmed collection's", getConfirmed().isEmpty(), getCollection().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 final Object[] confirmedValues = new Object[confirmedSize]; Iterator iter; iter = getConfirmed().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. final 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 = getCollection().iterator(); while (iter.hasNext()) { final 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: " + getCollection() + "\nReal: " + getConfirmed()); } } // 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: " + getCollection() + "\nReal: " + getConfirmed()); } } } //----------------------------------------------------------------------- /** * Resets the {@link #collection} and {@link #confirmed} fields to empty * collections. Invoke this method before performing a modification * test. */ public void resetEmpty() { this.setCollection(makeObject()); this.setConfirmed(makeConfirmedCollection()); } /** * Resets the {@link #collection} and {@link #confirmed} fields to full * collections. Invoke this method before performing a modification * test. */ public void resetFull() { this.setCollection(makeFullCollection()); this.setConfirmed(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. */ @Override public abstract Collection makeObject(); /** * 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() { final Collection c = makeObject(); c.addAll(Arrays.asList(getFullElements())); return c; } /** * Creates a new Map Entry that is independent of the first and the map. */ public Map.Entry cloneMapEntry(final Map.Entry entry) { final HashMap map = new HashMap(); map.put(entry.getKey(), entry.getValue()); return 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. */ @SuppressWarnings("unchecked") public E[] getFullElements() { if (isNullSupported()) { final ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullNonNullElements())); list.add(4, null); return (E[]) list.toArray(); } return 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 E[] 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. */ @SuppressWarnings("unchecked") public E[] getFullNonNullElements() { return (E[]) new Object[] { new String(""), new String("One"), Integer.valueOf(2), "Three", Integer.valueOf(4), "One", new Double(5), new Float(6), "Seven", "Eight", new String("Nine"), Integer.valueOf(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. */ @SuppressWarnings("unchecked") public E[] getOtherNonNullElements() { return (E[]) new Object[] { Integer.valueOf(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; } final E[] elements = getFullElements(); for (final E element : elements) { resetEmpty(); final boolean r = getCollection().add(element); getConfirmed().add(element); verify(); assertTrue("Empty collection changed after add", r); assertEquals("Collection size is 1 after first add", 1, getCollection().size()); } resetEmpty(); int size = 0; for (final E element : elements) { final boolean r = getCollection().add(element); getConfirmed().add(element); verify(); if (r) { size++; } assertEquals("Collection size should grow after add", size, getCollection().size()); assertTrue("Collection should contain added element", getCollection().contains(element)); } } /** * Tests {@link Collection#addAll(Collection)}. */ public void testCollectionAddAll() { if (!isAddSupported()) { return; } resetEmpty(); E[] elements = getFullElements(); boolean r = getCollection().addAll(Arrays.asList(elements)); getConfirmed().addAll(Arrays.asList(elements)); verify(); assertTrue("Empty collection should change after addAll", r); for (final E element : elements) { assertTrue("Collection should contain added element", getCollection().contains(element)); } resetFull(); int size = getCollection().size(); elements = getOtherElements(); r = getCollection().addAll(Arrays.asList(elements)); getConfirmed().addAll(Arrays.asList(elements)); verify(); assertTrue("Full collection should change after addAll", r); for (final E element : elements) { assertTrue("Full collection should contain added element", getCollection().contains(element)); } assertEquals("Size should increase after addAll", size + elements.length, getCollection().size()); resetFull(); size = getCollection().size(); r = getCollection().addAll(Arrays.asList(getFullElements())); getConfirmed().addAll(Arrays.asList(getFullElements())); verify(); if (r) { assertTrue("Size should increase if addAll returns true", size < getCollection().size()); } else { assertEquals("Size should not change if addAll returns false", size, getCollection().size()); } } /** * If {@link #isAddSupported()} returns false, tests that add operations * raise UnsupportedOperationException. */ public void testUnsupportedAdd() { if (isAddSupported()) { return; } resetEmpty(); try { getCollection().add(getFullNonNullElements()[0]); fail("Empty collection should not support add."); } catch (final UnsupportedOperationException e) { // expected } // make sure things didn't change even if the expected exception was // thrown. verify(); try { getCollection().addAll(Arrays.asList(getFullElements())); fail("Empty collection should not support addAll."); } catch (final UnsupportedOperationException e) { // expected } // make sure things didn't change even if the expected exception was // thrown. verify(); resetFull(); try { getCollection().add(getFullNonNullElements()[0]); fail("Full collection should not support add."); } catch (final UnsupportedOperationException e) { // expected } // make sure things didn't change even if the expected exception was // thrown. verify(); try { getCollection().addAll(Arrays.asList(getOtherElements())); fail("Full collection should not support addAll."); } catch (final 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(); getCollection().clear(); // just to make sure it doesn't raise anything verify(); resetFull(); getCollection().clear(); getConfirmed().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 + "]", !getCollection().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 + "]", !getCollection().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 + "]", getCollection().contains(elements[i])); } // make sure calls to "contains" don't change anything verify(); resetFull(); elements = getOtherElements(); for (Object element : elements) { assertTrue("Full collection shouldn't contain element", !getCollection().contains(element)); } } /** * Tests {@link Collection#containsAll(Collection)}. */ public void testCollectionContainsAll() { resetEmpty(); Collection col = new HashSet(); assertTrue("Every Collection should contain all elements of an " + "empty Collection.", getCollection().containsAll(col)); col.addAll(Arrays.asList(getOtherElements())); assertTrue("Empty Collection shouldn't contain all elements of " + "a non-empty Collection.", !getCollection().containsAll(col)); // make sure calls to "containsAll" don't change anything verify(); resetFull(); assertTrue("Full collection shouldn't contain other elements", !getCollection().containsAll(col)); col.clear(); col.addAll(Arrays.asList(getFullElements())); assertTrue("Full collection should containAll full elements", getCollection().containsAll(col)); // make sure calls to "containsAll" don't change anything verify(); final int min = getFullElements().length < 2 ? 0 : 2; final 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", getCollection().containsAll(col)); assertTrue("Full collection should containAll itself", getCollection().containsAll(getCollection())); // 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", getCollection().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, getCollection().isEmpty()); // make sure calls to "isEmpty() don't change anything verify(); resetFull(); assertEquals("Full collection shouldn't be empty", false, getCollection().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 = getCollection().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 (final NoSuchElementException e) { // expected } // make sure nothing has changed after non-modification verify(); resetFull(); it1 = getCollection().iterator(); for (int i = 0; i < getCollection().size(); i++) { assertTrue("Iterator for full collection should haveNext", it1.hasNext()); it1.next(); } assertTrue("Iterator should be finished", !it1.hasNext()); final ArrayList list = new ArrayList(); it1 = getCollection().iterator(); for (int i = 0; i < getCollection().size(); i++) { final E next = it1.next(); assertTrue("Collection should contain element returned by its iterator", getCollection().contains(next)); list.add(next); } try { it1.next(); fail("iterator.next() should raise NoSuchElementException after it finishes"); } catch (final NoSuchElementException e) { // expected } // make sure nothing has changed after non-modification verify(); } /** * Tests removals from {@link Collection#iterator()}. */ @SuppressWarnings("unchecked") public void testCollectionIteratorRemove() { if (!isRemoveSupported()) { return; } resetEmpty(); try { getCollection().iterator().remove(); fail("New iterator.remove should raise IllegalState"); } catch (final IllegalStateException e) { // expected } verify(); try { final Iterator iter = getCollection().iterator(); iter.hasNext(); iter.remove(); fail("New iterator.remove should raise IllegalState even after hasNext"); } catch (final IllegalStateException e) { // expected } verify(); resetFull(); int size = getCollection().size(); Iterator iter = getCollection().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()) { getConfirmed().remove(o); verify(); } size--; assertEquals("Collection should shrink by one after iterator.remove", size, getCollection().size()); } assertTrue("Collection should be empty after iterator purge", getCollection().isEmpty()); resetFull(); iter = getCollection().iterator(); iter.next(); iter.remove(); try { iter.remove(); fail("Second iter.remove should raise IllegalState"); } catch (final IllegalStateException e) { // expected } } /** * Tests {@link Collection#remove(Object)}. */ public void testCollectionRemove() { if (!isRemoveSupported()) { return; } resetEmpty(); final E[] elements = getFullElements(); for (E element : elements) { assertTrue("Shouldn't remove nonexistent element", !getCollection().remove(element)); verify(); } final E[] other = getOtherElements(); resetFull(); for (E element : other) { assertTrue("Shouldn't remove nonexistent other element", !getCollection().remove(element)); verify(); } final int size = getCollection().size(); for (final E element : elements) { resetFull(); assertTrue("Collection should remove extant element: " + element, getCollection().remove(element)); // 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()) { getConfirmed().remove(element); verify(); } assertEquals("Collection should shrink after remove", size - 1, getCollection().size()); } } /** * Tests {@link Collection#removeAll(Collection)}. */ public void testCollectionRemoveAll() { if (!isRemoveSupported()) { return; } resetEmpty(); assertTrue("Empty collection removeAll should return false for empty input", !getCollection().removeAll(Collections.EMPTY_SET)); verify(); assertTrue("Empty collection removeAll should return false for nonempty input", !getCollection().removeAll(new ArrayList(getCollection()))); verify(); resetFull(); assertTrue("Full collection removeAll should return false for empty input", !getCollection().removeAll(Collections.EMPTY_SET)); verify(); assertTrue("Full collection removeAll should return false for other elements", !getCollection().removeAll(Arrays.asList(getOtherElements()))); verify(); assertTrue("Full collection removeAll should return true for full elements", getCollection().removeAll(new HashSet(getCollection()))); getConfirmed().removeAll(new HashSet(getConfirmed())); verify(); resetFull(); final int size = getCollection().size(); final int min = getFullElements().length < 2 ? 0 : 2; final int max = getFullElements().length == 1 ? 1 : getFullElements().length <= 5 ? getFullElements().length - 1 : 5; final Collection all = Arrays.asList(getFullElements()).subList(min, max); assertTrue("Full collection removeAll should work", getCollection().removeAll(all)); getConfirmed().removeAll(all); verify(); assertTrue("Collection should shrink after removeAll", getCollection().size() < size); for (E element : all) { assertTrue("Collection shouldn't contain removed element", !getCollection().contains(element)); } } /** * Tests {@link Collection#retainAll(Collection)}. */ public void testCollectionRetainAll() { if (!isRemoveSupported()) { return; } resetEmpty(); final List elements = Arrays.asList(getFullElements()); final List other = Arrays.asList(getOtherElements()); assertTrue("Empty retainAll() should return false", !getCollection().retainAll(Collections.EMPTY_SET)); verify(); assertTrue("Empty retainAll() should return false", !getCollection().retainAll(elements)); verify(); resetFull(); assertTrue("Collection should change from retainAll empty", getCollection().retainAll(Collections.EMPTY_SET)); getConfirmed().retainAll(Collections.EMPTY_SET); verify(); resetFull(); assertTrue("Collection changed from retainAll other", getCollection().retainAll(other)); getConfirmed().retainAll(other); verify(); resetFull(); int size = getCollection().size(); assertTrue("Collection shouldn't change from retainAll elements", !getCollection().retainAll(elements)); verify(); assertEquals("Collection size shouldn't change", size, getCollection().size()); if (getFullElements().length > 1) { resetFull(); size = getCollection().size(); final int min = getFullElements().length < 2 ? 0 : 2; final int max = getFullElements().length <= 5 ? getFullElements().length - 1 : 5; assertTrue("Collection should changed by partial retainAll", getCollection().retainAll(elements.subList(min, max))); getConfirmed().retainAll(elements.subList(min, max)); verify(); for (E element : getCollection()) { assertTrue("Collection only contains retained element", elements.subList(min, max).contains(element)); } } resetFull(); final HashSet set = new HashSet(elements); size = getCollection().size(); assertTrue("Collection shouldn't change from retainAll without " + "duplicate elements", !getCollection().retainAll(set)); verify(); assertEquals("Collection size didn't change from nonduplicate " + "retainAll", size, getCollection().size()); } /** * Tests {@link Collection#size()}. */ public void testCollectionSize() { resetEmpty(); assertEquals("Size of new Collection is 0.", 0, getCollection().size()); resetFull(); assertTrue("Size of full collection should be greater than zero", getCollection().size() > 0); } /** * Tests {@link Collection#toArray()}. */ public void testCollectionToArray() { resetEmpty(); assertEquals("Empty Collection should return empty array for toArray", 0, getCollection().toArray().length); resetFull(); final Object[] array = getCollection().toArray(); assertEquals("Full collection toArray should be same size as collection", array.length, getCollection().size()); final Object[] confirmedArray = getConfirmed().toArray(); assertEquals("length of array from confirmed collection should " + "match the length of the collection's array", confirmedArray.length, array.length); final boolean[] matched = new boolean[array.length]; for (int i = 0; i < array.length; i++) { assertTrue("Collection should contain element in toArray", getCollection().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 (final boolean element : matched) { assertEquals("Collection should return all its elements in " + "toArray", true, element); } } /** * Tests {@link Collection#toArray(Object[])}. */ public void testCollectionToArray2() { resetEmpty(); Object[] a = new Object[] { new Object(), null, null }; Object[] array = getCollection().toArray(a); assertEquals("Given array shouldn't shrink", array, a); assertNull("Last element should be set to null", a[0]); verify(); resetFull(); try { array = getCollection().toArray(new Void[0]); fail("toArray(new Void[0]) should raise ArrayStore"); } catch (final ArrayStoreException e) { // expected } verify(); try { array = getCollection().toArray(null); fail("toArray(null) should raise NPE"); } catch (final NullPointerException e) { // expected } verify(); array = getCollection().toArray(new Object[0]); a = getCollection().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 final HashSet> classes = new HashSet>(); for (final Object element : array) { classes.add(element == null ? null : element.getClass()); } if (classes.size() > 1) { return; } Class cl = 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 = getCollection().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(getCollection().toArray())); verify(); } /** * Tests toString on a collection. */ public void testCollectionToString() { resetEmpty(); assertTrue("toString shouldn't return null", getCollection().toString() != null); resetFull(); assertTrue("toString shouldn't return null", getCollection().toString() != null); } /** * If isRemoveSupported() returns false, tests to see that remove * operations raise an UnsupportedOperationException. */ public void testUnsupportedRemove() { if (isRemoveSupported()) { return; } resetEmpty(); try { getCollection().clear(); fail("clear should raise UnsupportedOperationException"); } catch (final UnsupportedOperationException e) { // expected } verify(); try { getCollection().remove(null); fail("remove should raise UnsupportedOperationException"); } catch (final UnsupportedOperationException e) { // expected } verify(); try { getCollection().removeAll(null); fail("removeAll should raise UnsupportedOperationException"); } catch (final UnsupportedOperationException e) { // expected } verify(); try { getCollection().retainAll(null); fail("retainAll should raise UnsupportedOperationException"); } catch (final UnsupportedOperationException e) { // expected } verify(); resetFull(); try { final Iterator iterator = getCollection().iterator(); iterator.next(); iterator.remove(); fail("iterator.remove should raise UnsupportedOperationException"); } catch (final UnsupportedOperationException e) { // expected } verify(); } /** * Tests that the collection's iterator is fail-fast. */ public void testCollectionIteratorFailFast() { if (!isFailFastSupported()) { return; } if (isAddSupported()) { resetFull(); try { final Iterator iter = getCollection().iterator(); final E o = getOtherElements()[0]; getCollection().add(o); getConfirmed().add(o); iter.next(); fail("next after add should raise ConcurrentModification"); } catch (final ConcurrentModificationException e) { // expected } verify(); resetFull(); try { final Iterator iter = getCollection().iterator(); getCollection().addAll(Arrays.asList(getOtherElements())); getConfirmed().addAll(Arrays.asList(getOtherElements())); iter.next(); fail("next after addAll should raise ConcurrentModification"); } catch (final ConcurrentModificationException e) { // expected } verify(); } if (!isRemoveSupported()) { return; } resetFull(); try { final Iterator iter = getCollection().iterator(); getCollection().clear(); iter.next(); fail("next after clear should raise ConcurrentModification"); } catch (final ConcurrentModificationException e) { // expected } catch (final NoSuchElementException e) { // (also legal given spec) } resetFull(); try { final Iterator iter = getCollection().iterator(); getCollection().remove(getFullElements()[0]); iter.next(); fail("next after remove should raise ConcurrentModification"); } catch (final ConcurrentModificationException e) { // expected } resetFull(); try { final Iterator iter = getCollection().iterator(); final List sublist = Arrays.asList(getFullElements()).subList(2,5); getCollection().removeAll(sublist); iter.next(); fail("next after removeAll should raise ConcurrentModification"); } catch (final ConcurrentModificationException e) { // expected } resetFull(); try { final Iterator iter = getCollection().iterator(); final List sublist = Arrays.asList(getFullElements()).subList(2,5); getCollection().retainAll(sublist); iter.next(); fail("next after retainAll should raise ConcurrentModification"); } catch (final ConcurrentModificationException e) { // expected } } @Override public void testSerializeDeserializeThenCompare() throws Exception { Object obj = makeObject(); if (obj instanceof Serializable && isTestSerialization()) { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(obj); out.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); final Object dest = in.readObject(); in.close(); if (isEqualsCheckable()) { assertEquals("obj != deserialize(serialize(obj)) - EMPTY Collection", obj, dest); } } obj = makeFullCollection(); if (obj instanceof Serializable && isTestSerialization()) { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(buffer); out.writeObject(obj); out.close(); final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); final Object dest = in.readObject(); in.close(); if (isEqualsCheckable()) { assertEquals("obj != deserialize(serialize(obj)) - FULL Collection", obj, dest); } } } public Collection getCollection() { return collection; } /** * Set the collection. * @param collection the Collection to set */ public void setCollection(final Collection collection) { this.collection = collection; } public Collection getConfirmed() { return confirmed; } /** * Set the confirmed. * @param confirmed the Collection to set */ public void setConfirmed(final Collection confirmed) { this.confirmed = confirmed; } /** * Handle the optional exceptions declared by {@link Collection#contains(Object)} * @param coll * @param element */ protected static void assertNotCollectionContains(final Collection coll, final Object element) { try { assertFalse(coll.contains(element)); } catch (final ClassCastException e) { //apparently not } catch (final NullPointerException e) { //apparently not } } /** * Handle the optional exceptions declared by {@link Collection#containsAll(Collection)} * @param coll * @param sub */ protected static void assertNotCollectionContainsAll(final Collection coll, final Collection sub) { try { assertFalse(coll.containsAll(sub)); } catch (final ClassCastException cce) { //apparently not } catch (final NullPointerException e) { //apparently not } } /** * Handle optional exceptions of {@link Collection#remove(Object)} * @param coll * @param element */ protected static void assertNotRemoveFromCollection(final Collection coll, final Object element) { try { assertFalse(coll.remove(element)); } catch (final ClassCastException cce) { //apparently not } catch (final NullPointerException e) { //apparently not } } /** * Handle optional exceptions of {@link Collection#removeAll(Collection)} * @param coll * @param sub */ protected static void assertNotRemoveAllFromCollection(final Collection coll, final Collection sub) { try { assertFalse(coll.removeAll(sub)); } catch (final ClassCastException cce) { //apparently not } catch (final NullPointerException e) { //apparently not } } } ././@LongLink100644 0 0 166 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/UnmodifiableCollectionTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/UnmodifiableCo100664 6727 12243235516 31743 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.commons.collections4.Unmodifiable; /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link UnmodifiableCollection} implementation. * * @since 3.0 * @version $Id: UnmodifiableCollectionTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class UnmodifiableCollectionTest extends AbstractCollectionTest { public UnmodifiableCollectionTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public Collection makeObject() { return UnmodifiableCollection.unmodifiableCollection(new ArrayList()); } @Override public Collection makeFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return UnmodifiableCollection.unmodifiableCollection(list); } @Override public Collection makeConfirmedCollection() { return new ArrayList(); } @Override public Collection makeConfirmedFullCollection() { final ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullCollection() instanceof Unmodifiable); } public void testDecorateFactory() { final Collection coll = makeFullCollection(); assertSame(coll, UnmodifiableCollection.unmodifiableCollection(coll)); try { UnmodifiableCollection.unmodifiableCollection(null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableCollection.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableCollection.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 164 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/PredicatedCollectionTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/PredicatedColl100664 11471 12243235516 31751 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.TruePredicate; /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link PredicatedCollection} implementation. * * @since 3.0 * @version $Id: PredicatedCollectionTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class PredicatedCollectionTest extends AbstractCollectionTest { public PredicatedCollectionTest(final String name) { super(name); } //------------------------------------------------------------------------ protected Predicate truePredicate = TruePredicate.truePredicate(); protected Collection decorateCollection( final Collection collection, final Predicate predicate) { return PredicatedCollection.predicatedCollection(collection, predicate); } @Override public Collection makeObject() { return decorateCollection(new ArrayList(), truePredicate); } @Override public Collection makeConfirmedCollection() { return new ArrayList(); } @Override @SuppressWarnings("unchecked") public E[] getFullElements() { return (E[]) new Object[] { "1", "3", "5", "7", "2", "4", "6" }; } @Override public Collection makeFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return decorateCollection(list, truePredicate); } @Override public Collection makeConfirmedFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } //----------------------------------------------------------------------- protected Predicate testPredicate = new Predicate() { public boolean evaluate(final E o) { return o instanceof String; } }; public Collection makeTestCollection() { return decorateCollection(new ArrayList(), testPredicate); } @SuppressWarnings("unchecked") public void testIllegalAdd() { final Collection c = makeTestCollection(); final Integer i = Integer.valueOf(3); try { c.add((E) i); fail("Integer should fail string predicate."); } catch (final IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !c.contains(i)); } @SuppressWarnings("unchecked") public void testIllegalAddAll() { final Collection c = makeTestCollection(); final List elements = new ArrayList(); elements.add((E) "one"); elements.add((E) "two"); elements.add((E) Integer.valueOf(3)); elements.add((E) "four"); try { c.addAll(elements); fail("Integer should fail string predicate."); } catch (final 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(Integer.valueOf(3))); assertTrue("Collection shouldn't contain illegal element", !c.contains("four")); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/PredicatedCollection.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/PredicatedCollection.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/CompositeCollectionTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/CompositeColle100664 27646 12243235516 32027 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link CompositeCollection} implementation. * * @since 3.0 * @version $Id: CompositeCollectionTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class CompositeCollectionTest extends AbstractCollectionTest { public CompositeCollectionTest(final String name) { super(name); } //----------------------------------------------------------------------------- /** * Run stock collection tests without Mutator, so turn off add, remove */ @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } /** * Empty collection is empty composite */ @Override public Collection makeObject() { return new CompositeCollection(); } @Override public Collection makeConfirmedCollection() { return new HashSet(); } @Override @SuppressWarnings("unchecked") public E[] getFullElements() { return (E[]) new Object[] { "1", "2", "3", "4" }; } /** * Full collection consists of 4 collections, each with one element */ @Override public Collection makeFullCollection() { final CompositeCollection compositeCollection = new CompositeCollection(); final E[] elements = getFullElements(); for (final E element : elements) { final Collection summand = new HashSet(); summand.add(element); compositeCollection.addComposited(summand); } return compositeCollection; } /** * Full collection should look like a collection with 4 elements */ @Override public Collection makeConfirmedFullCollection() { final 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 */ @Override public void testUnsupportedRemove() { resetFull(); try { getCollection().remove(null); fail("remove should raise UnsupportedOperationException"); } catch (final 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(); } @SuppressWarnings("serial") protected void setUpMutatorTest() { setUpTest(); c.setMutator(new CompositeCollection.CollectionMutator() { public boolean add(final CompositeCollection composite, final List> collections, final E obj) { for (final Collection coll : collections) { coll.add(obj); } return true; } public boolean addAll(final CompositeCollection composite, final List> collections, final Collection coll) { for (final Collection collection : collections) { collection.addAll(coll); } return true; } public boolean remove(final CompositeCollection composite, final List> collections, final Object obj) { for (final Collection collection : collections) { collection.remove(obj); } return true; } }); } @SuppressWarnings("unchecked") public void testSize() { setUpTest(); final HashSet set = new HashSet(); set.add((E) "a"); set.add((E) "b"); c.addComposited(set); assertEquals(set.size(), c.size()); } @SuppressWarnings("unchecked") public void testMultipleCollectionsSize() { setUpTest(); final HashSet set = new HashSet(); set.add((E) "a"); set.add((E) "b"); c.addComposited(set); final HashSet other = new HashSet(); other.add((E) "c"); c.addComposited(other); assertEquals(set.size() + other.size(), c.size()); } @SuppressWarnings("unchecked") public void testIsEmpty() { setUpTest(); assertTrue(c.isEmpty()); final HashSet empty = new HashSet(); c.addComposited(empty); assertTrue(c.isEmpty()); empty.add((E) "a"); assertTrue(!c.isEmpty()); } @SuppressWarnings("unchecked") public void testIterator() { setUpTest(); one.add((E) "1"); two.add((E) "2"); c.addComposited(one); c.addComposited(two); final Iterator i = c.iterator(); E next = i.next(); assertTrue(c.contains(next)); assertTrue(one.contains(next)); next = i.next(); i.remove(); assertTrue(!c.contains(next)); assertTrue(!two.contains(next)); } @SuppressWarnings("unchecked") public void testClear() { setUpTest(); one.add((E) "1"); two.add((E) "2"); c.addComposited(one, two); c.clear(); assertTrue(one.isEmpty()); assertTrue(two.isEmpty()); assertTrue(c.isEmpty()); } @SuppressWarnings("unchecked") public void testContainsAll() { setUpTest(); one.add((E) "1"); two.add((E) "1"); c.addComposited(one); assertTrue(c.containsAll(two)); } @SuppressWarnings("unchecked") public void testRetainAll() { setUpTest(); one.add((E) "1"); one.add((E) "2"); two.add((E) "1"); c.addComposited(one); c.retainAll(two); assertTrue(!c.contains("2")); assertTrue(!one.contains("2")); assertTrue(c.contains("1")); assertTrue(one.contains("1")); } @SuppressWarnings({ "unchecked", "serial" }) public void testAddAllMutator() { setUpTest(); c.setMutator(new CompositeCollection.CollectionMutator() { public boolean add(final CompositeCollection composite, final List> collections, final E obj) { for (final Collection collection : collections) { collection.add(obj); } return true; } public boolean addAll(final CompositeCollection composite, final List> collections, final Collection coll) { for (final Collection collection : collections) { collection.addAll(coll); } return true; } public boolean remove(final CompositeCollection composite, final List> collections, final Object obj) { return false; } }); c.addComposited(one); two.add((E) "foo"); c.addAll(two); assertTrue(c.contains("foo")); assertTrue(one.contains("foo")); } @SuppressWarnings({ "unchecked", "serial" }) public void testAddMutator() { setUpTest(); c.setMutator(new CompositeCollection.CollectionMutator() { public boolean add(final CompositeCollection composite, final List> collections, final E obj) { for (final Collection collection : collections) { collection.add(obj); } return true; } public boolean addAll(final CompositeCollection composite, final List> collections, final Collection coll) { for (final Collection collection : collections) { collection.addAll(coll); } return true; } public boolean remove(final CompositeCollection composite, final List> collections, final Object obj) { return false; } }); c.addComposited(one); c.add((E) "foo"); assertTrue(c.contains("foo")); assertTrue(one.contains("foo")); } @SuppressWarnings("unchecked") public void testToCollection() { setUpTest(); one.add((E) "1"); two.add((E) "2"); c.addComposited(one, two); final Collection foo = c.toCollection(); assertTrue(foo.containsAll(c)); assertEquals(c.size(), foo.size()); one.add((E) "3"); assertTrue(!foo.containsAll(c)); } @SuppressWarnings("unchecked") public void testAddAllToCollection() { setUpTest(); one.add((E) "1"); two.add((E) "2"); c.addComposited(one, two); final Collection toCollection = new HashSet(); toCollection.addAll(c); assertTrue(toCollection.containsAll(c)); assertEquals(c.size(), toCollection.size()); } @SuppressWarnings("unchecked") public void testRemove() { setUpMutatorTest(); one.add((E) "1"); two.add((E) "2"); two.add((E) "1"); c.addComposited(one, two); c.remove("1"); assertTrue(!c.contains("1")); assertTrue(!one.contains("1")); assertTrue(!two.contains("1")); } @SuppressWarnings("unchecked") public void testRemoveAll() { setUpMutatorTest(); one.add((E) "1"); two.add((E) "2"); two.add((E) "1"); // need separate list to remove, as otherwise one clears itself final Collection removing = new ArrayList(one); c.addComposited(one, two); c.removeAll(removing); assertTrue(!c.contains("1")); assertTrue(!one.contains("1")); assertTrue(!two.contains("1")); } @SuppressWarnings("unchecked") public void testRemoveComposited() { setUpMutatorTest(); one.add((E) "1"); two.add((E) "2"); two.add((E) "1"); c.addComposited(one, two); c.removeComposited(one); assertTrue(c.contains("1")); assertEquals(2, c.size()); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CompositeCollection.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CompositeCollection.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 175 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/UnmodifiableBoundedCollectionTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/UnmodifiableBo100664 6614 12243235516 31735 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.apache.commons.collections4.BoundedCollection; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.list.FixedSizeList; /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link UnmodifiableBoundedCollection} implementation. * * @version $Id: UnmodifiableBoundedCollectionTest.java 1540766 2013-11-11 16:47:20Z tn $ */ public class UnmodifiableBoundedCollectionTest extends AbstractCollectionTest { public UnmodifiableBoundedCollectionTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public Collection makeObject() { final BoundedCollection coll = FixedSizeList.fixedSizeList(new ArrayList()); return UnmodifiableBoundedCollection.unmodifiableBoundedCollection(coll); } @Override public BoundedCollection makeFullCollection() { final E[] allElements = getFullElements(); final BoundedCollection coll = FixedSizeList.fixedSizeList(new ArrayList(Arrays.asList(allElements))); return UnmodifiableBoundedCollection.unmodifiableBoundedCollection(coll); } @Override public Collection makeConfirmedCollection() { return new ArrayList(); } @Override public Collection makeConfirmedFullCollection() { final ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override protected boolean skipSerializedCanonicalTests() { return true; } @Override public String getCompatibilityVersion() { return "4"; } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullCollection() instanceof Unmodifiable); } public void testDecorateFactory() { final BoundedCollection coll = makeFullCollection(); assertSame(coll, UnmodifiableBoundedCollection.unmodifiableBoundedCollection(coll)); try { UnmodifiableBoundedCollection.unmodifiableBoundedCollection(null); fail(); } catch (final IllegalArgumentException ex) {} } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/IndexedCollectionTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/IndexedCollect100664 13071 12243235516 31757 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import static java.util.Arrays.asList; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.apache.commons.collections4.Transformer; /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link IndexedCollection} implementation. * * @since 4.0 * @version $Id: IndexedCollectionTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("boxing") public class IndexedCollectionTest extends AbstractCollectionTest { public IndexedCollectionTest(final String name) { super(name); } //------------------------------------------------------------------------ protected Collection decorateCollection(final Collection collection) { return IndexedCollection.nonUniqueIndexedCollection(collection, new IntegerTransformer()); } protected IndexedCollection decorateUniqueCollection(final Collection collection) { return IndexedCollection.uniqueIndexedCollection(collection, new IntegerTransformer()); } private static final class IntegerTransformer implements Transformer, Serializable { private static final long serialVersionUID = 809439581555072949L; public Integer transform(final String input) { return Integer.valueOf(input); } } @Override public Collection makeObject() { return decorateCollection(new ArrayList()); } @Override public Collection makeConfirmedCollection() { return new ArrayList(); } @Override public String[] getFullElements() { return new String[] { "1", "3", "5", "7", "2", "4", "6" }; } @Override public String[] getOtherElements() { return new String[] {"9", "88", "678", "87", "98", "78", "99"}; } @Override public Collection makeFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return decorateCollection(list); } @Override public Collection makeConfirmedFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } public Collection makeTestCollection() { return decorateCollection(new ArrayList()); } public Collection makeUniqueTestCollection() { return decorateUniqueCollection(new ArrayList()); } @Override protected boolean skipSerializedCanonicalTests() { // FIXME: support canonical tests return true; } //------------------------------------------------------------------------ public void testAddedObjectsCanBeRetrievedByKey() throws Exception { final Collection coll = makeTestCollection(); coll.add("12"); coll.add("16"); coll.add("1"); coll.addAll(asList("2","3","4")); @SuppressWarnings("unchecked") final IndexedCollection indexed = (IndexedCollection) coll; assertEquals("12", indexed.get(12)); assertEquals("16", indexed.get(16)); assertEquals("1", indexed.get(1)); assertEquals("2", indexed.get(2)); assertEquals("3", indexed.get(3)); assertEquals("4", indexed.get(4)); } public void testEnsureDuplicateObjectsCauseException() throws Exception { final Collection coll = makeUniqueTestCollection(); coll.add("1"); try { coll.add("1"); fail(); } catch (final IllegalArgumentException e) { // expected } } public void testDecoratedCollectionIsIndexedOnCreation() throws Exception { final Collection original = makeFullCollection(); final IndexedCollection indexed = decorateUniqueCollection(original); assertEquals("1", indexed.get(1)); assertEquals("2", indexed.get(2)); assertEquals("3", indexed.get(3)); } public void testReindexUpdatesIndexWhenDecoratedCollectionIsModifiedSeparately() throws Exception { final Collection original = new ArrayList(); final IndexedCollection indexed = decorateUniqueCollection(original); original.add("1"); original.add("2"); original.add("3"); assertNull(indexed.get(1)); assertNull(indexed.get(2)); assertNull(indexed.get(3)); indexed.reindex(); assertEquals("1", indexed.get(1)); assertEquals("2", indexed.get(2)); assertEquals("3", indexed.get(3)); } } ././@LongLink100644 0 0 166 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/SynchronizedCollectionTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/SynchronizedCo100664 4530 12243235516 32012 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link SynchronizedCollection} implementation. * * @since 3.1 * @version $Id: SynchronizedCollectionTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class SynchronizedCollectionTest extends AbstractCollectionTest { public SynchronizedCollectionTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public Collection makeObject() { return SynchronizedCollection.synchronizedCollection(new ArrayList()); } @Override public Collection makeConfirmedCollection() { return new ArrayList(); } @Override public Collection makeConfirmedFullCollection() { final ArrayList list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/SynchronizedCollection.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/SynchronizedCollection.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 165 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/TransformedCollectionTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/collection/TransformedCol100664 12127 12243235516 32014 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.TransformerUtils; /** * Extension of {@link AbstractCollectionTest} for exercising the {@link TransformedCollection} * implementation. * * @since 3.0 * @version $Id: TransformedCollectionTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class TransformedCollectionTest extends AbstractCollectionTest { private static class StringToInteger implements Transformer { public Object transform(final Object input) { return Integer.valueOf((String) input); } } public static final Transformer NOOP_TRANSFORMER = TransformerUtils.nopTransformer(); public static final Transformer STRING_TO_INTEGER_TRANSFORMER = new StringToInteger(); public TransformedCollectionTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public Collection makeConfirmedCollection() { return new ArrayList(); } @Override public Collection makeConfirmedFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return list; } @Override public Collection makeObject() { return TransformedCollection.transformingCollection(new ArrayList(), NOOP_TRANSFORMER); } @Override public Collection makeFullCollection() { final List list = new ArrayList(); list.addAll(Arrays.asList(getFullElements())); return TransformedCollection.transformingCollection(list, NOOP_TRANSFORMER); } //----------------------------------------------------------------------- @Override public Object[] getFullElements() { return new Object[] {"1", "3", "5", "7", "2", "4", "6"}; } @Override public Object[] getOtherElements() { return new Object[] {"9", "88", "678", "87", "98", "78", "99"}; } //----------------------------------------------------------------------- public void testTransformedCollection() { final Collection coll = TransformedCollection.transformingCollection(new ArrayList(), STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, coll.size()); final Object[] elements = getFullElements(); for (int i = 0; i < elements.length; i++) { coll.add(elements[i]); assertEquals(i + 1, coll.size()); assertEquals(true, coll.contains(Integer.valueOf((String) elements[i]))); assertEquals(false, coll.contains(elements[i])); } assertEquals(true, coll.remove(Integer.valueOf((String) elements[0]))); } public void testTransformedCollection_decorateTransform() { final Collection originalCollection = new ArrayList(); final Object[] elements = getFullElements(); Collections.addAll(originalCollection, elements); final Collection collection = TransformedCollection.transformedCollection(originalCollection, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(elements.length, collection.size()); for (final Object element : elements) { assertEquals(true, collection.contains(Integer.valueOf((String) element))); assertEquals(false, collection.contains(element)); } assertEquals(false, collection.remove(elements[0])); assertEquals(true, collection.remove(Integer.valueOf((String) elements[0]))); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/TransformedCollection.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/TransformedCollection.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ReverseListIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ReverseListIter100664 13361 12243235516 32047 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableListIterator; /** * Tests the ReverseListIterator. * * @version $Id: ReverseListIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ReverseListIteratorTest extends AbstractListIteratorTest { protected String[] testArray = { "One", "Two", "Three", "Four" }; public ReverseListIteratorTest(final String testName) { super(testName); } @Override public ListIterator makeEmptyIterator() { return new ReverseListIterator(new ArrayList()); } @Override @SuppressWarnings("unchecked") public ReverseListIterator makeObject() { final List list = new ArrayList(Arrays.asList((E[]) testArray)); return new ReverseListIterator(list); } // overrides //----------------------------------------------------------------------- @Override public void testEmptyListIteratorIsIndeedEmpty() { final ListIterator it = makeEmptyIterator(); 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 (final NoSuchElementException e) { } // previous() should throw a NoSuchElementException try { it.previous(); fail("NoSuchElementException must be thrown from empty ListIterator"); } catch (final NoSuchElementException e) { } } @Override public void testWalkForwardAndBack() { final ArrayList list = new ArrayList(); final ListIterator it = makeObject(); 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 final 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 (final NoSuchElementException e) { } } //----------------------------------------------------------------------- public void testReverse() { final ListIterator it = makeObject(); 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() { final ResettableListIterator it = makeObject(); assertEquals("Four", it.next()); it.reset(); assertEquals("Four", it.next()); it.next(); it.next(); it.reset(); assertEquals("Four", it.next()); } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/AbstractListIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/AbstractListIte100664 17614 12243235516 32022 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; 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 3.0 * @version $Id: AbstractListIteratorTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractListIteratorTest extends AbstractIteratorTest { /** * JUnit constructor. * * @param testName the test class name */ public AbstractListIteratorTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * Implements the abstract superclass method to return the list iterator. * * @return an empty iterator */ @Override public abstract ListIterator makeEmptyIterator(); /** * Implements the abstract superclass method to return the list iterator. * * @return a full iterator */ @Override public abstract ListIterator makeObject(); /** * 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 E addSetValue() { return null; } //----------------------------------------------------------------------- /** * Test that the empty list iterator contract is correct. */ public void testEmptyListIteratorIsIndeedEmpty() { if (!supportsEmptyIterator()) { return; } final ListIterator it = makeEmptyIterator(); 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 (final NoSuchElementException e) { } // previous() should throw a NoSuchElementException try { it.previous(); fail("NoSuchElementException must be thrown from empty ListIterator"); } catch (final NoSuchElementException e) { } } /** * Test navigation through the iterator. */ public void testWalkForwardAndBack() { final ArrayList list = new ArrayList(); final ListIterator it = makeObject(); 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 (final NoSuchElementException e) { } // loop back through comparing for (int i = list.size() - 1; i >= 0; i--) { assertEquals(i + 1, it.nextIndex()); assertEquals(i, it.previousIndex()); final 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 (final NoSuchElementException e) { } } /** * Test add behaviour. */ public void testAdd() { ListIterator it = makeObject(); final E addValue = addSetValue(); if (!supportsAdd()) { // check for UnsupportedOperationException if not supported try { it.add(addValue); } catch (final UnsupportedOperationException ex) {} return; } // add at start should be OK, added should be previous it = makeObject(); it.add(addValue); assertEquals(addValue, it.previous()); // add at start should be OK, added should not be next it = makeObject(); it.add(addValue); assertTrue(addValue != it.next()); // add in middle and at end should be OK it = makeObject(); while (it.hasNext()) { it.next(); it.add(addValue); // check add OK assertEquals(addValue, it.previous()); it.next(); } } /** * Test set behaviour. */ public void testSet() { final ListIterator it = makeObject(); if (!supportsSet()) { // check for UnsupportedOperationException if not supported try { it.set(addSetValue()); } catch (final UnsupportedOperationException ex) {} return; } // should throw IllegalStateException before next() called try { it.set(addSetValue()); fail(); } catch (final 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() { final ListIterator it = makeObject(); if (supportsRemove() && supportsSet()) { it.next(); it.remove(); try { it.set(addSetValue()); fail("IllegalStateException must be thrown from set after remove"); } catch (final IllegalStateException e) { } } } public void testAddThenSet() { final ListIterator it = makeObject(); // 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 (final IllegalStateException e) { } } } /** * Test remove after add behaviour. */ public void testAddThenRemove() { final ListIterator it = makeObject(); // add then remove if (supportsAdd() && supportsRemove()) { it.next(); it.add(addSetValue()); try { it.remove(); fail("IllegalStateException must be thrown from remove after add"); } catch (final IllegalStateException e) { } } } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/PushbackIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/PushbackIterato100664 6770 12243235516 32032 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.junit.Test; /** * Tests the PushbackIterator. * * @version $Id: PushbackIteratorTest.java 1479763 2013-05-07 05:28:39Z tn $ */ public class PushbackIteratorTest extends AbstractIteratorTest { private String[] testArray = { "a", "b", "c" }; private List testList; public PushbackIteratorTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void setUp() throws Exception { super.setUp(); testList = new ArrayList(Arrays.asList((E[]) testArray)); } @Override public Iterator makeEmptyIterator() { return PushbackIterator.pushbackIterator(Collections. emptyList().iterator()); } @Override public PushbackIterator makeObject() { return PushbackIterator.pushbackIterator(testList.iterator()); } @Override public boolean supportsRemove() { return false; } // ----------------------------------------------------------------------- @Test public void testNormalIteration() { PushbackIterator iter = makeObject(); assertEquals("a", iter.next()); assertEquals("b", iter.next()); assertEquals("c", iter.next()); assertFalse(iter.hasNext()); } @Test @SuppressWarnings("unchecked") public void testImmediatePushback() { PushbackIterator iter = makeObject(); iter.pushback((E) "x"); assertEquals("x", iter.next()); assertEquals("a", iter.next()); validate(iter, "b", "c"); } @Test @SuppressWarnings("unchecked") public void testDelayedPushback() { PushbackIterator iter = makeObject(); assertEquals("a", iter.next()); iter.pushback((E) "x"); assertEquals("x", iter.next()); assertEquals("b", iter.next()); validate(iter, "c"); } @Test @SuppressWarnings("unchecked") public void testMultiplePushback() { PushbackIterator iter = makeObject(); assertEquals("a", iter.next()); iter.pushback((E) "x"); iter.pushback((E) "y"); assertEquals("y", iter.next()); assertEquals("x", iter.next()); assertEquals("b", iter.next()); validate(iter, "c"); } private void validate(Iterator iter, Object... items) { for (final Object x : items) { assertTrue(iter.hasNext()); assertEquals(x, iter.next()); } assertFalse(iter.hasNext()); } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/FilterListIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/FilterListItera100664 42472 12243235516 32027 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.ListIterator; import java.util.Random; import junit.framework.TestCase; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.list.GrowthList; import org.junit.Assert; /** * Tests the FilterListIterator class. * * @version $Id: FilterListIteratorTest.java 1540705 2013-11-11 13:22:32Z ebourg $ */ @SuppressWarnings("boxing") public class FilterListIteratorTest extends TestCase { private ArrayList list = null; private ArrayList odds = null; private ArrayList evens = null; private ArrayList threes = null; private ArrayList fours = null; private ArrayList sixes = null; private Predicate truePred = null; private Predicate falsePred = null; private Predicate evenPred = null; private Predicate oddPred = null; private Predicate threePred = null; private Predicate fourPred = null; private final Random random = new Random(); @Override public void setUp() { list = new ArrayList(); odds = new ArrayList(); evens = new ArrayList(); threes = new ArrayList(); fours = new ArrayList(); sixes = new ArrayList(); for (int i = 0; i < 20; i++) { list.add(Integer.valueOf(i)); if (i % 2 == 0) { evens.add(Integer.valueOf(i)); } if (i % 2 != 0) { odds.add(Integer.valueOf(i)); } if (i % 3 == 0) { threes.add(Integer.valueOf(i)); } if (i % 4 == 0) { fours.add(Integer.valueOf(i)); } if (i % 6 == 0) { sixes.add(Integer.valueOf(i)); } } truePred = new Predicate() { public boolean evaluate(final Integer x) { return true; } }; falsePred = new Predicate() { public boolean evaluate(final Integer x) { return true; } }; evenPred = new Predicate() { public boolean evaluate(final Integer x) { return x % 2 == 0; } }; oddPred = new Predicate() { public boolean evaluate(final Integer x) { return x % 2 != 0; //works for all numbers, not just >= 0 as is the case for "x % 2 == 1" } }; threePred = new Predicate() { public boolean evaluate(final Integer x) { return x % 3 == 0; } }; fourPred = new Predicate() { public boolean evaluate(final Integer x) { return x % 4 == 0; } }; } @Override public void tearDown() throws Exception { list = null; odds = null; evens = null; threes = null; fours = null; sixes = null; truePred = null; falsePred = null; evenPred = null; oddPred = null; threePred = null; fourPred = null; } public void testWalkLists() { // this just confirms that our walkLists method works OK walkLists(list,list.listIterator()); } public void testManual() { // do this one "by hand" as a sanity check final FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); assertEquals(Integer.valueOf(0), filtered.next()); assertEquals(Integer.valueOf(3), filtered.next()); assertEquals(Integer.valueOf(6), filtered.next()); assertEquals(Integer.valueOf(9), filtered.next()); assertEquals(Integer.valueOf(12), filtered.next()); assertEquals(Integer.valueOf(15), filtered.next()); assertEquals(Integer.valueOf(18), filtered.next()); assertEquals(Integer.valueOf(18), filtered.previous()); assertEquals(Integer.valueOf(15), filtered.previous()); assertEquals(Integer.valueOf(12), filtered.previous()); assertEquals(Integer.valueOf(9), filtered.previous()); assertEquals(Integer.valueOf(6), filtered.previous()); assertEquals(Integer.valueOf(3), filtered.previous()); assertEquals(Integer.valueOf(0), filtered.previous()); assertTrue(!filtered.hasPrevious()); assertEquals(Integer.valueOf(0), filtered.next()); assertEquals(Integer.valueOf(3), filtered.next()); assertEquals(Integer.valueOf(6), filtered.next()); assertEquals(Integer.valueOf(9), filtered.next()); assertEquals(Integer.valueOf(12), filtered.next()); assertEquals(Integer.valueOf(15), filtered.next()); assertEquals(Integer.valueOf(18), filtered.next()); assertTrue(!filtered.hasNext()); assertEquals(Integer.valueOf(18), filtered.previous()); assertEquals(Integer.valueOf(15), filtered.previous()); assertEquals(Integer.valueOf(12), filtered.previous()); assertEquals(Integer.valueOf(9), filtered.previous()); assertEquals(Integer.valueOf(6), filtered.previous()); assertEquals(Integer.valueOf(3), filtered.previous()); assertEquals(Integer.valueOf(0), filtered.previous()); assertEquals(Integer.valueOf(0), filtered.next()); assertEquals(Integer.valueOf(0), filtered.previous()); assertEquals(Integer.valueOf(0), filtered.next()); assertEquals(Integer.valueOf(3), filtered.next()); assertEquals(Integer.valueOf(6), filtered.next()); assertEquals(Integer.valueOf(6), filtered.previous()); assertEquals(Integer.valueOf(3), filtered.previous()); assertEquals(Integer.valueOf(3), filtered.next()); assertEquals(Integer.valueOf(6), filtered.next()); assertEquals(Integer.valueOf(9), filtered.next()); assertEquals(Integer.valueOf(12), filtered.next()); assertEquals(Integer.valueOf(15), filtered.next()); assertEquals(Integer.valueOf(15), filtered.previous()); assertEquals(Integer.valueOf(12), filtered.previous()); assertEquals(Integer.valueOf(9), filtered.previous()); } public void testTruePredicate() { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), truePred); walkLists(list, filtered); } public void testFalsePredicate() { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), falsePred); walkLists(new ArrayList(), filtered); } public void testEvens() { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), evenPred); walkLists(evens, filtered); } public void testOdds() { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), oddPred); walkLists(odds, filtered); } public void testThrees() { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); walkLists(threes, filtered); } public void testFours() { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), fourPred); walkLists(fours, filtered); } public void testNestedSixes() { final FilterListIterator filtered = new FilterListIterator( new FilterListIterator(list.listIterator(), threePred), evenPred ); walkLists(sixes, filtered); } public void testNestedSixes2() { final FilterListIterator filtered = new FilterListIterator( new FilterListIterator(list.listIterator(), evenPred), threePred ); walkLists(sixes, filtered); } public void testNestedSixes3() { final FilterListIterator filtered = new FilterListIterator( new FilterListIterator(list.listIterator(), threePred), evenPred ); walkLists(sixes, new FilterListIterator(filtered, truePred)); } public void testNextChangesPrevious() { { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); nextNextPrevious(threes.listIterator(), filtered); } { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), truePred); nextNextPrevious(list.listIterator(), filtered); } } public void testPreviousChangesNext() { { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), threePred); final ListIterator expected = threes.listIterator(); walkForward(expected,filtered); previousPreviousNext(expected,filtered); } { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), truePred); final ListIterator expected = list.listIterator(); walkForward(expected, filtered); previousPreviousNext(expected, filtered); } } public void testFailingHasNextBug() { final FilterListIterator filtered = new FilterListIterator(list.listIterator(), fourPred); final ListIterator expected = fours.listIterator(); while (expected.hasNext()) { expected.next(); filtered.next(); } assertTrue(filtered.hasPrevious()); assertTrue(!filtered.hasNext()); assertEquals(expected.previous(), filtered.previous()); } /** * Test for {@link "https://issues.apache.org/jira/browse/COLLECTIONS-360 COLLECTIONS-360"} */ public void testCollections360() throws Throwable { final Collection> var7 = new GrowthList>(); final Predicate var9 = PredicateUtils.anyPredicate(var7); final FilterListIterator var13 = new FilterListIterator(var9); Assert.assertFalse(var13.hasNext()); final FilterListIterator var14 = new FilterListIterator(var9); Assert.assertFalse(var14.hasPrevious()); } // Utilities private void walkForward(final ListIterator expected, final ListIterator testing) { while (expected.hasNext()) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(testing.hasNext()); assertEquals(expected.next(), testing.next()); } } private void walkBackward(final ListIterator expected, final ListIterator testing) { while (expected.hasPrevious()) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(testing.hasPrevious()); assertEquals(expected.previous(), testing.previous()); } } private void nextNextPrevious(final ListIterator expected, final ListIterator testing) { // calls to next() should change the value returned by previous() // even after previous() has been set by a call to hasPrevious() assertEquals(expected.next(), testing.next()); assertEquals(expected.hasPrevious(), testing.hasPrevious()); final Object expecteda = expected.next(); final Object testinga = testing.next(); assertEquals(expecteda, testinga); final Object expectedb = expected.previous(); final Object testingb = testing.previous(); assertEquals(expecteda, expectedb); assertEquals(testinga, testingb); } private void previousPreviousNext(final ListIterator expected, final ListIterator testing) { // calls to previous() should change the value returned by next() // even after next() has been set by a call to hasNext() assertEquals(expected.previous(), testing.previous()); assertEquals(expected.hasNext(), testing.hasNext()); final Object expecteda = expected.previous(); final Object testinga = testing.previous(); assertEquals(expecteda, testinga); final Object expectedb = expected.next(); final Object testingb = testing.next(); assertEquals(expecteda, testingb); assertEquals(expecteda, expectedb); assertEquals(testinga, testingb); } private void walkLists(final List list, final ListIterator testing) { final ListIterator expected = list.listIterator(); // walk all the way forward walkForward(expected,testing); // walk all the way back walkBackward(expected,testing); // forward,back,forward while (expected.hasNext()) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(testing.hasNext()); assertEquals(expected.next(), testing.next()); assertTrue(testing.hasPrevious()); assertEquals(expected.previous(), testing.previous()); assertTrue(testing.hasNext()); assertEquals(expected.next(), testing.next()); } // walk all the way back walkBackward(expected, testing); for (int i = 0; i < list.size(); i++) { // walk forward i for (int j = 0; j < i; j++) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(expected.hasNext()); // if this one fails we've got a logic error in the test assertTrue(testing.hasNext()); assertEquals(expected.next(), testing.next()); } // walk back i/2 for (int j = 0; j < i / 2; j++) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(expected.hasPrevious()); // if this one fails we've got a logic error in the test assertTrue(testing.hasPrevious()); assertEquals(expected.previous(), testing.previous()); } // walk forward i/2 for (int j = 0; j < i / 2; j++) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(expected.hasNext()); // if this one fails we've got a logic error in the test assertTrue(testing.hasNext()); assertEquals(expected.next(), testing.next()); } // walk back i for (int j = 0; j < i; j++) { assertEquals(expected.nextIndex(), testing.nextIndex()); assertEquals(expected.previousIndex(), testing.previousIndex()); assertTrue(expected.hasPrevious()); // if this one fails we've got a logic error in the test assertTrue(testing.hasPrevious()); assertEquals(expected.previous(), testing.previous()); } } // random walk final StringBuilder walkdescr = new StringBuilder(500); for (int i = 0; i < 500; i++) { if (random.nextBoolean()) { // step forward walkdescr.append("+"); if (expected.hasNext()) { assertEquals(walkdescr.toString(), expected.next(), testing.next()); } } else { // step backward walkdescr.append("-"); if (expected.hasPrevious()) { assertEquals(walkdescr.toString(), expected.previous(), testing.previous()); } } assertEquals(walkdescr.toString(), expected.nextIndex(), testing.nextIndex()); assertEquals(walkdescr.toString(), expected.previousIndex(), testing.previousIndex()); } } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/PeekingIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/PeekingIterator100664 7655 12243235516 32041 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test; /** * Tests the PeekingIterator. * * @version $Id: PeekingIteratorTest.java 1479760 2013-05-07 05:12:06Z tn $ */ public class PeekingIteratorTest extends AbstractIteratorTest { private String[] testArray = { "a", "b", "c" }; private List testList; public PeekingIteratorTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void setUp() throws Exception { super.setUp(); testList = new ArrayList(Arrays.asList((E[]) testArray)); } @Override public Iterator makeEmptyIterator() { return PeekingIterator.peekingIterator(Collections.emptyList().iterator()); } @Override public PeekingIterator makeObject() { return PeekingIterator.peekingIterator(testList.iterator()); } @Override public boolean supportsRemove() { return true; } //----------------------------------------------------------------------- @Test public void testEmpty() { Iterator it = makeEmptyIterator(); assertFalse(it.hasNext()); } @Test @SuppressWarnings("unchecked") public void testSinglePeek() { PeekingIterator it = makeObject(); assertEquals("a", it.peek()); assertEquals("a", it.element()); validate(it, (E[]) testArray); } @Test public void testMultiplePeek() { PeekingIterator it = makeObject(); assertEquals("a", it.peek()); assertEquals("a", it.peek()); assertEquals("a", it.next()); assertTrue(it.hasNext()); assertEquals("b", it.peek()); assertEquals("b", it.peek()); assertEquals("b", it.next()); assertTrue(it.hasNext()); assertEquals("c", it.peek()); assertEquals("c", it.peek()); assertEquals("c", it.next()); assertFalse(it.hasNext()); } @Test public void testIteratorExhausted() { PeekingIterator it = makeObject(); it.next(); it.next(); it.next(); assertFalse(it.hasNext()); assertNull(it.peek()); try { it.element(); fail(); } catch (NoSuchElementException e) { // expected } } @Test public void testIllegalRemove() { PeekingIterator it = makeObject(); it.next(); it.remove(); // supported assertTrue(it.hasNext()); assertEquals("b", it.peek()); try { it.remove(); fail(); } catch (IllegalStateException e) { // expected } } private void validate(Iterator iter, E... items) { for (E x : items) { assertTrue(iter.hasNext()); assertEquals(x, iter.next()); } assertFalse(iter.hasNext()); } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/LoopingListIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/LoopingListIter100664 31502 12243235516 32040 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import junit.framework.TestCase; /** * Tests the LoopingListIterator class. * * @version $Id: LoopingListIteratorTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class LoopingListIteratorTest extends TestCase { /** * Tests constructor exception. */ public void testConstructorEx() throws Exception { try { new LoopingListIterator(null); fail(); } catch (final NullPointerException ex) { } } /** * Tests whether an empty looping list iterator works. */ public void testLooping0() throws Exception { final List list = new ArrayList(); final LoopingListIterator loop = new LoopingListIterator(list); assertFalse(loop.hasNext()); assertFalse(loop.hasPrevious()); try { loop.next(); fail(); } catch (final NoSuchElementException ex) { } try { loop.previous(); fail(); } catch (final NoSuchElementException ex) { } } /** * Tests whether a looping list iterator works on a list with only * one element. */ public void testLooping1() throws Exception { final List list = Arrays.asList("a"); final 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 { final List list = Arrays.asList("a", "b"); final 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() { final List list = Arrays.asList("a", "b"); final 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() { final List list = Arrays.asList("a", "b"); final 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() { final List list = new ArrayList(Arrays.asList("a", "b", "c")); final 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 (final NoSuchElementException ex) { } } /** * Tests removing an element from a wrapped ArrayList. */ public void testRemovingElementsAndIteratingBackwards() { final List list = new ArrayList(Arrays.asList("a", "b", "c")); final 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 (final NoSuchElementException ex) { } } /** * Tests the reset method. */ public void testReset() { final List list = Arrays.asList("a", "b", "c"); final 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("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("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() { final List list = Arrays.asList("a", "b", "c"); final 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() { final List list = Arrays.asList("q", "r", "z"); final 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 } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/NodeListIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/NodeListIterato100664 7704 12243235516 32011 0ustartntn 0 0 /* * Copyright 2013 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; /** * Tests the NodeListIterator. */ public class NodeListIteratorTest extends AbstractIteratorTest { // Node array to be filled with mocked Node instances private Node[] nodes; // NodeListIterator supports two constructors. This flag allows to // control, which constructor to use in makeObject() and makeEmtpyIterator private boolean createIteratorWithStandardConstr = true; /** * Constructor * @param testName */ public NodeListIteratorTest(final String testName) { super(testName); } @Override protected void setUp() throws Exception { super.setUp(); // Default: use standard constr. createIteratorWithStandardConstr = true; // create mocked Node Instances and fill Node[] to be used by test cases final Node node1 = createMock(Element.class); final Node node2 = createMock(Element.class); final Node node3 = createMock(Text.class); final Node node4 = createMock(Element.class); nodes = new Node[] {node1, node2, node3, node4}; replay(node1); replay(node2); replay(node3); replay(node4); } @Override public Iterator makeEmptyIterator() { final NodeList emptyNodeList = new NodeList() { public Node item(final int index) { throw new IndexOutOfBoundsException(); } public int getLength() { return 0; } }; if (createIteratorWithStandardConstr) { return new NodeListIterator(emptyNodeList); } else { final Node parentNode = createMock(Node.class); expect(parentNode.getChildNodes()).andStubReturn(emptyNodeList); replay(parentNode); return new NodeListIterator(parentNode); } } @Override public Iterator makeObject() { final NodeList nodeList = new NodeList() { public Node item(final int index) { return nodes[index]; } public int getLength() { return nodes.length; } }; return new NodeListIterator(nodeList); } @Override public boolean supportsRemove() { return false; } //----------------------------------------------------------------------- public void testNullConstructor(){ try{ new NodeListIterator((Node) null); fail("IllegalArgumentException expected!"); }catch(final IllegalArgumentException e){ // expected. } } /** * tests the convenience Constructor with parameter type org.w3c.Node */ public void testEmptyIteratorWithNodeConstructor(){ createIteratorWithStandardConstr = false; testEmptyIterator(); } /** * tests the convenience Constructor with parameter type org.w3c.Node */ public void testFullIteratorWithNodeConstructor(){ createIteratorWithStandardConstr = false; testFullIterator(); } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/IteratorEnumerationTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/IteratorEnumera100664 3577 12243235516 32052 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import junit.framework.TestCase; /** * Tests the IteratorEnumeration. * * @version $Id: IteratorEnumerationTest.java 1543728 2013-11-20 07:51:32Z ebourg $ */ public class IteratorEnumerationTest extends TestCase { public void testEnumeration() { Iterator iterator = Arrays.asList("a", "b", "c").iterator(); IteratorEnumeration enumeration = new IteratorEnumeration(iterator); assertEquals(iterator, enumeration.getIterator()); assertTrue(enumeration.hasMoreElements()); assertEquals("a", enumeration.nextElement()); assertEquals("b", enumeration.nextElement()); assertEquals("c", enumeration.nextElement()); assertFalse(enumeration.hasMoreElements()); try { enumeration.nextElement(); fail("NoSuchElementException expected"); } catch (NoSuchElementException e) { // expected } } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/AbstractMapIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/AbstractMapIter100664 24720 12243235516 32002 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections4.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 3.0 * @version $Id: AbstractMapIteratorTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractMapIteratorTest extends AbstractIteratorTest { /** * JUnit constructor. * * @param testName the test class name */ public AbstractMapIteratorTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * Implement this method to return a map iterator over an empty map. * * @return an empty iterator */ @Override public abstract MapIterator makeEmptyIterator(); /** * Implement this method to return a map iterator over a map with elements. * * @return a full iterator */ @Override public abstract MapIterator makeObject(); /** * 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(); /** * 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. */ @SuppressWarnings("unchecked") public V[] addSetValues() { return (V[]) new Object[] { "A", "B" }; } //----------------------------------------------------------------------- /** * Test that the empty list iterator contract is correct. */ public void testEmptyMapIterator() { if (!supportsEmptyIterator()) { return; } final MapIterator it = makeEmptyIterator(); assertEquals(false, it.hasNext()); // next() should throw a NoSuchElementException try { it.next(); fail(); } catch (final NoSuchElementException ex) {} // getKey() should throw an IllegalStateException try { it.getKey(); fail(); } catch (final IllegalStateException ex) {} // getValue() should throw an IllegalStateException try { it.getValue(); fail(); } catch (final IllegalStateException ex) {} if (!supportsSetValue()) { // setValue() should throw an UnsupportedOperationException/IllegalStateException try { it.setValue(addSetValues()[0]); fail(); } catch (final UnsupportedOperationException ex) { } catch (final IllegalStateException ex) {} } else { // setValue() should throw an IllegalStateException try { it.setValue(addSetValues()[0]); fail(); } catch (final IllegalStateException ex) {} } } //----------------------------------------------------------------------- /** * Test that the full list iterator contract is correct. */ public void testFullMapIterator() { if (!supportsFullIterator()) { return; } final MapIterator it = makeObject(); final Map map = getMap(); assertEquals(true, it.hasNext()); assertEquals(true, it.hasNext()); final Set set = new HashSet(); while (it.hasNext()) { // getKey final K 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 final V value = it.getValue(); if (!isGetStructuralModify()) { 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()) { return; } final V newValue = addSetValues()[0]; final V newValue2 = addSetValues().length == 1 ? addSetValues()[0] : addSetValues()[1]; final MapIterator it = makeObject(); final Map map = getMap(); final Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); final K key = it.next(); final V value = it.getValue(); if (!supportsSetValue()) { try { it.setValue(newValue); fail(); } catch (final UnsupportedOperationException ex) {} return; } final V 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(); } //----------------------------------------------------------------------- @Override public void testRemove() { // override final MapIterator it = makeObject(); final Map map = getMap(); final Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); final K key = it.next(); if (!supportsRemove()) { try { it.remove(); fail(); } catch (final UnsupportedOperationException ex) { } return; } it.remove(); confirmed.remove(key); assertEquals(false, map.containsKey(key)); verify(); try { it.remove(); // second remove fails } catch (final IllegalStateException ex) { } verify(); } //----------------------------------------------------------------------- public void testMapIteratorSetRemoveSet() { if (!supportsSetValue() || !supportsRemove()) { return; } final V newValue = addSetValues()[0]; final MapIterator it = makeObject(); final Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); final K key = it.next(); it.setValue(newValue); it.remove(); confirmed.remove(key); verify(); try { it.setValue(newValue); fail(); } catch (final IllegalStateException ex) {} verify(); } //----------------------------------------------------------------------- public void testMapIteratorRemoveGetKey() { if (!supportsRemove()) { return; } final MapIterator it = makeObject(); final Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); final K key = it.next(); it.remove(); confirmed.remove(key); verify(); try { it.getKey(); fail(); } catch (final IllegalStateException ex) {} verify(); } //----------------------------------------------------------------------- public void testMapIteratorRemoveGetValue() { if (!supportsRemove()) { return; } final MapIterator it = makeObject(); final Map confirmed = getConfirmedMap(); assertEquals(true, it.hasNext()); final K key = it.next(); it.remove(); confirmed.remove(key); verify(); try { it.getValue(); fail(); } catch (final IllegalStateException ex) {} verify(); } } ././@LongLink100644 0 0 167 12243235652 10263 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableListIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableLis100664 5517 12243235516 32006 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections4.Unmodifiable; /** * Tests the UnmodifiableListIterator. * * @version $Id: UnmodifiableListIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class UnmodifiableListIteratorTest extends AbstractListIteratorTest { protected String[] testArray = { "One", "Two", "Three" }; protected List testList; public UnmodifiableListIteratorTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void setUp() throws Exception { super.setUp(); testList = new ArrayList(Arrays.asList((E[]) testArray)); } @Override public ListIterator makeEmptyIterator() { return UnmodifiableListIterator.umodifiableListIterator(Collections.emptyList().listIterator()); } @Override public ListIterator makeObject() { return UnmodifiableListIterator.umodifiableListIterator(testList.listIterator()); } @Override public boolean supportsRemove() { return false; } @Override public boolean supportsAdd() { return false; } @Override public boolean supportsSet() { return false; } //----------------------------------------------------------------------- public void testListIterator() { assertTrue(makeEmptyIterator() instanceof Unmodifiable); } public void testDecorateFactory() { ListIterator it = makeObject(); assertSame(it, UnmodifiableListIterator.umodifiableListIterator(it)); it = testList.listIterator(); assertTrue(it != UnmodifiableListIterator.umodifiableListIterator(it)); try { UnmodifiableListIterator.umodifiableListIterator(null); fail(); } catch (final IllegalArgumentException ex) {} } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableIte100664 5134 12243235516 31773 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.commons.collections4.Unmodifiable; /** * Tests the UnmodifiableIterator. * * @version $Id: UnmodifiableIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class UnmodifiableIteratorTest extends AbstractIteratorTest { protected String[] testArray = { "One", "Two", "Three" }; protected List testList; public UnmodifiableIteratorTest(final String testName) { super(testName); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected void setUp() throws Exception { super.setUp(); testList = new ArrayList(Arrays.asList((E[]) testArray)); } @Override public Iterator makeEmptyIterator() { return UnmodifiableIterator.unmodifiableIterator(Collections.emptyList().iterator()); } @Override public Iterator makeObject() { return UnmodifiableIterator.unmodifiableIterator(testList.iterator()); } @Override public boolean supportsRemove() { return false; } //----------------------------------------------------------------------- public void testIterator() { assertTrue(makeEmptyIterator() instanceof Unmodifiable); } public void testDecorateFactory() { Iterator it = makeObject(); assertSame(it, UnmodifiableIterator.unmodifiableIterator(it)); it = testList.iterator(); assertTrue(it != UnmodifiableIterator.unmodifiableIterator(it)); try { UnmodifiableIterator.unmodifiableIterator(null); fail(); } catch (final IllegalArgumentException ex) {} } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ArrayIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ArrayIteratorTe100664 5341 12243235516 32014 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; /** * Tests the ArrayIterator to ensure that the next() method will actually * perform the iteration rather than the hasNext() method. * The code of this test was supplied by Mauricio S. Moura. * * @version $Id: ArrayIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ArrayIteratorTest extends AbstractIteratorTest { protected String[] testArray = { "One", "Two", "Three" }; public ArrayIteratorTest(final String testName) { super(testName); } @Override public ArrayIterator makeEmptyIterator() { return new ArrayIterator(new Object[0]); } @Override public ArrayIterator makeObject() { return new ArrayIterator(testArray); } @Override public boolean supportsRemove() { return false; } public void testIterator() { final Iterator iter = makeObject(); for (final String testValue : testArray) { final E iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (final Exception e) { assertTrue( "NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } public void testNullArray() { try { new ArrayIterator(null); fail("Constructor should throw a NullPointerException when constructed with a null array"); } catch (final NullPointerException e) { // expected } } public void testReset() { final ArrayIterator it = makeObject(); it.next(); it.reset(); assertEquals("One", it.next()); } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ArrayListIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ArrayListIterat100664 7431 12243235516 32020 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Arrays; import java.util.ListIterator; import java.util.NoSuchElementException; /** * Test the ArrayListIterator class. * * @version $Id: ArrayListIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ArrayListIteratorTest extends ArrayIteratorTest { public ArrayListIteratorTest(final String testName) { super(testName); } @Override public ArrayListIterator makeEmptyIterator() { return new ArrayListIterator(new Object[0]); } @Override public ArrayListIterator makeObject() { return new ArrayListIterator(testArray); } public ArrayListIterator makeArrayListIterator(final Object array) { return new ArrayListIterator(array); } @Override public boolean supportsRemove() { return false; } /** * Test the basic ListIterator functionality - going backwards using * previous(). */ public void testListIterator() { final ListIterator iter = makeObject(); // 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--) { final Object testValue = testArray[x]; final Object iterValue = iter.previous(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasPrevious()); try { iter.previous(); } catch (final Exception e) { assertTrue( "NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } /** * Tests the {@link java.util.ListIterator#set} operation. */ @SuppressWarnings("unchecked") public void testListIteratorSet() { final String[] testData = new String[] { "a", "b", "c" }; final String[] result = new String[] { "0", "1", "2" }; ListIterator iter = makeArrayListIterator(testData); int x = 0; while (iter.hasNext()) { iter.next(); iter.set((E) 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((E) "should fail"); fail("ListIterator#set should fail if next() or previous() have not yet been called."); } catch (final IllegalStateException e) { // expected } catch (final Throwable t) { // should never happen fail(t.toString()); } } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ArrayIterator2Test.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ArrayIterator2T100664 12060 12243235516 31745 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; /** * Tests the ArrayIterator with primitive type arrays. * * @version $Id: ArrayIterator2Test.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ArrayIterator2Test extends AbstractIteratorTest { protected int[] testArray = { 2, 4, 6, 8 }; public ArrayIterator2Test(final String testName) { super(testName); } @Override public ArrayIterator makeEmptyIterator() { return new ArrayIterator(new int[0]); } @Override public ArrayIterator makeObject() { return new ArrayIterator(testArray); } public ArrayIterator makeArrayIterator(final Object array) { return new ArrayIterator(array); } public ArrayIterator makeArrayIterator(final Object array, final int index) { return new ArrayIterator(array, index); } public ArrayIterator makeArrayIterator(final Object array, final int start, final int end) { return new ArrayIterator(array, start, end); } @Override public boolean supportsRemove() { return false; } public void testIterator() { final Iterator iter = makeObject(); for (final int element : testArray) { final Integer testValue = Integer.valueOf(element); final Number iterValue = (Number) iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (final Exception e) { assertTrue( "NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } 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 (final ArrayIndexOutOfBoundsException aioobe) { // expected } try { iter = makeArrayIterator(testArray, testArray.length + 1); fail("new ArrayIterator(Object,length+1) should throw an ArrayIndexOutOfBoundsException"); } catch (final ArrayIndexOutOfBoundsException aioobe) { // expected } try { iter = makeArrayIterator(testArray, 0, -1); fail("new ArrayIterator(Object,0,-1) should throw an ArrayIndexOutOfBoundsException"); } catch (final ArrayIndexOutOfBoundsException aioobe) { // expected } try { iter = makeArrayIterator(testArray, 0, testArray.length + 1); fail("new ArrayIterator(Object,0,length+1) should throw an ArrayIndexOutOfBoundsException"); } catch (final ArrayIndexOutOfBoundsException aioobe) { // expected } try { iter = makeArrayIterator(testArray, 1, 1); // expected not to fail } catch (final 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 (final IllegalArgumentException iae) { // expected } } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWrapperTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWra100664 17234 12243235516 32056 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableListIterator; /** * Tests the ListIteratorWrapper to insure that it simulates * a ListIterator correctly. * * @version $Id: ListIteratorWrapperTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ListIteratorWrapperTest extends AbstractIteratorTest { protected String[] testArray = { "One", "Two", "Three", "Four", "Five", "Six" }; protected List list1 = null; public ListIteratorWrapperTest(final String testName) { super(testName); } @Override @SuppressWarnings("unchecked") public void setUp() { list1 = new ArrayList(); list1.add((E) "One"); list1.add((E) "Two"); list1.add((E) "Three"); list1.add((E) "Four"); list1.add((E) "Five"); list1.add((E) "Six"); } @Override public ResettableListIterator makeEmptyIterator() { final ArrayList list = new ArrayList(); return new ListIteratorWrapper(list.iterator()); } @Override public ResettableListIterator makeObject() { return new ListIteratorWrapper(list1.iterator()); } public void testIterator() { final ListIterator iter = makeObject(); for (final String testValue : testArray) { final Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (final Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } // now, read it backwards for (int i = testArray.length - 1; i > -1; --i) { final Object testValue = testArray[i]; final E iterValue = iter.previous(); assertEquals( "Iteration value is correct", testValue, iterValue ); } try { iter.previous(); } catch (final Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } // now, read it forwards again for (final String testValue : testArray) { final Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } } @Override public void testRemove() { final ListIterator iter = makeObject(); //initial state: assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); try { iter.remove(); fail("ListIteratorWrapper#remove() should fail; must be initially positioned first"); } catch (final IllegalStateException e) { } //no change from invalid op: assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); //establish size: int sz = list1.size(); //verify initial next() call: assertEquals(list1.get(0), iter.next()); assertEquals(0, iter.previousIndex()); assertEquals(1, iter.nextIndex()); //verify remove(): iter.remove(); assertEquals(--sz, list1.size()); //like we never started iterating: assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); try { iter.remove(); fail("ListIteratorWrapper#remove() should fail; must be repositioned first"); } catch (final IllegalStateException e) { } //no change from invalid op: assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); //two consecutive next() calls: assertEquals(list1.get(0), iter.next()); assertEquals(0, iter.previousIndex()); assertEquals(1, iter.nextIndex()); assertEquals(list1.get(1), iter.next()); assertEquals(1, iter.previousIndex()); assertEquals(2, iter.nextIndex()); //call previous(): assertEquals(list1.get(1), iter.previous()); assertEquals(0, iter.previousIndex()); assertEquals(1, iter.nextIndex()); //should support remove() after calling previous() once from tip because we haven't changed the underlying iterator's position: iter.remove(); assertEquals(--sz, list1.size()); assertEquals(0, iter.previousIndex()); assertEquals(1, iter.nextIndex()); //dig into cache assertEquals(list1.get(0), iter.previous()); assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); try { iter.remove(); fail("ListIteratorWrapper does not support the remove() method while dug into the cache via previous()"); } catch (final IllegalStateException e) { } //no change from invalid op: assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); //dig out of cache, first next() maintains current position: assertEquals(list1.get(0), iter.next()); assertEquals(0, iter.previousIndex()); assertEquals(1, iter.nextIndex()); //continue traversing underlying iterator with this next() call, and we're out of the hole, so to speak: assertEquals(list1.get(1), iter.next()); assertEquals(1, iter.previousIndex()); assertEquals(2, iter.nextIndex()); //verify remove() works again: iter.remove(); assertEquals(--sz, list1.size()); assertEquals(0, iter.previousIndex()); assertEquals(1, iter.nextIndex()); assertEquals(list1.get(1), iter.next()); assertEquals(1, iter.previousIndex()); assertEquals(2, iter.nextIndex()); } public void testReset() { final ResettableListIterator iter = makeObject(); final E first = iter.next(); final E 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++) { final Object testValue = testArray[i]; final E iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } } } ././@LongLink100644 0 0 167 12243235652 10263 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayListIterator2Test.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayList100664 3555 12243235516 32001 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; /** * Tests the ObjectArrayListIterator class. * * @version $Id: ObjectArrayListIterator2Test.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ObjectArrayListIterator2Test extends AbstractListIteratorTest { protected String[] testArray = { "One", "Two", "Three" }; public ObjectArrayListIterator2Test(final String testName) { super(testName); } @Override @SuppressWarnings("unchecked") public ObjectArrayListIterator makeEmptyIterator() { return new ObjectArrayListIterator((E[]) new Object[0]); } @Override @SuppressWarnings("unchecked") public ObjectArrayListIterator makeObject() { return new ObjectArrayListIterator((E[]) testArray); } public ObjectArrayListIterator makeArrayListIterator(final E[] array) { return new ObjectArrayListIterator(array); } @Override public boolean supportsAdd() { return false; } @Override public boolean supportsRemove() { return false; } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/CollatingIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/CollatingIterat100664 25062 12243235516 32042 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import org.apache.commons.collections4.comparators.ComparableComparator; /** * Unit test suite for {@link CollatingIterator}. * * @version $Id: CollatingIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("boxing") public class CollatingIteratorTest extends AbstractIteratorTest { //------------------------------------------------------------ Conventional public CollatingIteratorTest(final String testName) { super(testName); } //--------------------------------------------------------------- Lifecycle private Comparator comparator = null; private ArrayList evens = null; private ArrayList odds = null; private ArrayList fib = null; @Override 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(i); } else { odds.add(i); } } fib = new ArrayList(); fib.add(1); fib.add(1); fib.add(2); fib.add(3); fib.add(5); fib.add(8); fib.add(13); fib.add(21); } //---------------------------------------------------- TestIterator Methods @Override public CollatingIterator makeEmptyIterator() { return new CollatingIterator(comparator); } @Override public CollatingIterator makeObject() { final CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); iter.addIterator(odds.iterator()); iter.addIterator(fib.iterator()); return iter; } //------------------------------------------------------------------- Tests public void testGetSetComparator() { final CollatingIterator iter = new CollatingIterator(); assertNull(iter.getComparator()); iter.setComparator(comparator); assertSame(comparator, iter.getComparator()); iter.setComparator(null); assertNull(iter.getComparator()); } public void testIterateEven() { final CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); for (int i = 0; i < evens.size(); i++) { assertTrue(iter.hasNext()); assertEquals(evens.get(i), iter.next()); assertEquals(0,iter.getIteratorIndex()); } assertTrue(!iter.hasNext()); } public void testIterateEvenOdd() { final CollatingIterator iter = new CollatingIterator(comparator, evens.iterator(), odds.iterator()); for (int i = 0; i < 20; i++) { assertTrue(iter.hasNext()); assertEquals(Integer.valueOf(i), iter.next()); assertEquals(i % 2,iter.getIteratorIndex()); } assertTrue(!iter.hasNext()); } public void testIterateOddEven() { final CollatingIterator iter = new CollatingIterator(comparator, odds.iterator(), evens.iterator()); for (int i = 0; i < 20; i++) { assertTrue(iter.hasNext()); assertEquals(Integer.valueOf(i),iter.next()); assertEquals(i % 2 == 0 ? 1 : 0,iter.getIteratorIndex()); } assertTrue(!iter.hasNext()); } public void testIterateEvenEven() { final CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); iter.addIterator(evens.iterator()); for (int i = 0; i < evens.size(); i++) { assertTrue(iter.hasNext()); assertEquals(evens.get(i), iter.next()); assertEquals(0,iter.getIteratorIndex()); assertTrue(iter.hasNext()); assertEquals(evens.get(i), iter.next()); assertEquals(1,iter.getIteratorIndex()); } assertTrue(!iter.hasNext()); } public void testIterateFibEvenOdd() { final CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(fib.iterator()); iter.addIterator(evens.iterator()); iter.addIterator(odds.iterator()); assertEquals(Integer.valueOf(0),iter.next()); // even 0 assertEquals(1,iter.getIteratorIndex()); assertEquals(Integer.valueOf(1),iter.next()); // fib 1 assertEquals(0,iter.getIteratorIndex()); assertEquals(Integer.valueOf(1),iter.next()); // fib 1 assertEquals(0,iter.getIteratorIndex()); assertEquals(Integer.valueOf(1),iter.next()); // odd 1 assertEquals(2,iter.getIteratorIndex()); assertEquals(Integer.valueOf(2),iter.next()); // fib 2 assertEquals(0,iter.getIteratorIndex()); assertEquals(Integer.valueOf(2),iter.next()); // even 2 assertEquals(1,iter.getIteratorIndex()); assertEquals(Integer.valueOf(3),iter.next()); // fib 3 assertEquals(0,iter.getIteratorIndex()); assertEquals(Integer.valueOf(3),iter.next()); // odd 3 assertEquals(2,iter.getIteratorIndex()); assertEquals(Integer.valueOf(4),iter.next()); // even 4 assertEquals(1,iter.getIteratorIndex()); assertEquals(Integer.valueOf(5),iter.next()); // fib 5 assertEquals(0,iter.getIteratorIndex()); assertEquals(Integer.valueOf(5),iter.next()); // odd 5 assertEquals(2,iter.getIteratorIndex()); assertEquals(Integer.valueOf(6),iter.next()); // even 6 assertEquals(1,iter.getIteratorIndex()); assertEquals(Integer.valueOf(7),iter.next()); // odd 7 assertEquals(2,iter.getIteratorIndex()); assertEquals(Integer.valueOf(8),iter.next()); // fib 8 assertEquals(0,iter.getIteratorIndex()); assertEquals(Integer.valueOf(8),iter.next()); // even 8 assertEquals(1,iter.getIteratorIndex()); assertEquals(Integer.valueOf(9),iter.next()); // odd 9 assertEquals(2,iter.getIteratorIndex()); assertEquals(Integer.valueOf(10),iter.next()); // even 10 assertEquals(1,iter.getIteratorIndex()); assertEquals(Integer.valueOf(11),iter.next()); // odd 11 assertEquals(2,iter.getIteratorIndex()); assertEquals(Integer.valueOf(12),iter.next()); // even 12 assertEquals(1,iter.getIteratorIndex()); assertEquals(Integer.valueOf(13),iter.next()); // fib 13 assertEquals(0,iter.getIteratorIndex()); assertEquals(Integer.valueOf(13),iter.next()); // odd 13 assertEquals(2,iter.getIteratorIndex()); assertEquals(Integer.valueOf(14),iter.next()); // even 14 assertEquals(1,iter.getIteratorIndex()); assertEquals(Integer.valueOf(15),iter.next()); // odd 15 assertEquals(2,iter.getIteratorIndex()); assertEquals(Integer.valueOf(16),iter.next()); // even 16 assertEquals(1,iter.getIteratorIndex()); assertEquals(Integer.valueOf(17),iter.next()); // odd 17 assertEquals(2,iter.getIteratorIndex()); assertEquals(Integer.valueOf(18),iter.next()); // even 18 assertEquals(1,iter.getIteratorIndex()); assertEquals(Integer.valueOf(19),iter.next()); // odd 19 assertEquals(2,iter.getIteratorIndex()); assertEquals(Integer.valueOf(21),iter.next()); // fib 21 assertEquals(0,iter.getIteratorIndex()); assertTrue(!iter.hasNext()); } public void testRemoveFromSingle() { final CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); int expectedSize = evens.size(); while (iter.hasNext()) { final Object o = iter.next(); final Integer val = (Integer) o; if (val.intValue() % 4 == 0) { expectedSize--; iter.remove(); } } assertEquals(expectedSize,evens.size()); } public void testRemoveFromDouble() { final CollatingIterator iter = new CollatingIterator(comparator); iter.addIterator(evens.iterator()); iter.addIterator(odds.iterator()); int expectedSize = evens.size() + odds.size(); while (iter.hasNext()) { final Object o = iter.next(); final Integer val = (Integer) o; if (val.intValue() % 4 == 0 || val.intValue() % 3 == 0) { expectedSize--; iter.remove(); } } assertEquals(expectedSize, evens.size() + odds.size()); } public void testNullComparator() { final List l1 = Arrays.asList(1, 3, 5); final List l2 = Arrays.asList(2, 4, 6); final CollatingIterator collatingIterator1 = new CollatingIterator(null, l1.iterator(), l2.iterator()); try { collatingIterator1.next(); } catch (final NullPointerException e) { assertTrue(e.getMessage().startsWith("You must invoke setComparator")); } int i = 0; final CollatingIterator collatingIterator2 = new CollatingIterator(null, l1.iterator(), l2.iterator()); collatingIterator2.setComparator(new ComparableComparator()); for ( ; collatingIterator2.hasNext(); i++ ) { final Integer n = collatingIterator2.next(); assertEquals("wrong order", (int)n, i + 1); } assertEquals("wrong size", i, l1.size() + l2.size()); } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/IteratorIterableTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/IteratorIterabl100664 5126 12243235516 32030 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; /** * Tests for IteratorIterable. * * @version $Id: IteratorIterableTest.java 1541722 2013-11-13 21:14:15Z tn $ */ public class IteratorIterableTest extends BulkTest { public static Test suite() { return BulkTest.makeSuite(IteratorIterableTest.class); } public IteratorIterableTest(final String name) { super(name); } private Iterator createIterator() { final List list = new ArrayList(); list.add(Integer.valueOf(0)); list.add(Integer.valueOf(1)); list.add(Integer.valueOf(2)); final Iterator iter = list.iterator(); return iter; } @SuppressWarnings("unused") public void testIterator() { final Iterator iter = createIterator(); final Iterable iterable = new IteratorIterable(iter); // first use verifyIteration(iterable); // second use for (final Number actual : iterable) { fail("should not be able to iterate twice"); } } public void testMultipleUserIterator() { final Iterator iter = createIterator(); final Iterable iterable = new IteratorIterable(iter, true); // first use verifyIteration(iterable); // second use verifyIteration(iterable); } private void verifyIteration(final Iterable iterable) { int expected = 0; for (final Number actual : iterable) { assertEquals(expected, actual.intValue()); ++expected; } assertTrue(expected > 0); } } ././@LongLink100644 0 0 171 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/AbstractOrderedMapIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/AbstractOrdered100664 13026 12243235516 32022 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.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 3.0 * @version $Id: AbstractOrderedMapIteratorTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractOrderedMapIteratorTest extends AbstractMapIteratorTest { /** * JUnit constructor. * * @param testName the test class name */ public AbstractOrderedMapIteratorTest(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override public abstract OrderedMapIterator makeEmptyIterator(); @Override public abstract OrderedMapIterator makeObject(); //----------------------------------------------------------------------- /** * Test that the empty list iterator contract is correct. */ @Override public void testEmptyMapIterator() { if (!supportsEmptyIterator()) { return; } super.testEmptyMapIterator(); final OrderedMapIterator it = makeEmptyIterator(); assertEquals(false, it.hasPrevious()); try { it.previous(); fail(); } catch (final NoSuchElementException ex) {} } //----------------------------------------------------------------------- /** * Test that the full list iterator contract is correct. */ @Override public void testFullMapIterator() { if (!supportsFullIterator()) { return; } super.testFullMapIterator(); final OrderedMapIterator it = makeObject(); final Map map = getMap(); assertEquals(true, it.hasNext()); assertEquals(false, it.hasPrevious()); final Set set = new HashSet(); while (it.hasNext()) { // getKey final K 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 final V value = it.getValue(); if (!isGetStructuralModify()) { 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 final 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 final Object value = it.getValue(); if (!isGetStructuralModify()) { 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()) { return; } final OrderedMapIterator it = makeObject(); final Map map = getMap(); assertEquals("keySet() not consistent", new ArrayList(map.keySet()), new ArrayList(map.keySet())); final Iterator it2 = map.keySet().iterator(); assertEquals(true, it.hasNext()); assertEquals(true, it2.hasNext()); final List list = new ArrayList(); while (it.hasNext()) { final K key = it.next(); assertEquals(it2.next(), key); list.add(key); } assertEquals(map.size(), list.size()); while (it.hasPrevious()) { final K key = it.previous(); assertEquals(list.get(list.size() - 1), key); list.remove(list.size() - 1); } assertEquals(0, list.size()); } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/PermutationIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/PermutationIter100664 14145 12243235516 32110 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; /** * Test class for PermutationIterator. * * @version $Id: PermutationIteratorTest.java 1477789 2013-04-30 19:28:27Z sebb $ * @since 4.0 */ public class PermutationIteratorTest extends AbstractIteratorTest> { @SuppressWarnings("boxing") // OK in test code protected Character[] testArray = { 'A', 'B', 'C' }; protected List testList; public PermutationIteratorTest(final String testName) { super(testName); } @Override public void setUp() { testList = new ArrayList(); testList.addAll(Arrays.asList(testArray)); } //----------------------------------------------------------------------- @Override public boolean supportsRemove() { return false; } @Override public boolean supportsEmptyIterator() { return false; } @Override public PermutationIterator makeEmptyIterator() { return new PermutationIterator(new ArrayList()); } @Override public PermutationIterator makeObject() { return new PermutationIterator(testList); } //----------------------------------------------------------------------- @SuppressWarnings("boxing") // OK in test code public void testPermutationResultSize() { int factorial = 1; for (int i = 0; i < 8; i++, factorial*=i) { List list = new ArrayList(); for (int j = 0; j < i; j++) { list.add(j); } Iterator> it = new PermutationIterator(list); int count = 0; while (it.hasNext()) { it.next(); count++; } assertEquals(factorial, count); } } /** * test checking that all the permutations are returned */ @SuppressWarnings("boxing") // OK in test code public void testPermutationExhaustivity() { List perm1 = new ArrayList(); List perm2 = new ArrayList(); List perm3 = new ArrayList(); List perm4 = new ArrayList(); List perm5 = new ArrayList(); List perm6 = new ArrayList(); perm1.add('A'); perm2.add('A'); perm3.add('B'); perm4.add('B'); perm5.add('C'); perm6.add('C'); perm1.add('B'); perm2.add('C'); perm3.add('A'); perm4.add('C'); perm5.add('A'); perm6.add('B'); perm1.add('C'); perm2.add('B'); perm3.add('C'); perm4.add('A'); perm5.add('B'); perm6.add('A'); List> results = new ArrayList>(); PermutationIterator it = makeObject(); while (it.hasNext()) { List next = it.next(); results.add(next); } //3! permutation for 3 elements assertEquals(6, results.size()); assertTrue(results.contains(perm1)); assertTrue(results.contains(perm2)); assertTrue(results.contains(perm3)); assertTrue(results.contains(perm4)); assertTrue(results.contains(perm5)); assertTrue(results.contains(perm6)); } /** * test checking that all the permutations are returned only once. */ public void testPermutationUnicity() { List> resultsList = new ArrayList>(); Set> resultsSet = new HashSet>(); PermutationIterator it = makeObject(); while (it.hasNext()) { List permutation = it.next(); resultsList.add(permutation); resultsSet.add(permutation); } //3! permutation for 3 elements assertEquals(6, resultsList.size()); assertEquals(6, resultsSet.size()); } public void testPermutationException() { List> resultsList = new ArrayList>(); PermutationIterator it = makeObject(); while (it.hasNext()) { List permutation = it.next(); resultsList.add(permutation); } //asking for another permutation should throw an exception try { it.next(); fail(); } catch (NoSuchElementException e) { // expected } } public void testPermutatorHasMore() { PermutationIterator it = makeObject(); for (int i = 0; i < 6; i++) { assertTrue(it.hasNext()); it.next(); } assertFalse(it.hasNext()); } public void testEmptyCollection() { PermutationIterator it = makeEmptyIterator(); // there is one permutation for an empty set: 0! = 1 assertTrue(it.hasNext()); List nextPermutation = it.next(); assertEquals(0, nextPermutation.size()); assertFalse(it.hasNext()); } }././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/FilterIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/FilterIteratorT100664 16072 12243235516 32041 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import static org.apache.commons.collections4.functors.TruePredicate.truePredicate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.NotNullPredicate; /** * Test the filter iterator. * * @version $Id: FilterIteratorTest.java 1541722 2013-11-13 21:14:15Z tn $ */ public class FilterIteratorTest extends AbstractIteratorTest { /** Creates new TestFilterIterator */ public FilterIteratorTest(final String name) { super(name); } private String[] array; private List list; private FilterIterator iterator; /** * Set up instance variables required by this test case. */ @Override public void setUp() { array = new String[] { "a", "b", "c" }; initIterator(); } /** * Tear down instance variables required by this test case. */ @Override public void tearDown() throws Exception { iterator = null; } /** * Returns an full iterator wrapped in a * FilterIterator that blocks all the elements * * @return "empty" FilterIterator */ @Override public FilterIterator makeEmptyIterator() { return makeBlockAllFilter(new ArrayIterator(array)); } /** * Returns an array with elements wrapped in a pass-through * FilterIterator * * @return a filtered iterator */ @Override @SuppressWarnings("unchecked") public FilterIterator makeObject() { list = new ArrayList(Arrays.asList((E[]) array)); return makePassThroughFilter(list.iterator()); } public void testRepeatedHasNext() { for (int i = 0; i <= array.length; i++) { assertTrue(iterator.hasNext()); } } @SuppressWarnings("unused") public void testRepeatedNext() { for (final String element : array) { iterator.next(); } verifyNoMoreElements(); } public void testReturnValues() { verifyElementsInPredicate(new String[0]); verifyElementsInPredicate(new String[] { "a" }); verifyElementsInPredicate(new String[] { "b" }); verifyElementsInPredicate(new String[] { "c" }); verifyElementsInPredicate(new String[] { "a", "b" }); verifyElementsInPredicate(new String[] { "a", "c" }); verifyElementsInPredicate(new String[] { "b", "c" }); verifyElementsInPredicate(new String[] { "a", "b", "c" }); } /** * Test that when the iterator is changed, the hasNext method returns the * correct response for the new iterator. */ @SuppressWarnings("unchecked") public void testSetIterator() { final Iterator iter1 = Collections.singleton((E) new Object()).iterator(); final Iterator iter2 = Collections.emptyList().iterator(); final FilterIterator filterIterator = new FilterIterator(iter1); filterIterator.setPredicate(truePredicate()); // this iterator has elements assertEquals(true, filterIterator.hasNext()); // this iterator has no elements filterIterator.setIterator(iter2); assertEquals(false, filterIterator.hasNext()); } /** * Test that when the predicate is changed, the hasNext method returns the * correct response for the new predicate. */ public void testSetPredicate() { final Iterator iter = Collections.singleton((E) null).iterator(); final FilterIterator filterIterator = new FilterIterator(iter); filterIterator.setPredicate(truePredicate()); // this predicate matches assertEquals(true, filterIterator.hasNext()); // this predicate doesn't match filterIterator.setPredicate(NotNullPredicate.notNullPredicate()); assertEquals(false, filterIterator.hasNext()); } private void verifyNoMoreElements() { assertTrue(!iterator.hasNext()); try { iterator.next(); fail("NoSuchElementException expected"); } catch (final NoSuchElementException e) { // success } } private void verifyElementsInPredicate(final String[] elements) { final Predicate pred = new Predicate() { public boolean evaluate(final E x) { for (final String element : elements) { if (element.equals(x)) { return true; } } return false; } }; initIterator(); iterator.setPredicate(pred); for (int i = 0; i < elements.length; i++) { final String s = (String)iterator.next(); assertEquals(elements[i], s); assertTrue(i == elements.length - 1 ? !iterator.hasNext() : iterator.hasNext()); } verifyNoMoreElements(); // test removal initIterator(); iterator.setPredicate(pred); if (iterator.hasNext()) { final Object last = iterator.next(); iterator.remove(); assertTrue("Base of FilterIterator still contains removed element.", !list.contains(last)); } } private void initIterator() { iterator = makeObject(); } /** * Returns a FilterIterator that does not filter * any of its elements * * @param i the Iterator to "filter" * @return "filtered" iterator */ protected FilterIterator makePassThroughFilter(final Iterator i) { final Predicate pred = new Predicate() { public boolean evaluate(final E x) { return true; } }; return new FilterIterator(i, pred); } /** * Returns a FilterIterator that blocks * all of its elements * * @param i the Iterator to "filter" * @return "filtered" iterator */ protected FilterIterator makeBlockAllFilter(final Iterator i) { final Predicate pred = new Predicate() { public boolean evaluate(final E x) { return false; } }; return new FilterIterator(i, pred); } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ArrayListIterator2Test.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ArrayListIterat100664 3524 12243235516 32017 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; /** * Test the ArrayListIterator class with primitives. * * @version $Id: ArrayListIterator2Test.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ArrayListIterator2Test extends ArrayIterator2Test { public ArrayListIterator2Test(final String testName) { super(testName); } @Override public ArrayListIterator makeEmptyIterator() { return new ArrayListIterator(new int[0]); } @Override public ArrayListIterator makeObject() { return new ArrayListIterator(testArray); } public ArrayListIterator makeArrayListIterator(final Object array) { return new ArrayListIterator(array); } public ArrayListIterator makeArrayListIterator(final Object array, final int index) { return new ArrayListIterator(array, index); } public ArrayListIterator makeArrayListIterator(final Object array, final int start, final int end) { return new ArrayListIterator(array, start, end); } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ObjectGraphIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ObjectGraphIter100664 34642 12243235516 31775 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.collections4.Transformer; /** * Testcase. * * @version $Id: ObjectGraphIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ObjectGraphIteratorTest extends AbstractIteratorTest { 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 ObjectGraphIteratorTest(final String testName) { super(testName); } @Override 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()); } //----------------------------------------------------------------------- @Override public ObjectGraphIterator makeEmptyIterator() { final ArrayList list = new ArrayList(); return new ObjectGraphIterator(list.iterator()); } @Override public ObjectGraphIterator makeObject() { return new ObjectGraphIterator(iteratorList.iterator()); } //----------------------------------------------------------------------- public void testIteratorConstructor_null1() { final Iterator it = new ObjectGraphIterator(null); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (final NoSuchElementException ex) { } try { it.remove(); fail(); } catch (final IllegalStateException ex) { } } public void testIteratorConstructor_null_next() { final Iterator it = new ObjectGraphIterator(null); try { it.next(); fail(); } catch (final NoSuchElementException ex) { } } public void testIteratorConstructor_null_remove() { final Iterator it = new ObjectGraphIterator(null); try { it.remove(); fail(); } catch (final IllegalStateException ex) { } } //----------------------------------------------------------------------- public void testIteratorConstructorIteration_Empty() { final List> iteratorList = new ArrayList>(); final Iterator it = new ObjectGraphIterator(iteratorList.iterator()); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (final NoSuchElementException ex) { } try { it.remove(); fail(); } catch (final IllegalStateException ex) { } } public void testIteratorConstructorIteration_Simple() { final List> iteratorList = new ArrayList>(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); final 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 (final NoSuchElementException ex) { } } public void testIteratorConstructorIteration_SimpleNoHasNext() { final List> iteratorList = new ArrayList>(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); final Iterator it = new ObjectGraphIterator(iteratorList.iterator()); for (int i = 0; i < 6; i++) { assertEquals(testArray[i], it.next()); } try { it.next(); fail(); } catch (final NoSuchElementException ex) { } } public void testIteratorConstructorIteration_WithEmptyIterators() { final List> iteratorList = new ArrayList>(); iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list1.iterator()); iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list2.iterator()); iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list3.iterator()); iteratorList.add(IteratorUtils.emptyIterator()); final 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 (final NoSuchElementException ex) { } } public void testIteratorConstructorRemove() { final List> iteratorList = new ArrayList>(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); final 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() { final List> iteratorList = new ArrayList>(); iteratorList.add(list1.iterator()); iteratorList.add(list2.iterator()); iteratorList.add(list3.iterator()); final 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() { final List> iteratorList = new ArrayList>(); iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list1.iterator()); iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list2.iterator()); iteratorList.add(IteratorUtils.emptyIterator()); iteratorList.add(list3.iterator()); iteratorList.add(IteratorUtils.emptyIterator()); final 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() { final Iterator it = new ObjectGraphIterator(null, null); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (final NoSuchElementException ex) { } try { it.remove(); fail(); } catch (final IllegalStateException ex) { } } public void testIteration_RootNoTransformer() { final Forest forest = new Forest(); final Iterator it = new ObjectGraphIterator(forest, null); assertEquals(true, it.hasNext()); assertSame(forest, it.next()); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (final NoSuchElementException ex) { } } public void testIteration_Transformed1() { final Forest forest = new Forest(); final Leaf l1 = forest.addTree().addBranch().addLeaf(); final Iterator it = new ObjectGraphIterator(forest, new LeafFinder()); assertEquals(true, it.hasNext()); assertSame(l1, it.next()); assertEquals(false, it.hasNext()); try { it.next(); fail(); } catch (final NoSuchElementException ex) { } } public void testIteration_Transformed2() { final Forest forest = new Forest(); forest.addTree(); forest.addTree(); forest.addTree(); final Branch b1 = forest.getTree(0).addBranch(); final Branch b2 = forest.getTree(0).addBranch(); final Branch b3 = forest.getTree(2).addBranch(); /* Branch b4 = */ forest.getTree(2).addBranch(); final Branch b5 = forest.getTree(2).addBranch(); final Leaf l1 = b1.addLeaf(); final Leaf l2 = b1.addLeaf(); final Leaf l3 = b2.addLeaf(); final Leaf l4 = b3.addLeaf(); final Leaf l5 = b5.addLeaf(); final 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 (final NoSuchElementException ex) { } } public void testIteration_Transformed3() { final Forest forest = new Forest(); forest.addTree(); forest.addTree(); forest.addTree(); final Branch b1 = forest.getTree(1).addBranch(); final Branch b2 = forest.getTree(1).addBranch(); final Branch b3 = forest.getTree(2).addBranch(); final Branch b4 = forest.getTree(2).addBranch(); /* Branch b5 = */ forest.getTree(2).addBranch(); final Leaf l1 = b1.addLeaf(); final Leaf l2 = b1.addLeaf(); final Leaf l3 = b2.addLeaf(); final Leaf l4 = b3.addLeaf(); final Leaf l5 = b4.addLeaf(); final 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 (final NoSuchElementException ex) { } } //----------------------------------------------------------------------- static class LeafFinder implements Transformer { public Object transform(final 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(final int index) { return 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(final int index) { return 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(final int index) { return leaves.get(index); } Iterator leafIterator() { return leaves.iterator(); } } static class Leaf { String colour; String getColour() { return colour; } void setColour(final String colour) { this.colour = colour; } } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/IteratorChainTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/IteratorChainTe100664 13504 12243235516 32000 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.collections4.Predicate; /** * Tests the IteratorChain class. * * @version $Id: IteratorChainTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class IteratorChainTest extends AbstractIteratorTest { protected String[] testArray = { "One", "Two", "Three", "Four", "Five", "Six" }; protected List list1 = null; protected List list2 = null; protected List list3 = null; public IteratorChainTest(final String testName) { super(testName); } @Override 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"); } @Override public IteratorChain makeEmptyIterator() { final ArrayList list = new ArrayList(); return new IteratorChain(list.iterator()); } @Override public IteratorChain makeObject() { final IteratorChain chain = new IteratorChain(); chain.addIterator(list1.iterator()); chain.addIterator(list2.iterator()); chain.addIterator(list3.iterator()); return chain; } public void testIterator() { final Iterator iter = makeObject(); for (final String testValue : testArray) { final Object iterValue = iter.next(); assertEquals( "Iteration value is correct", testValue, iterValue ); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (final Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } public void testRemoveFromFilteredIterator() { final Predicate myPredicate = new Predicate() { public boolean evaluate(final Integer i) { return i.compareTo(Integer.valueOf(4)) < 0; } }; final List list1 = new ArrayList(); final List list2 = new ArrayList(); list1.add(Integer.valueOf(1)); list1.add(Integer.valueOf(2)); list2.add(Integer.valueOf(3)); list2.add(Integer.valueOf(4)); // will be ignored by the predicate final Iterator it1 = IteratorUtils.filteredIterator(list1.iterator(), myPredicate); final Iterator it2 = IteratorUtils.filteredIterator(list2.iterator(), myPredicate); final Iterator it = IteratorUtils.chainedIterator(it1, it2); while (it.hasNext()) { it.next(); it.remove(); } assertEquals(0, list1.size()); assertEquals(1, list2.size()); } @Override public void testRemove() { final Iterator iter = makeObject(); try { iter.remove(); fail("Calling remove before the first call to next() should throw an exception"); } catch (final IllegalStateException e) { } for (final String testValue : testArray) { final String iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); if (!iterValue.equals("Four")) { iter.remove(); } } assertTrue("List is empty",list1.size() == 0); assertTrue("List is empty",list2.size() == 1); assertTrue("List is empty",list3.size() == 0); } public void testFirstIteratorIsEmptyBug() { final List empty = new ArrayList(); final List notEmpty = new ArrayList(); notEmpty.add("A"); notEmpty.add("B"); notEmpty.add("C"); final IteratorChain chain = new IteratorChain(); chain.addIterator(empty.iterator()); chain.addIterator(notEmpty.iterator()); assertTrue("should have next",chain.hasNext()); assertEquals("A",chain.next()); assertTrue("should have next",chain.hasNext()); assertEquals("B",chain.next()); assertTrue("should have next",chain.hasNext()); assertEquals("C",chain.next()); assertTrue("should not have next",!chain.hasNext()); } public void testEmptyChain() { final IteratorChain chain = new IteratorChain(); assertEquals(false, chain.hasNext()); try { chain.next(); fail(); } catch (final NoSuchElementException ex) {} try { chain.remove(); fail(); } catch (final IllegalStateException ex) {} } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/SingletonIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/SingletonIterat100664 6603 12243235516 32050 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableIterator; /** * Tests the SingletonIterator to ensure that the next() method will actually * perform the iteration rather than the hasNext() method. * * @version $Id: SingletonIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class SingletonIteratorTest extends AbstractIteratorTest { private static final Object testValue = "foo"; public SingletonIteratorTest(final String testName) { super(testName); } /** * Returns a SingletonIterator from which * the element has already been removed. */ @Override public SingletonIterator makeEmptyIterator() { final SingletonIterator iter = makeObject(); iter.next(); iter.remove(); iter.reset(); return iter; } @Override @SuppressWarnings("unchecked") public SingletonIterator makeObject() { return new SingletonIterator((E) testValue); } @Override public boolean supportsRemove() { return true; } @Override public boolean supportsEmptyIterator() { return true; } public void testIterator() { final Iterator iter = makeObject(); assertTrue("Iterator has a first item", iter.hasNext()); final E iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (final Exception e) { assertTrue( "NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } @SuppressWarnings("unchecked") public void testSingletonIteratorRemove() { final ResettableIterator iter = new SingletonIterator((E) "xyzzy"); assertTrue(iter.hasNext()); assertEquals("xyzzy",iter.next()); iter.remove(); iter.reset(); assertTrue(! iter.hasNext()); } public void testReset() { final ResettableIterator it = 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()); } } ././@LongLink100644 0 0 164 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/SingletonListIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/SingletonListIt100664 11414 12243235516 32044 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableListIterator; /** * Tests the SingletonListIterator. * * @version $Id: SingletonListIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class SingletonListIteratorTest extends AbstractListIteratorTest { private static final Object testValue = "foo"; public SingletonListIteratorTest(final String testName) { super(testName); } /** * Returns a SingletonListIterator from which * the element has already been removed. */ @Override public SingletonListIterator makeEmptyIterator() { final SingletonListIterator iter = makeObject(); iter.next(); iter.remove(); iter.reset(); return iter; } @Override @SuppressWarnings("unchecked") public SingletonListIterator makeObject() { return new SingletonListIterator((E) testValue); } @Override public boolean supportsAdd() { return false; } @Override public boolean supportsRemove() { return true; } @Override public boolean supportsEmptyIterator() { return true; } public void testIterator() { final ListIterator iter = 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 (final Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } iter.previous(); try { iter.previous(); } catch (final Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } public void testReset() { final ResettableListIterator it = 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()); } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/SingletonIterator2Test.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/SingletonIterat100664 6260 12243235516 32047 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableIterator; /** * Tests the SingletonIterator to ensure that the next() method will actually * perform the iteration rather than the hasNext() method. * * @version $Id: SingletonIterator2Test.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class SingletonIterator2Test extends AbstractIteratorTest { private static final Object testValue = "foo"; public SingletonIterator2Test(final String testName) { super(testName); } //----------------------------------------------------------------------- @Override @SuppressWarnings("unchecked") public SingletonIterator makeEmptyIterator() { final SingletonIterator iter = new SingletonIterator((E) testValue); iter.next(); iter.remove(); iter.reset(); return iter; } @Override @SuppressWarnings("unchecked") public SingletonIterator makeObject() { return new SingletonIterator((E) testValue, false); } @Override public boolean supportsRemove() { return false; } @Override public boolean supportsEmptyIterator() { return false; } //----------------------------------------------------------------------- public void testIterator() { final Iterator iter = makeObject(); assertTrue("Iterator has a first item", iter.hasNext()); final E iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (final Exception e) { assertTrue( "NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } public void testReset() { final ResettableIterator it = 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()); } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/LazyIteratorChainTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/LazyIteratorCha100664 14667 12243235516 32033 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.collections4.Predicate; /** * Tests the LazyIteratorChain class. * * @version $Id: LazyIteratorChainTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class LazyIteratorChainTest extends AbstractIteratorTest { protected String[] testArray = { "One", "Two", "Three", "Four", "Five", "Six" }; protected List list1 = null; protected List list2 = null; protected List list3 = null; public LazyIteratorChainTest(final String testName) { super(testName); } @Override 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"); } @Override public LazyIteratorChain makeEmptyIterator() { return new LazyIteratorChain() { @Override protected Iterator nextIterator(final int count) { return null; } }; } @Override public LazyIteratorChain makeObject() { final LazyIteratorChain chain = new LazyIteratorChain() { @Override protected Iterator nextIterator(final int count) { switch (count) { case 1: return list1.iterator(); case 2: return list2.iterator(); case 3: return list3.iterator(); } return null; } }; return chain; } public void testIterator() { final Iterator iter = makeObject(); for (final String testValue : testArray) { final Object iterValue = iter.next(); assertEquals( "Iteration value is correct", testValue, iterValue ); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (final Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } public void testRemoveFromFilteredIterator() { final Predicate myPredicate = new Predicate() { public boolean evaluate(final Integer i) { return i.compareTo(Integer.valueOf(4)) < 0; } }; final List list1 = new ArrayList(); final List list2 = new ArrayList(); list1.add(Integer.valueOf(1)); list1.add(Integer.valueOf(2)); list2.add(Integer.valueOf(3)); list2.add(Integer.valueOf(4)); // will be ignored by the predicate final Iterator it1 = IteratorUtils.filteredIterator(list1.iterator(), myPredicate); final Iterator it2 = IteratorUtils.filteredIterator(list2.iterator(), myPredicate); final Iterator it = IteratorUtils.chainedIterator(it1, it2); while (it.hasNext()) { it.next(); it.remove(); } assertEquals(0, list1.size()); assertEquals(1, list2.size()); } @Override public void testRemove() { final Iterator iter = makeObject(); try { iter.remove(); fail("Calling remove before the first call to next() should throw an exception"); } catch (final IllegalStateException e) { } for (final String testValue : testArray) { final String iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); if (!iterValue.equals("Four")) { iter.remove(); } } assertTrue("List is empty",list1.size() == 0); assertTrue("List is empty",list2.size() == 1); assertTrue("List is empty",list3.size() == 0); } public void testFirstIteratorIsEmptyBug() { final List empty = new ArrayList(); final List notEmpty = new ArrayList(); notEmpty.add("A"); notEmpty.add("B"); notEmpty.add("C"); final LazyIteratorChain chain = new LazyIteratorChain() { @Override protected Iterator nextIterator(final int count) { switch (count) { case 1: return empty.iterator(); case 2: return notEmpty.iterator(); } return null; } }; assertTrue("should have next",chain.hasNext()); assertEquals("A",chain.next()); assertTrue("should have next",chain.hasNext()); assertEquals("B",chain.next()); assertTrue("should have next",chain.hasNext()); assertEquals("C",chain.next()); assertTrue("should not have next",!chain.hasNext()); } public void testEmptyChain() { final LazyIteratorChain chain = makeEmptyIterator(); assertEquals(false, chain.hasNext()); try { chain.next(); fail(); } catch (final NoSuchElementException ex) {} try { chain.remove(); fail(); } catch (final IllegalStateException ex) {} } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/LoopingIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/LoopingIterator100664 15355 12243235516 32102 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import junit.framework.TestCase; /** * Tests the LoopingIterator class. * * @version $Id: LoopingIteratorTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class LoopingIteratorTest extends TestCase { /** * Tests constructor exception. */ public void testConstructorEx() throws Exception { try { new LoopingIterator(null); fail(); } catch (final NullPointerException ex) { } } /** * Tests whether an empty looping iterator works as designed. * @throws Exception If something unexpected occurs. */ public void testLooping0() throws Exception { final List list = new ArrayList(); final LoopingIterator loop = new LoopingIterator(list); assertTrue("hasNext should return false", !loop.hasNext()); try { loop.next(); fail("NoSuchElementException was not thrown during next() call."); } catch (final NoSuchElementException ex) { } } /** * Tests whether a populated looping iterator works as designed. * @throws Exception If something unexpected occurs. */ public void testLooping1() throws Exception { final List list = Arrays.asList("a"); final 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 { final List list = Arrays.asList("a", "b"); final 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 { final List list = Arrays.asList("a", "b", "c"); final 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 { final List list = new ArrayList(Arrays.asList("a", "b", "c")); final 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()); assertFalse("4th hasNext should return false", loop.hasNext()); try { loop.next(); fail("Expected NoSuchElementException to be thrown."); } catch (final NoSuchElementException ex) { } } /** * Tests the reset() method on a LoopingIterator wrapped ArrayList. * @throws Exception If something unexpected occurs. */ public void testReset() throws Exception { final List list = Arrays.asList("a", "b", "c"); final 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 { final List list = new ArrayList(Arrays.asList("a", "b", "c")); final 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()); } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWrapper2Test.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWra100664 15616 12243235516 32060 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableListIterator; /** * Tests the ListIteratorWrapper to insure that it behaves as expected when wrapping a ListIterator. * * @version $Id: ListIteratorWrapper2Test.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ListIteratorWrapper2Test extends AbstractIteratorTest { protected String[] testArray = { "One", "Two", "Three", "Four", "Five", "Six" }; protected List list1 = null; public ListIteratorWrapper2Test(final String testName) { super(testName); } @Override @SuppressWarnings("unchecked") public void setUp() { list1 = new ArrayList(); list1.add((E) "One"); list1.add((E) "Two"); list1.add((E) "Three"); list1.add((E) "Four"); list1.add((E) "Five"); list1.add((E) "Six"); } @Override public ResettableListIterator makeEmptyIterator() { final ArrayList list = new ArrayList(); return new ListIteratorWrapper(list.listIterator()); } @Override public ResettableListIterator makeObject() { return new ListIteratorWrapper(list1.listIterator()); } public void testIterator() { final ListIterator iter = makeObject(); for (final String testValue : testArray) { final Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (final Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } // now, read it backwards for (int i = testArray.length - 1; i > -1; --i) { final Object testValue = testArray[i]; final E iterValue = iter.previous(); assertEquals( "Iteration value is correct", testValue, iterValue ); } try { iter.previous(); } catch (final Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } // now, read it forwards again for (final String testValue : testArray) { final Object iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } } @Override public void testRemove() { final ListIterator iter = makeObject(); //initial state: assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); try { iter.remove(); fail("ListIteratorWrapper#remove() should fail; must be initially positioned first"); } catch (final IllegalStateException e) { } //no change from invalid op: assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); //establish size: int sz = list1.size(); //verify initial next() call: assertEquals(list1.get(0), iter.next()); assertEquals(0, iter.previousIndex()); assertEquals(1, iter.nextIndex()); //verify remove(): iter.remove(); assertEquals(--sz, list1.size()); //like we never started iterating: assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); try { iter.remove(); fail("ListIteratorWrapper#remove() should fail; must be repositioned first"); } catch (final IllegalStateException e) { } //no change from invalid op: assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); //two consecutive next() calls: assertEquals(list1.get(0), iter.next()); assertEquals(0, iter.previousIndex()); assertEquals(1, iter.nextIndex()); assertEquals(list1.get(1), iter.next()); assertEquals(1, iter.previousIndex()); assertEquals(2, iter.nextIndex()); //call previous(): assertEquals(list1.get(1), iter.previous()); assertEquals(0, iter.previousIndex()); assertEquals(1, iter.nextIndex()); //should support remove() after calling previous() once from tip because we haven't changed the underlying iterator's position: iter.remove(); assertEquals(--sz, list1.size()); assertEquals(0, iter.previousIndex()); assertEquals(1, iter.nextIndex()); //this would dig into cache on a plain Iterator, but forwards directly to wrapped ListIterator: assertEquals(list1.get(0), iter.previous()); assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); //here's the proof; remove() still works: iter.remove(); assertEquals(--sz, list1.size()); assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); //further testing would be fairly meaningless: } public void testReset() { final ResettableListIterator iter = makeObject(); final E first = iter.next(); final E 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++) { final Object testValue = testArray[i]; final E iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } } } ././@LongLink100644 0 0 175 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableOrderedMapIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableOrd100664 6505 12243235516 32001 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.map.ListOrderedMap; /** * Tests the UnmodifiableOrderedMapIterator. * * @version $Id: UnmodifiableOrderedMapIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class UnmodifiableOrderedMapIteratorTest extends AbstractOrderedMapIteratorTest { public UnmodifiableOrderedMapIteratorTest(final String testName) { super(testName); } @Override public OrderedMapIterator makeEmptyIterator() { return UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator( ListOrderedMap.listOrderedMap(new HashMap()).mapIterator()); } @Override public OrderedMapIterator makeObject() { return UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(getMap().mapIterator()); } @Override @SuppressWarnings("unchecked") public OrderedMap getMap() { final OrderedMap testMap = ListOrderedMap.listOrderedMap(new HashMap()); testMap.put((K) "A", (V) "a"); testMap.put((K) "B", (V) "b"); testMap.put((K) "C", (V) "c"); return testMap; } @Override @SuppressWarnings("unchecked") public Map getConfirmedMap() { final Map testMap = new TreeMap(); testMap.put((K) "A", (V) "a"); testMap.put((K) "B", (V) "b"); testMap.put((K) "C", (V) "c"); return testMap; } @Override public boolean supportsRemove() { return false; } @Override public boolean supportsSetValue() { return false; } //----------------------------------------------------------------------- public void testOrderedMapIterator() { assertTrue(makeEmptyIterator() instanceof Unmodifiable); } public void testDecorateFactory() { OrderedMapIterator it = makeObject(); assertSame(it, UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(it)); it = getMap().mapIterator() ; assertTrue(it != UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(it)); try { UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(null); fail(); } catch (final IllegalArgumentException ex) {} } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/AbstractIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/AbstractIterato100664 12701 12243235516 32044 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.AbstractObjectTest; /** * 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 3.0 * @version $Id: AbstractIteratorTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public abstract class AbstractIteratorTest extends AbstractObjectTest { /** * JUnit constructor. * * @param testName the test class name */ public AbstractIteratorTest(final String testName) { super(testName); } //----------------------------------------------------------------------- /** * Implement this method to return an iterator over an empty collection. * * @return an empty iterator */ public abstract Iterator makeEmptyIterator(); /** * Implements the abstract superclass method to return the full iterator. * * @return a full iterator */ @Override public abstract Iterator makeObject(); /** * 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()) { return; } final 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 (final NoSuchElementException e) { } verify(); assertNotNull(it.toString()); } /** * Test normal iteration behaviour. */ public void testFullIterator() { if (!supportsFullIterator()) { return; } final Iterator it = makeObject(); // 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 (final 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 (final NoSuchElementException e) { } assertNotNull(it.toString()); } /** * Test remove behaviour. */ public void testRemove() { final Iterator it = makeObject(); if (!supportsRemove()) { // check for UnsupportedOperationException if not supported try { it.remove(); } catch (final UnsupportedOperationException ex) {} return; } // should throw IllegalStateException before next() called try { it.remove(); fail(); } catch (final IllegalStateException ex) {} verify(); // remove after next should be fine it.next(); it.remove(); // should throw IllegalStateException for second remove() try { it.remove(); fail(); } catch (final IllegalStateException ex) {} } } ././@LongLink100644 0 0 166 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayListIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayList100664 7546 12243235516 32005 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Arrays; import java.util.ListIterator; import java.util.NoSuchElementException; /** * Tests the ObjectArrayListIterator class. * * @version $Id: ObjectArrayListIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class ObjectArrayListIteratorTest extends ObjectArrayIteratorTest { public ObjectArrayListIteratorTest(final String testName) { super(testName); } @Override @SuppressWarnings("unchecked") public ObjectArrayListIterator makeEmptyIterator() { return new ObjectArrayListIterator((E[]) new Object[0]); } @Override @SuppressWarnings("unchecked") public ObjectArrayListIterator makeObject() { return new ObjectArrayListIterator((E[]) testArray); } public ObjectArrayListIterator makeArrayListIterator(final E[] array) { return new ObjectArrayListIterator(array); } /** * Test the basic ListIterator functionality - going backwards using * previous(). */ public void testListIterator() { final ListIterator iter = makeObject(); // 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--) { final Object testValue = testArray[x]; final Object iterValue = iter.previous(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasPrevious()); try { iter.previous(); } catch (final Exception e) { assertTrue( "NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } /** * Tests the {@link java.util.ListIterator#set} operation. */ @SuppressWarnings("unchecked") public void testListIteratorSet() { final String[] testData = new String[] { "a", "b", "c" }; final String[] result = new String[] { "0", "1", "2" }; ListIterator iter = makeArrayListIterator((E[]) testData); int x = 0; while (iter.hasNext()) { iter.next(); iter.set((E) 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((E[]) testArray); try { iter.set((E) "should fail"); fail("ListIterator#set should fail if next() or previous() have not yet been called."); } catch (final IllegalStateException e) { // expected } catch (final Throwable t) { // should never happen fail(t.toString()); } } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayIter100664 6505 12243235516 31767 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; /** * Tests the ObjectArrayIterator. * * @version $Id: ObjectArrayIteratorTest.java 1543964 2013-11-20 21:53:39Z tn $ */ public class ObjectArrayIteratorTest extends AbstractIteratorTest { protected String[] testArray = { "One", "Two", "Three" }; public ObjectArrayIteratorTest(final String testName) { super(testName); } @Override @SuppressWarnings("unchecked") public ObjectArrayIterator makeEmptyIterator() { return new ObjectArrayIterator((E[]) new Object[0]); } @Override @SuppressWarnings("unchecked") public ObjectArrayIterator makeObject() { return new ObjectArrayIterator((E[]) testArray); } @SuppressWarnings("unchecked") public ObjectArrayIterator makeArrayIterator() { return new ObjectArrayIterator(); } public ObjectArrayIterator makeArrayIterator(final E[] array) { return new ObjectArrayIterator(array); } public ObjectArrayIterator makeArrayIterator(final E[] array, final int index) { return new ObjectArrayIterator(array, index); } public ObjectArrayIterator makeArrayIterator(final E[] array, final int start, final int end) { return new ObjectArrayIterator(array, start, end); } @Override public boolean supportsRemove() { return false; } public void testIterator() { final Iterator iter = makeObject(); for (final String testValue : testArray) { final E iterValue = iter.next(); assertEquals("Iteration value is correct", testValue, iterValue); } assertTrue("Iterator should now be empty", !iter.hasNext()); try { iter.next(); } catch (final Exception e) { assertTrue( "NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } public void testNullArray() { try { makeArrayIterator(null); fail("Constructor should throw a NullPointerException when constructed with a null array"); } catch (final NullPointerException e) { // expected } } @SuppressWarnings("unchecked") public void testReset() { final ObjectArrayIterator it = makeArrayIterator((E[]) testArray); it.next(); it.reset(); assertEquals("One", it.next()); } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/UniqueFilterIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/UniqueFilterIte100664 5343 12243235516 32013 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Tests the UniqueFilterIterator class. * * @version $Id: UniqueFilterIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class UniqueFilterIteratorTest extends AbstractIteratorTest { protected String[] testArray = { "One", "Two", "Three", "Four", "Five", "Six" }; protected List list1 = null; public UniqueFilterIteratorTest(final String testName) { super(testName); } @Override @SuppressWarnings("unchecked") public void setUp() { list1 = new ArrayList(); list1.add((E) "One"); list1.add((E) "Two"); list1.add((E) "Three"); list1.add((E) "Two"); list1.add((E) "One"); list1.add((E) "Four"); list1.add((E) "Five"); list1.add((E) "Five"); list1.add((E) "Six"); list1.add((E) "Five"); } @Override public UniqueFilterIterator makeEmptyIterator() { final ArrayList list = new ArrayList(); return new UniqueFilterIterator(list.iterator()); } @Override public UniqueFilterIterator makeObject() { final Iterator i = list1.iterator(); return new UniqueFilterIterator(i); } public void testIterator() { final Iterator iter = makeObject(); for (final String testValue : testArray) { final E iterValue = iter.next(); assertEquals( "Iteration value is correct", testValue, iterValue ); } assertTrue("Iterator should now be empty", ! iter.hasNext() ); try { iter.next(); } catch (final Exception e) { assertTrue("NoSuchElementException must be thrown", e.getClass().equals(new NoSuchElementException().getClass())); } } } ././@LongLink100644 0 0 166 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableMapIteratorTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableMap100664 6146 12243235516 31773 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.bidimap.DualHashBidiMap; /** * Tests the UnmodifiableMapIterator. * * @version $Id: UnmodifiableMapIteratorTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public class UnmodifiableMapIteratorTest extends AbstractMapIteratorTest { public UnmodifiableMapIteratorTest(final String testName) { super(testName); } @Override public MapIterator makeEmptyIterator() { return UnmodifiableMapIterator.unmodifiableMapIterator(new DualHashBidiMap().mapIterator()); } @Override public MapIterator makeObject() { return UnmodifiableMapIterator.unmodifiableMapIterator(getMap().mapIterator()); } @Override @SuppressWarnings("unchecked") public IterableMap getMap() { final IterableMap testMap = new DualHashBidiMap(); testMap.put((K) "A", (V) "a"); testMap.put((K) "B", (V)"b"); testMap.put((K) "C", (V) "c"); return testMap; } @Override @SuppressWarnings("unchecked") public Map getConfirmedMap() { final Map testMap = new HashMap(); testMap.put((K) "A", (V) "a"); testMap.put((K) "B", (V)"b"); testMap.put((K) "C", (V) "c"); return testMap; } @Override public boolean supportsRemove() { return false; } @Override public boolean supportsSetValue() { return false; } //----------------------------------------------------------------------- public void testMapIterator() { assertTrue(makeEmptyIterator() instanceof Unmodifiable); } public void testDecorateFactory() { MapIterator it = makeObject(); assertSame(it, UnmodifiableMapIterator.unmodifiableMapIterator(it)); it = getMap().mapIterator() ; assertTrue(it != UnmodifiableMapIterator.unmodifiableMapIterator(it)); try { UnmodifiableMapIterator.unmodifiableMapIterator(null); fail(); } catch (final IllegalArgumentException ex) {} } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/ClosureUtilsTest.java100664 35613 12243235516 31161 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import org.apache.commons.collections4.functors.EqualPredicate; import org.apache.commons.collections4.functors.ExceptionClosure; import org.apache.commons.collections4.functors.FalsePredicate; import org.apache.commons.collections4.functors.NOPClosure; import org.apache.commons.collections4.functors.TruePredicate; /** * Tests the ClosureUtils class. * * @since 3.0 * @version $Id: ClosureUtilsTest.java 1540705 2013-11-11 13:22:32Z ebourg $ */ public class ClosureUtilsTest extends TestCase { private static final Object cString = "Hello"; static class MockClosure implements Closure { int count = 0; public void execute(final T object) { count++; } public void reset() { count = 0; } } static class MockTransformer implements Transformer { int count = 0; public T transform(final T object) { count++; return object; } } // exceptionClosure //------------------------------------------------------------------ public void testExceptionClosure() { assertNotNull(ClosureUtils.exceptionClosure()); assertSame(ClosureUtils.exceptionClosure(), ClosureUtils.exceptionClosure()); try { ClosureUtils.exceptionClosure().execute(null); } catch (final FunctorException ex) { try { ClosureUtils.exceptionClosure().execute(cString); } catch (final FunctorException ex2) { return; } } fail(); } // nopClosure //------------------------------------------------------------------ public void testNopClosure() { final StringBuilder buf = new StringBuilder("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"); // Only StringBuffer has setLength() method ClosureUtils.invokerClosure("reverse").execute(buf); assertEquals("olleH", buf.toString()); buf = new StringBuffer("Hello"); ClosureUtils.invokerClosure("setLength", new Class[] {Integer.TYPE}, new Object[] {Integer.valueOf(2)}).execute(buf); assertEquals("He", buf.toString()); } // forClosure //------------------------------------------------------------------ public void testForClosure() { final 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(FalsePredicate.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 (final IllegalArgumentException ex) {} try { ClosureUtils.whileClosure(FalsePredicate.falsePredicate(), null); fail(); } catch (final IllegalArgumentException ex) {} try { ClosureUtils.whileClosure(null, null); fail(); } catch (final IllegalArgumentException ex) {} } // doWhileClosure //------------------------------------------------------------------ public void testDoWhileClosure() { MockClosure cmd = new MockClosure(); ClosureUtils.doWhileClosure(cmd, FalsePredicate.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 (final IllegalArgumentException ex) {} } // chainedClosure //------------------------------------------------------------------ @SuppressWarnings("unchecked") 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.>emptyList())); try { ClosureUtils.chainedClosure(null, null); fail(); } catch (final IllegalArgumentException ex) {} try { ClosureUtils.chainedClosure((Closure[]) null); fail(); } catch (final IllegalArgumentException ex) {} try { ClosureUtils.chainedClosure((Collection>) null); fail(); } catch (final IllegalArgumentException ex) {} try { ClosureUtils.chainedClosure(new Closure[] {null, null}); fail(); } catch (final IllegalArgumentException ex) {} try { coll = new ArrayList>(); coll.add(null); coll.add(null); ClosureUtils.chainedClosure(coll); fail(); } catch (final IllegalArgumentException ex) {} } // ifClosure //------------------------------------------------------------------ public void testIfClosure() { MockClosure a = new MockClosure(); MockClosure b = null; ClosureUtils.ifClosure(TruePredicate.truePredicate(), a).execute(null); assertEquals(1, a.count); a = new MockClosure(); ClosureUtils.ifClosure(FalsePredicate.falsePredicate(), a).execute(null); assertEquals(0, a.count); a = new MockClosure(); b = new MockClosure(); ClosureUtils.ifClosure(TruePredicate.truePredicate(), a, b).execute(null); assertEquals(1, a.count); assertEquals(0, b.count); a = new MockClosure(); b = new MockClosure(); ClosureUtils.ifClosure(FalsePredicate.falsePredicate(), a, b).execute(null); assertEquals(0, a.count); assertEquals(1, b.count); } // switchClosure //------------------------------------------------------------------ @SuppressWarnings("unchecked") public void testSwitchClosure() { final MockClosure a = new MockClosure(); final MockClosure b = new MockClosure(); ClosureUtils.switchClosure( new Predicate[] { EqualPredicate.equalPredicate("HELLO"), EqualPredicate.equalPredicate("THERE") }, new Closure[] { a, b }).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); a.reset(); b.reset(); ClosureUtils.switchClosure( new Predicate[] { EqualPredicate.equalPredicate("HELLO"), EqualPredicate.equalPredicate("THERE") }, new Closure[] { a, b }).execute("HELLO"); assertEquals(1, a.count); assertEquals(0, b.count); a.reset(); b.reset(); final MockClosure c = new MockClosure(); ClosureUtils.switchClosure( new Predicate[] { EqualPredicate.equalPredicate("HELLO"), EqualPredicate.equalPredicate("THERE") }, new Closure[] { a, b }, c).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); assertEquals(1, c.count); a.reset(); b.reset(); final Map, Closure> map = new HashMap, Closure>(); map.put(EqualPredicate.equalPredicate("HELLO"), a); map.put(EqualPredicate.equalPredicate("THERE"), b); ClosureUtils.switchClosure(map).execute(null); assertEquals(0, a.count); assertEquals(0, b.count); a.reset(); b.reset(); map.clear(); map.put(EqualPredicate.equalPredicate("HELLO"), a); map.put(EqualPredicate.equalPredicate("THERE"), b); ClosureUtils.switchClosure(map).execute("THERE"); assertEquals(0, a.count); assertEquals(1, b.count); a.reset(); b.reset(); c.reset(); map.clear(); map.put(EqualPredicate.equalPredicate("HELLO"), a); map.put(EqualPredicate.equalPredicate("THERE"), b); map.put(null, c); ClosureUtils.switchClosure(map).execute("WELL"); assertEquals(0, a.count); assertEquals(0, b.count); assertEquals(1, c.count); assertEquals(NOPClosure.INSTANCE, ClosureUtils.switchClosure(new Predicate[0], new Closure[0])); assertEquals(NOPClosure.INSTANCE, ClosureUtils.switchClosure(new HashMap, Closure>())); map.clear(); map.put(null, null); assertEquals(NOPClosure.INSTANCE, ClosureUtils.switchClosure(map)); try { ClosureUtils.switchClosure(null, null); fail(); } catch (final IllegalArgumentException ex) {} try { ClosureUtils.switchClosure((Predicate[]) null, (Closure[]) null); fail(); } catch (final IllegalArgumentException ex) {} try { ClosureUtils.switchClosure((Map, Closure>) null); fail(); } catch (final IllegalArgumentException ex) {} try { ClosureUtils.switchClosure(new Predicate[2], new Closure[2]); fail(); } catch (final IllegalArgumentException ex) {} try { ClosureUtils.switchClosure( new Predicate[] { TruePredicate.truePredicate() }, new Closure[] { a, b }); fail(); } catch (final IllegalArgumentException ex) {} } // switchMapClosure //------------------------------------------------------------------ public void testSwitchMapClosure() { final MockClosure a = new MockClosure(); final MockClosure b = new MockClosure(); final 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.reset(); b.reset(); map.clear(); map.put("HELLO", a); map.put("THERE", b); ClosureUtils.switchMapClosure(map).execute("THERE"); assertEquals(0, a.count); assertEquals(1, b.count); a.reset(); b.reset(); map.clear(); final MockClosure c = new MockClosure(); 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); assertEquals(NOPClosure.INSTANCE, ClosureUtils.switchMapClosure(new HashMap>())); try { ClosureUtils.switchMapClosure(null); fail(); } catch (final IllegalArgumentException ex) {} } // asClosure //------------------------------------------------------------------ public void testTransformerClosure() { final MockTransformer mock = new MockTransformer(); final Closure closure = ClosureUtils.asClosure(mock); closure.execute(null); assertEquals(1, mock.count); closure.execute(null); assertEquals(2, mock.count); assertEquals(ClosureUtils.nopClosure(), ClosureUtils.asClosure(null)); } // misc tests //------------------------------------------------------------------ /** * Test that all Closure singletones hold singleton pattern in * serialization/deserialization process. */ public void testSingletonPatternInSerialization() { final Object[] singletones = new Object[] { ExceptionClosure.INSTANCE, NOPClosure.INSTANCE, }; for (final Object original : singletones) { TestUtils.assertSameAfterSerialization( "Singletone patern broken for " + original.getClass(), original ); } } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/MapBackedSet2Test.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/MapBackedSet2Test.jav100664 5333 12243235516 31477 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Iterator; import java.util.Set; import org.apache.commons.collections4.map.LinkedMap; /** * JUnit test. * * @since 3.1 * @version $Id: MapBackedSet2Test.java 1469004 2013-04-17 17:37:03Z tn $ */ public class MapBackedSet2Test extends AbstractSetTest { public MapBackedSet2Test(final String testName) { super(testName); } @Override public Set makeObject() { return MapBackedSet.mapBackedSet(new LinkedMap()); } @SuppressWarnings("unchecked") protected Set setupSet() { final Set set = makeObject(); for (int i = 0; i < 10; i++) { set.add((E) Integer.toString(i)); } return set; } @SuppressWarnings("unchecked") public void testOrdering() { final 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((E) 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()); } } @Override public void testCanonicalEmptyCollectionExists() { } @Override public void testCanonicalFullCollectionExists() { } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/PredicatedSetTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/PredicatedSetTest.jav100664 10401 12243235516 31662 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.HashSet; import java.util.Set; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.TruePredicate; /** * Extension of {@link AbstractSetTest} for exercising the * {@link PredicatedSet} implementation. * * @since 3.0 * @version $Id: PredicatedSetTest.java 1476855 2013-04-28 23:15:54Z sebb $ */ public class PredicatedSetTest extends AbstractSetTest { public PredicatedSetTest(final String testName) { super(testName); } //------------------------------------------------------------------- protected Predicate truePredicate = TruePredicate.truePredicate(); protected PredicatedSet decorateSet(final Set set, final Predicate predicate) { return PredicatedSet.predicatedSet(set, predicate); } @Override public PredicatedSet makeObject() { return decorateSet(new HashSet(), truePredicate); } @Override @SuppressWarnings("unchecked") public E[] getFullElements() { return (E[]) new Object[] {"1", "3", "5", "7", "2", "4", "6"}; } //-------------------------------------------------------------------- protected Predicate testPredicate = new Predicate() { public boolean evaluate(final E o) { return o instanceof String; } }; protected PredicatedSet makeTestSet() { return decorateSet(new HashSet(), testPredicate); } public void testGetSet() { final PredicatedSet set = makeTestSet(); assertTrue("returned set should not be null", set.decorated() != null); } @SuppressWarnings("unchecked") public void testIllegalAdd() { final Set set = makeTestSet(); final Integer i = Integer.valueOf(3); try { set.add((E) i); fail("Integer should fail string predicate."); } catch (final IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !set.contains(i)); } @SuppressWarnings("unchecked") public void testIllegalAddAll() { final Set set = makeTestSet(); final Set elements = new HashSet(); elements.add((E) "one"); elements.add((E) "two"); elements.add((E) Integer.valueOf(3)); elements.add((E) "four"); try { set.addAll(elements); fail("Integer should fail string predicate."); } catch (final 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(Integer.valueOf(3))); assertTrue("Set shouldn't contain illegal element", !set.contains("four")); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/PredicatedSet.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/PredicatedSet.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/TransformedSortedSetTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/TransformedSortedSetT100664 10207 12243235516 31774 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Arrays; import java.util.Collections; import java.util.TreeSet; import java.util.Set; import java.util.SortedSet; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.collection.TransformedCollectionTest; /** * Extension of {@link AbstractSortedSetTest} for exercising the {@link TransformedSortedSet} * implementation. * * @since 3.0 * @version $Id: TransformedSortedSetTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class TransformedSortedSetTest extends AbstractSortedSetTest { public TransformedSortedSetTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(TransformedSortedSetTest.class); } //----------------------------------------------------------------------- @Override @SuppressWarnings("unchecked") public SortedSet makeObject() { return TransformedSortedSet.transformingSortedSet(new TreeSet(), (Transformer) TransformedCollectionTest.NOOP_TRANSFORMER); } @Override @SuppressWarnings("unchecked") public SortedSet makeFullCollection() { final SortedSet set = new TreeSet(); set.addAll(Arrays.asList(getFullElements())); return TransformedSortedSet.transformingSortedSet(set, (Transformer) TransformedCollectionTest.NOOP_TRANSFORMER); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testTransformedSet() { final SortedSet set = TransformedSortedSet.transformingSortedSet(new TreeSet(), (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, set.size()); final E[] els = (E[]) 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(Integer.valueOf((String) els[i]))); } assertEquals(true, set.remove(Integer.valueOf((String) els[0]))); } public void testTransformedSet_decorateTransform() { final Set originalSet = new TreeSet(); final Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; Collections.addAll(originalSet, els); final Set set = TransformedSortedSet.transformedSet(originalSet, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(els.length, set.size()); for (final Object el : els) { assertEquals(true, set.contains(Integer.valueOf((String) el))); } assertEquals(true, set.remove(Integer.valueOf((String) els[0]))); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/TransformedSortedSet.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/TransformedSortedSet.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/CompositeSetTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/CompositeSetTest.java100664 14571 12243235516 31735 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.collections4.set.CompositeSet.SetMutator; /** * Extension of {@link AbstractSetTest} for exercising the * {@link CompositeSet} implementation. * * @since 3.0 * @version $Id: CompositeSetTest.java 1521262 2013-09-09 19:38:49Z tn $ */ public class CompositeSetTest extends AbstractSetTest { public CompositeSetTest(final String name) { super(name); } @Override public CompositeSet makeObject() { final HashSet contained = new HashSet(); final CompositeSet set = new CompositeSet(contained); set.setMutator( new EmptySetMutator(contained) ); return set; } @SuppressWarnings("unchecked") public Set buildOne() { final HashSet set = new HashSet(); set.add((E) "1"); set.add((E) "2"); return set; } @SuppressWarnings("unchecked") public Set buildTwo() { final HashSet set = new HashSet(); set.add((E) "3"); set.add((E) "4"); return set; } @SuppressWarnings("unchecked") public void testContains() { final CompositeSet set = new CompositeSet(new Set[]{ buildOne(), buildTwo() }); assertTrue(set.contains("1")); } @SuppressWarnings("unchecked") public void testRemoveUnderlying() { final Set one = buildOne(); final Set two = buildTwo(); final CompositeSet set = new CompositeSet(new Set[] { one, two }); one.remove("1"); assertFalse(set.contains("1")); two.remove("3"); assertFalse(set.contains("3")); } @SuppressWarnings("unchecked") public void testRemoveComposited() { final Set one = buildOne(); final Set two = buildTwo(); final CompositeSet set = new CompositeSet(new Set[] { one, two }); set.remove("1"); assertFalse(one.contains("1")); set.remove("3"); assertFalse(one.contains("3")); } @SuppressWarnings("unchecked") public void testFailedCollisionResolution() { final Set one = buildOne(); final Set two = buildTwo(); final CompositeSet set = new CompositeSet(new Set[] { one, two }); set.setMutator(new SetMutator() { private static final long serialVersionUID = 1L; public void resolveCollision(final CompositeSet comp, final Set existing, final Set added, final Collection intersects) { //noop } public boolean add(final CompositeSet composite, final List> collections, final E obj) { throw new UnsupportedOperationException(); } public boolean addAll(final CompositeSet composite, final List> collections, final Collection coll) { throw new UnsupportedOperationException(); } }); final HashSet three = new HashSet(); three.add((E) "1"); try { set.addComposited(three); fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException e) { // expected } } @SuppressWarnings("unchecked") public void testAddComposited() { final Set one = buildOne(); final Set two = buildTwo(); final CompositeSet set = new CompositeSet(); set.addComposited(one, two); final CompositeSet set2 = new CompositeSet(buildOne()); set2.addComposited(buildTwo()); assertTrue(set.equals(set2)); final HashSet set3 = new HashSet(); set3.add((E) "1"); set3.add((E) "2"); set3.add((E) "3"); final HashSet set4 = new HashSet(); set4.add((E) "4"); final CompositeSet set5 = new CompositeSet(set3); set5.addComposited(set4); assertTrue(set.equals(set5)); try { set.addComposited(set3); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException ex) { // expected } } @SuppressWarnings("unchecked") public void testAddCompositedCollision() { final HashSet set1 = new HashSet(); set1.add((E) "1"); set1.add((E) "2"); set1.add((E) "3"); final HashSet set2 = new HashSet(); set2.add((E) "4"); final CompositeSet set3 = new CompositeSet(set1); try { set3.addComposited(set1, buildOne()); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException ex) { // expected } try { set3.addComposited(set1, buildOne(), buildTwo()); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException ex) { // expected } } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CompositeSet.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CompositeSet.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/ListOrderedSetTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/ListOrderedSetTest.ja100664 22342 12243235516 31657 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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; /** * Extension of {@link AbstractSetTest} for exercising the * {@link ListOrderedSet} implementation. * * @since 3.0 * @version $Id: ListOrderedSetTest.java 1477789 2013-04-30 19:28:27Z sebb $ */ public class ListOrderedSetTest extends AbstractSetTest { private static final Integer ZERO = Integer.valueOf(0); private static final Integer ONE = Integer.valueOf(1); private static final Integer TWO = Integer.valueOf(2); private static final Integer THREE = Integer.valueOf(3); public ListOrderedSetTest(final String testName) { super(testName); } @Override public ListOrderedSet makeObject() { return ListOrderedSet.listOrderedSet(new HashSet()); } @SuppressWarnings("unchecked") protected ListOrderedSet setupSet() { final ListOrderedSet set = makeObject(); for (int i = 0; i < 10; i++) { set.add((E) Integer.toString(i)); } return set; } @SuppressWarnings("unchecked") public void testOrdering() { final ListOrderedSet 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((E) 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()); } } @SuppressWarnings("unchecked") public void testListAddRemove() { final ListOrderedSet set = makeObject(); final List view = set.asList(); set.add((E) ZERO); set.add((E) ONE); set.add((E) 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)); } @SuppressWarnings("unchecked") public void testListAddIndexed() { final ListOrderedSet set = makeObject(); set.add((E) ZERO); set.add((E) TWO); set.add(1, (E) ONE); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); set.add(0, (E) ONE); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); final List list = new ArrayList(); list.add((E) ZERO); list.add((E) 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, (E) 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)); } @SuppressWarnings("unchecked") public void testListAddReplacing() { final ListOrderedSet set = makeObject(); final A a = new A(); final B b = new B(); set.add((E) a); assertEquals(1, set.size()); set.add((E) b); // will match but not replace A as equal assertEquals(1, set.size()); assertSame(a, set.decorated().iterator().next()); assertSame(a, set.iterator().next()); assertSame(a, set.get(0)); assertSame(a, set.asList().get(0)); } @SuppressWarnings("unchecked") public void testRetainAll() { final List list = new ArrayList(10); final Set set = new HashSet(10); final ListOrderedSet orderedSet = ListOrderedSet.listOrderedSet(set, list); for (int i = 0; i < 10; ++i) { orderedSet.add((E) Integer.valueOf(10 - i - 1)); } final Collection retained = new ArrayList(5); for (int i = 0; i < 5; ++i) { retained.add((E) Integer.valueOf(i * 2)); } assertTrue(orderedSet.retainAll(retained)); assertEquals(5, orderedSet.size()); // insertion order preserved? assertEquals(Integer.valueOf(8), orderedSet.get(0)); assertEquals(Integer.valueOf(6), orderedSet.get(1)); assertEquals(Integer.valueOf(4), orderedSet.get(2)); assertEquals(Integer.valueOf(2), orderedSet.get(3)); assertEquals(Integer.valueOf(0), orderedSet.get(4)); } /* * test case for https://issues.apache.org/jira/browse/COLLECTIONS-426 */ @SuppressWarnings("boxing") // OK in test code public void testRetainAllCollections426() { final int size = 100000; final ListOrderedSet set = new ListOrderedSet(); for (int i = 0; i < size; i++) { set.add(i); } final ArrayList list = new ArrayList(); for (int i = size; i < 2 * size; i++) { list.add(i); } final long start = System.currentTimeMillis(); set.retainAll(list); final long stop = System.currentTimeMillis(); // make sure retainAll completes under 5 seconds // TODO if test is migrated to JUnit 4, add a Timeout rule. // http://kentbeck.github.com/junit/javadoc/latest/org/junit/rules/Timeout.html assertTrue(stop - start < 5000); } static class A { @Override public boolean equals(final Object obj) { return obj instanceof A || obj instanceof B; } @Override public int hashCode() { return 1; } } static class B { @Override public boolean equals(final Object obj) { return obj instanceof A || obj instanceof B; } @Override public int hashCode() { return 1; } } public void testDecorator() { try { ListOrderedSet.listOrderedSet((List) null); fail(); } catch (final IllegalArgumentException ex) { } try { ListOrderedSet.listOrderedSet((Set) null); fail(); } catch (final IllegalArgumentException ex) { } try { ListOrderedSet.listOrderedSet(null, null); fail(); } catch (final IllegalArgumentException ex) { } try { ListOrderedSet.listOrderedSet(new HashSet(), null); fail(); } catch (final IllegalArgumentException ex) { } try { ListOrderedSet.listOrderedSet(null, new ArrayList()); fail(); } catch (final IllegalArgumentException ex) { } } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/ListOrderedSet.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/ListOrderedSet.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/MapBackedSetTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/MapBackedSetTest.java100664 3414 12243235516 31554 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Set; import org.apache.commons.collections4.map.HashedMap; /** * JUnit test. * * @since 3.1 * @version $Id: MapBackedSetTest.java 1469009 2013-04-17 17:56:22Z tn $ */ public class MapBackedSetTest extends AbstractSetTest { public MapBackedSetTest(final String testName) { super(testName); } @Override public Set makeObject() { return MapBackedSet.mapBackedSet(new HashedMap()); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/MapBackedSet.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/MapBackedSet.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/TransformedSetTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/TransformedSetTest.ja100664 10265 12243235516 31724 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.collection.TransformedCollectionTest; /** * Extension of {@link AbstractSetTest} for exercising the {@link TransformedSet} * implementation. * * @since 3.0 * @version $Id: TransformedSetTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class TransformedSetTest extends AbstractSetTest { public TransformedSetTest(final String testName) { super(testName); } @Override public Set makeConfirmedCollection() { return new HashSet(); } @Override public Set makeConfirmedFullCollection() { final Set set = new HashSet(); set.addAll(Arrays.asList(getFullElements())); return set; } @Override @SuppressWarnings("unchecked") public Set makeObject() { return TransformedSet.transformingSet(new HashSet(), (Transformer) TransformedCollectionTest.NOOP_TRANSFORMER); } @Override @SuppressWarnings("unchecked") public Set makeFullCollection() { final Set list = new HashSet(); list.addAll(Arrays.asList(getFullElements())); return TransformedSet.transformingSet(list, (Transformer) TransformedCollectionTest.NOOP_TRANSFORMER); } @SuppressWarnings("unchecked") public void testTransformedSet() { final Set set = TransformedSet.transformingSet(new HashSet(), (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(0, set.size()); final E[] els = (E[]) 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(Integer.valueOf((String) els[i]))); assertEquals(false, set.contains(els[i])); } assertEquals(false, set.remove(els[0])); assertEquals(true, set.remove(Integer.valueOf((String) els[0]))); } public void testTransformedSet_decorateTransform() { final Set originalSet = new HashSet(); final Object[] els = new Object[] {"1", "3", "5", "7", "2", "4", "6"}; Collections.addAll(originalSet, els); final Set set = TransformedSet.transformedSet(originalSet, TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER); assertEquals(els.length, set.size()); for (final Object el : els) { assertEquals(true, set.contains(Integer.valueOf((String) el))); assertEquals(false, set.contains(el)); } assertEquals(false, set.remove(els[0])); assertEquals(true, set.remove(Integer.valueOf((String) els[0]))); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/TransformedSet.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/TransformedSet.fullCollection.version4.obj"); // } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/EmptySetMutator.java100664 3566 12243235516 31567 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Collection; import java.util.List; import java.util.Set; /** * This class is used in CompositeSetTest. When testing serialization, * the class has to be separate of CompositeSetTest, else the test * class also has to be serialized. */ class EmptySetMutator implements CompositeSet.SetMutator { /** Serialization version */ private static final long serialVersionUID = 5321193666420238910L; private final Set contained; public EmptySetMutator(final Set set) { this.contained = set; } public void resolveCollision(final CompositeSet comp, final Set existing, final Set added, final Collection intersects) { throw new IllegalArgumentException(); } public boolean add(final CompositeSet composite, final List> collections, final E obj) { return contained.add(obj); } public boolean addAll(final CompositeSet composite, final List> collections, final Collection coll) { return contained.addAll(coll); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/AbstractSetTest.java100664 13214 12243235516 31527 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.apache.commons.collections4.collection.AbstractCollectionTest; /** * 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 #makeObject()} * 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 AbstractCollectionTest} for more details. * * @since 3.0 * @version $Id: AbstractSetTest.java 1543158 2013-11-18 21:07:59Z ggregory $ */ public abstract class AbstractSetTest extends AbstractCollectionTest { /** * JUnit constructor. * * @param name name for test */ public AbstractSetTest(final String name) { super(name); } //----------------------------------------------------------------------- /** * Provides additional verifications for sets. */ @Override public void verify() { super.verify(); assertEquals("Sets should be equal", getConfirmed(), getCollection()); assertEquals("Sets should have equal hashCodes", getConfirmed().hashCode(), getCollection().hashCode()); final Collection set = makeConfirmedCollection(); for (E element : getCollection()) { assertTrue("Set.iterator should only return unique elements", set.add(element)); } } //----------------------------------------------------------------------- /** * Set equals method is defined. */ @Override public boolean isEqualsCheckable() { return true; } /** * Returns an empty Set for use in modification testing. * * @return a confirmed empty collection */ @Override public Collection makeConfirmedCollection() { return new HashSet(); } /** * Returns a full Set for use in modification testing. * * @return a confirmed full collection */ @Override public Collection makeConfirmedFullCollection() { final 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 */ @Override public abstract Set makeObject(); /** * 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 */ @Override public Set makeFullCollection() { final Set set = makeObject(); set.addAll(Arrays.asList(getFullElements())); return set; } //----------------------------------------------------------------------- /** * Return the {@link AbstractCollectionTest#collection} fixture, but cast as a Set. */ @Override public Set getCollection() { return (Set) super.getCollection(); } /** * Return the {@link AbstractCollectionTest#confirmed} fixture, but cast as a Set. */ @Override public Set getConfirmed() { return (Set) super.getConfirmed(); } //----------------------------------------------------------------------- /** * Tests {@link Set#equals(Object)}. */ @SuppressWarnings("unchecked") public void testSetEquals() { resetEmpty(); assertEquals("Empty sets should be equal", getCollection(), getConfirmed()); verify(); final Collection set2 = makeConfirmedCollection(); set2.add((E) "foo"); assertTrue("Empty set shouldn't equal nonempty set", !getCollection().equals(set2)); resetFull(); assertEquals("Full sets should be equal", getCollection(), getConfirmed()); verify(); set2.clear(); set2.addAll(Arrays.asList(getOtherElements())); assertTrue("Sets with different contents shouldn't be equal", !getCollection().equals(set2)); } /** * Tests {@link Set#hashCode()}. */ public void testSetHashCode() { resetEmpty(); assertEquals("Empty sets have equal hashCodes", getCollection().hashCode(), getConfirmed().hashCode()); resetFull(); assertEquals("Equal sets have equal hashCodes", getCollection().hashCode(), getConfirmed().hashCode()); } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/UnmodifiableSortedSetTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/UnmodifiableSortedSet100664 12577 12243235516 31776 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.ArrayList; 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.collections4.BulkTest; /** * Extension of {@link AbstractSortedSetTest} for exercising the * {@link UnmodifiableSortedSet} implementation. * * @since 3.0 * @version $Id: UnmodifiableSortedSetTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class UnmodifiableSortedSetTest extends AbstractSortedSetTest { protected UnmodifiableSortedSet set = null; protected ArrayList array = null; public UnmodifiableSortedSetTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(UnmodifiableSortedSetTest.class); } //------------------------------------------------------------------- @Override public SortedSet makeObject() { return UnmodifiableSortedSet.unmodifiableSortedSet(new TreeSet()); } @Override public UnmodifiableSortedSet makeFullCollection() { final TreeSet set = new TreeSet(); set.addAll(Arrays.asList(getFullElements())); return (UnmodifiableSortedSet) UnmodifiableSortedSet.unmodifiableSortedSet(set); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } //-------------------------------------------------------------------- @SuppressWarnings("unchecked") protected void setupSet() { set = makeFullCollection(); array = new ArrayList(); array.add((E) Integer.valueOf(1)); } /** * Verify that base set and subsets are not modifiable */ @SuppressWarnings("unchecked") public void testUnmodifiable() { setupSet(); verifyUnmodifiable(set); verifyUnmodifiable(set.headSet((E) Integer.valueOf(1))); verifyUnmodifiable(set.tailSet((E) Integer.valueOf(1))); verifyUnmodifiable(set.subSet((E) Integer.valueOf(1), (E) Integer.valueOf(3))); } public void testDecorateFactory() { final SortedSet set = makeFullCollection(); assertSame(set, UnmodifiableSortedSet.unmodifiableSortedSet(set)); try { UnmodifiableSortedSet.unmodifiableSortedSet(null); fail(); } catch (final IllegalArgumentException ex) {} } /** * Verifies that a set is not modifiable */ @SuppressWarnings("unchecked") public void verifyUnmodifiable(final Set set) { try { set.add((E) "value"); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { set.addAll(new TreeSet()); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { set.clear(); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { set.remove("x"); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { set.removeAll(array); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } try { set.retainAll(array); fail("Expecting UnsupportedOperationException."); } catch (final UnsupportedOperationException e) { // expected } } public void testComparator() { setupSet(); final Comparator c = set.comparator(); assertTrue("natural order, so comparator should be null", c == null); } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableSortedSet.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableSortedSet.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/UnmodifiableSetTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/UnmodifiableSetTest.j100664 6224 12243235516 31655 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.Unmodifiable; /** * Extension of {@link AbstractSetTest} for exercising the * {@link UnmodifiableSet} implementation. * * @since 3.0 * @version $Id: UnmodifiableSetTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class UnmodifiableSetTest extends AbstractSetTest { public UnmodifiableSetTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(UnmodifiableSetTest.class); } //------------------------------------------------------------------- @Override public Set makeObject() { return UnmodifiableSet.unmodifiableSet(new HashSet()); } @Override public Set makeFullCollection() { final HashSet set = new HashSet(); set.addAll(Arrays.asList(getFullElements())); return UnmodifiableSet.unmodifiableSet(set); } @Override public boolean isAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullCollection() instanceof Unmodifiable); } public void testDecorateFactory() { final Set set = makeFullCollection(); assertSame(set, UnmodifiableSet.unmodifiableSet(set)); try { UnmodifiableSet.unmodifiableSet(null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableSet.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableSet.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/PredicatedSortedSetTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/PredicatedSortedSetTe100664 11374 12243235516 31727 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.BulkTest; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.functors.TruePredicate; /** * Extension of {@link AbstractSortedSetTest} for exercising the * {@link PredicatedSortedSet} implementation. * * @since 3.0 * @version $Id: PredicatedSortedSetTest.java 1470323 2013-04-21 17:51:33Z tn $ */ public class PredicatedSortedSetTest extends AbstractSortedSetTest { public PredicatedSortedSetTest(final String testName) { super(testName); } public static Test suite() { return BulkTest.makeSuite(PredicatedSortedSetTest.class); } //------------------------------------------------------------------- protected Predicate truePredicate = TruePredicate.truePredicate(); @Override public SortedSet makeObject() { return PredicatedSortedSet.predicatedSortedSet(new TreeSet(), truePredicate); } @Override public SortedSet makeFullCollection() { final TreeSet set = new TreeSet(); set.addAll(Arrays.asList(getFullElements())); return PredicatedSortedSet.predicatedSortedSet(set, truePredicate); } //-------------------------------------------------------------------- protected Predicate testPredicate = new Predicate() { public boolean evaluate(final E o) { return o instanceof String && ((String) o).startsWith("A"); } }; protected PredicatedSortedSet makeTestSet() { return PredicatedSortedSet.predicatedSortedSet(new TreeSet(), testPredicate); } public void testGetSet() { final PredicatedSortedSet set = makeTestSet(); assertTrue("returned set should not be null", set.decorated() != null); } @SuppressWarnings("unchecked") public void testIllegalAdd() { final SortedSet set = makeTestSet(); final String testString = "B"; try { set.add((E) testString); fail("Should fail string predicate."); } catch (final IllegalArgumentException e) { // expected } assertTrue("Collection shouldn't contain illegal element", !set.contains(testString)); } @SuppressWarnings("unchecked") public void testIllegalAddAll() { final SortedSet set = makeTestSet(); final Set elements = new TreeSet(); elements.add((E) "Aone"); elements.add((E) "Atwo"); elements.add((E) "Bthree"); elements.add((E) "Afour"); try { set.addAll(elements); fail("Should fail string predicate."); } catch (final 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() { final SortedSet set = makeTestSet(); final Comparator c = set.comparator(); assertTrue("natural order, so comparator should be null", c == null); } @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/PredicatedSortedSet.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/PredicatedSortedSet.fullCollection.version4.obj"); // } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/ListOrderedSet2Test.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/ListOrderedSet2Test.j100664 12615 12243235516 31602 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Extension of {@link AbstractSetTest} for exercising the {@link ListOrderedSet} * implementation. * * @since 3.1 * @version $Id: ListOrderedSet2Test.java 1476855 2013-04-28 23:15:54Z sebb $ */ public class ListOrderedSet2Test extends AbstractSetTest { private static final Integer ZERO = Integer.valueOf(0); private static final Integer ONE = Integer.valueOf(1); private static final Integer TWO = Integer.valueOf(2); private static final Integer THREE = Integer.valueOf(3); public ListOrderedSet2Test(final String testName) { super(testName); } @Override public ListOrderedSet makeObject() { return new ListOrderedSet(); } @SuppressWarnings("unchecked") protected ListOrderedSet setupSet() { final ListOrderedSet set = makeObject(); for (int i = 0; i < 10; i++) { set.add((E) Integer.toString(i)); } return set; } @SuppressWarnings("unchecked") public void testOrdering() { final ListOrderedSet 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((E) 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()); } } @SuppressWarnings("unchecked") public void testListAddRemove() { final ListOrderedSet set = makeObject(); final List view = set.asList(); set.add((E) ZERO); set.add((E) ONE); set.add((E) 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)); } @SuppressWarnings("unchecked") public void testListAddIndexed() { final ListOrderedSet set = makeObject(); set.add((E) ZERO); set.add((E) TWO); set.add(1, (E) ONE); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); set.add(0, (E) ONE); assertEquals(3, set.size()); assertSame(ZERO, set.get(0)); assertSame(ONE, set.get(1)); assertSame(TWO, set.get(2)); final List list = new ArrayList(); list.add((E) ZERO); list.add((E) 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, (E) 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)); } @Override public String getCompatibilityVersion() { return "4"; } // 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"); // } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/AbstractSortedSetTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/set/AbstractSortedSetTest100664 27741 12243235516 32002 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.collections4.BulkTest; /** * Abstract test class for {@link SortedSet} methods and contracts. *

* To use, subclass and override the {@link #makeObject()} * 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 AbstractSetTest} for more details. * * @since 3.0 * @version $Id: AbstractSortedSetTest.java 1477661 2013-04-30 14:27:35Z sebb $ */ public abstract class AbstractSortedSetTest extends AbstractSetTest { /** * JUnit constructor. * * @param name name for test */ public AbstractSortedSetTest(final String name) { super(name); } //----------------------------------------------------------------------- /** * Verification extension, will check the order of elements, * the sets should already be verified equal. */ @Override public void verify() { super.verify(); // Check that iterator returns elements in order and first() and last() // are consistent final Iterator colliter = getCollection().iterator(); final Iterator confiter = getConfirmed().iterator(); E first = null; E 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 (getCollection().size() > 0) { assertEquals("Incorrect element returned by first().", first, getCollection().first()); assertEquals("Incorrect element returned by last().", last, getCollection().last()); } } //----------------------------------------------------------------------- /** * Overridden because SortedSets don't allow null elements (normally). * @return false */ @Override public boolean isNullSupported() { return false; } /** * {@inheritDoc} */ @Override public abstract SortedSet makeObject(); /** * {@inheritDoc} */ @Override public SortedSet makeFullCollection() { return (SortedSet) super.makeFullCollection(); } //----------------------------------------------------------------------- /** * Returns an empty {@link TreeSet} for use in modification testing. * * @return a confirmed empty collection */ @Override public SortedSet makeConfirmedCollection() { return new TreeSet(); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** * Override to return comparable objects. */ @Override @SuppressWarnings("unchecked") public E[] getFullNonNullElements() { final Object[] elements = new Object[30]; for (int i = 0; i < 30; i++) { elements[i] = Integer.valueOf(i + i + 1); } return (E[]) elements; } /** * Override to return comparable objects. */ @Override @SuppressWarnings("unchecked") public E[] getOtherNonNullElements() { final Object[] elements = new Object[30]; for (int i = 0; i < 30; i++) { elements[i] = Integer.valueOf(i + i + 2); } return (E[]) elements; } //----------------------------------------------------------------------- /** * Bulk test {@link SortedSet#subSet(Object, Object)}. This method runs through all of * the tests in {@link AbstractSortedSetTest}. * After modification operations, {@link #verify()} is invoked to ensure * that the set and the other collection views are still valid. * * @return a {@link AbstractSetTest} instance for testing a subset. */ public BulkTest bulkTestSortedSetSubSet() { final int length = getFullElements().length; final int lobound = length / 3; final 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 AbstractSortedSetTest}. * After modification operations, {@link #verify()} is invoked to ensure * that the set and the other collection views are still valid. * * @return a {@link AbstractSetTest} instance for testing a headset. */ public BulkTest bulkTestSortedSetHeadSet() { final int length = getFullElements().length; final int lobound = length / 3; final 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 AbstractSortedSetTest}. * After modification operations, {@link #verify()} is invoked to ensure * that the set and the other collection views are still valid. * * @return a {@link AbstractSetTest} instance for testing a tailset. */ public BulkTest bulkTestSortedSetTailSet() { final int length = getFullElements().length; final int lobound = length / 3; return new TestSortedSetSubSet(lobound, false); } public class TestSortedSetSubSet extends AbstractSortedSetTest { private int m_Type; private int m_LowBound; private int m_HighBound; private E[] m_FullElements; private E[] m_OtherElements; @SuppressWarnings("unchecked") public TestSortedSetSubSet(final int bound, final boolean head) { super("TestSortedSetSubSet"); if (head) { //System.out.println("HEADSET"); m_Type = TYPE_HEADSET; m_HighBound = bound; m_FullElements = (E[]) new Object[bound]; System.arraycopy(AbstractSortedSetTest.this.getFullElements(), 0, m_FullElements, 0, bound); m_OtherElements = (E[]) new Object[bound - 1]; System.arraycopy(//src src_pos dst dst_pos length AbstractSortedSetTest.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; final Object[] allelements = AbstractSortedSetTest.this.getFullElements(); //System.out.println("bound = "+bound +"::length="+allelements.length); m_FullElements = (E[]) new Object[allelements.length - bound]; System.arraycopy(allelements, bound, m_FullElements, 0, allelements.length - bound); m_OtherElements = (E[]) new Object[allelements.length - bound - 1]; System.arraycopy(//src src_pos dst dst_pos length AbstractSortedSetTest.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 @SuppressWarnings("unchecked") public TestSortedSetSubSet(final int lobound, final int hibound) { super("TestSortedSetSubSet"); //System.out.println("SUBSET"); m_Type = TYPE_SUBSET; m_LowBound = lobound; m_HighBound = hibound; final int length = hibound - lobound; //System.out.println("Low=" + lobound + "::High=" + hibound + "::Length=" + length); m_FullElements = (E[]) new Object[length]; System.arraycopy(AbstractSortedSetTest.this.getFullElements(), lobound, m_FullElements, 0, length); m_OtherElements = (E[]) new Object[length - 1]; System.arraycopy(//src src_pos dst dst_pos length AbstractSortedSetTest.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))); } @Override public boolean isNullSupported() { return AbstractSortedSetTest.this.isNullSupported(); } @Override public boolean isAddSupported() { return AbstractSortedSetTest.this.isAddSupported(); } @Override public boolean isRemoveSupported() { return AbstractSortedSetTest.this.isRemoveSupported(); } @Override public boolean isFailFastSupported() { return AbstractSortedSetTest.this.isFailFastSupported(); } @Override public E[] getFullElements() { return m_FullElements; } @Override public E[] getOtherElements() { return m_OtherElements; } private SortedSet getSubSet(final SortedSet set) { final E[] elements = AbstractSortedSetTest.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; } } @Override public SortedSet makeObject() { return getSubSet(AbstractSortedSetTest.this.makeObject()); } @Override public SortedSet makeFullCollection() { return getSubSet(AbstractSortedSetTest.this.makeFullCollection()); } @Override public boolean isTestSerialization() { return false; } @Override public BulkTest bulkTestSortedSetSubSet() { return null; // prevent infinite recursion } @Override public BulkTest bulkTestSortedSetHeadSet() { return null; // prevent infinite recursion } @Override 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; } /** * {@inheritDoc} */ @Override public SortedSet getCollection() { return (SortedSet) super.getCollection(); } /** * {@inheritDoc} */ @Override public SortedSet getConfirmed() { return (SortedSet) super.getConfirmed(); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/AbstractTreeMapTest.java100664 3724 12243235516 31523 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.TreeMap; import org.apache.commons.collections4.map.AbstractMapTest; /** * Tests TreeMap. * * @version $Id: AbstractTreeMapTest.java 1469004 2013-04-17 17:37:03Z tn $ */ public abstract class AbstractTreeMapTest extends AbstractMapTest { public AbstractTreeMapTest(final String testName) { super(testName); } @Override public boolean isAllowNullKey() { return false; } /** * {@inheritDoc} */ @Override public abstract TreeMap makeObject(); public void testNewMap() { final TreeMap map = makeObject(); assertTrue("New map is empty", map.isEmpty()); assertEquals("New map has size zero", 0, map.size()); } @SuppressWarnings("unchecked") public void testSearch() { final TreeMap map = makeObject(); map.put((K) "first", (V) "First Item"); map.put((K) "second", (V) "Second Item"); assertEquals("Top item is 'Second Item'", "First Item", map.get("first")); assertEquals("Next Item is 'First Item'", "Second Item", map.get("second")); } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/EqualPredicateTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/EqualPredicateTe100664 4563 12243235516 31750 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import static org.apache.commons.collections4.functors.EqualPredicate.equalPredicate; import static org.apache.commons.collections4.functors.NullPredicate.nullPredicate; import static org.junit.Assert.assertSame; import org.apache.commons.collections4.Predicate; import org.junit.Test; public class EqualPredicateTest extends AbstractPredicateTest { private static final EqualsTestObject FALSE_OBJECT = new EqualsTestObject(false); private static final EqualsTestObject TRUE_OBJECT = new EqualsTestObject(true); @Override protected Predicate generatePredicate() { return equalPredicate(null); } @Test public void testNullArgumentEqualsNullPredicate() throws Exception { assertSame(nullPredicate(), equalPredicate(null)); } @Test public void objectFactoryUsesEqualsForTest() throws Exception { final Predicate predicate = equalPredicate(FALSE_OBJECT); assertFalse(predicate, FALSE_OBJECT); assertTrue(equalPredicate(TRUE_OBJECT), TRUE_OBJECT); } @SuppressWarnings("boxing") @Test public void testPredicateTypeCanBeSuperClassOfObject() throws Exception { final Predicate predicate = equalPredicate((Number) 4); assertTrue(predicate, 4); } public static class EqualsTestObject { private final boolean b; public EqualsTestObject(final boolean b) { this.b = b; } @Override public boolean equals(final Object obj) { return b; } } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AllPredicateTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AllPredicateTest100664 11666 12243235516 32002 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import org.apache.commons.collections4.Predicate; import static org.apache.commons.collections4.functors.AllPredicate.allPredicate; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import java.util.Collection; import java.util.Collections; /** * Tests the org.apache.commons.collections.functors.AllPredicate class. * * @since 3.0 * @version $Id: AllPredicateTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("boxing") public class AllPredicateTest extends AbstractAnyAllOnePredicateTest { /** * Creates a new TestAllPredicate. */ public AllPredicateTest() { super(42); } /** * {@inheritDoc} */ @Override protected final Predicate getPredicateInstance(final Predicate ... predicates) { return AllPredicate.allPredicate(predicates); } /** * {@inheritDoc} */ @Override protected final Predicate getPredicateInstance(final Collection> predicates) { return AllPredicate.allPredicate(predicates); } /** * Verifies that providing an empty predicate array evaluates to true. */ @SuppressWarnings({"unchecked"}) @Test public void emptyArrayToGetInstance() { assertTrue("empty array not true", getPredicateInstance(new Predicate[] {}).evaluate(null)); } /** * Verifies that providing an empty predicate collection evaluates to true. */ @Test public void emptyCollectionToGetInstance() { final Predicate allPredicate = getPredicateInstance( Collections.>emptyList()); assertTrue("empty collection not true", allPredicate.evaluate(getTestValue())); } /** * Tests whether a single true predicate evaluates to true. */ @SuppressWarnings("unchecked") @Test public void oneTruePredicate() { // use the constructor directly, as getInstance() returns the original predicate when passed // an array of size one. final Predicate predicate = createMockPredicate(true); assertTrue("single true predicate evaluated to false", allPredicate(predicate).evaluate(getTestValue())); } /** * Tests whether a single false predicate evaluates to true. */ @SuppressWarnings("unchecked") @Test public void oneFalsePredicate() { // use the constructor directly, as getInstance() returns the original predicate when passed // an array of size one. final Predicate predicate = createMockPredicate(false); assertFalse("single false predicate evaluated to true", allPredicate(predicate).evaluate(getTestValue())); } /** * Tests whether multiple true predicates evaluates to true. */ @Test public void allTrue() { assertTrue("multiple true predicates evaluated to false", getPredicateInstance(true, true).evaluate(getTestValue())); assertTrue("multiple true predicates evaluated to false", getPredicateInstance(true, true, true).evaluate(getTestValue())); } /** * Tests whether combining some true and one false evalutes to false. Also verifies that only the first * false predicate is actually evaluated */ @Test public void trueAndFalseCombined() { assertFalse("false predicate evaluated to true", getPredicateInstance(false, null).evaluate(getTestValue())); assertFalse("false predicate evaluated to true", getPredicateInstance(false, null, null).evaluate(getTestValue())); assertFalse("false predicate evaluated to true", getPredicateInstance(true, false, null).evaluate(getTestValue())); assertFalse("false predicate evaluated to true", getPredicateInstance(true, true, false).evaluate(getTestValue())); assertFalse("false predicate evaluated to true", getPredicateInstance(true, true, false, null).evaluate(getTestValue())); } } ././@LongLink100644 0 0 170 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AbstractCompositePredicateTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AbstractComposit100664 12313 12243235516 32060 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import org.apache.commons.collections4.Predicate; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Base class for tests of composite predicates. * * @since 3.0 * @version $Id: AbstractCompositePredicateTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public abstract class AbstractCompositePredicateTest extends AbstractMockPredicateTest { /** * Creates a new TestCompositePredicate. * * @param testValue the value which the mock predicates should expect to see (may be null). */ protected AbstractCompositePredicateTest(final T testValue) { super(testValue); } /** * Creates an instance of the predicate to test. * * @param predicates the arguments to getInstance. * * @return a predicate to test. */ protected abstract Predicate getPredicateInstance(final Predicate ... predicates); /** * Creates an instance of the predicate to test. * * @param predicates the argument to getInstance. * * @return a predicate to test. */ protected abstract Predicate getPredicateInstance(final Collection> predicates); /** * Creates an instance of the predicate to test. * * @param mockReturnValues the return values for the mock predicates, or null if that mock is not expected * to be called * * @return a predicate to test. */ protected final Predicate getPredicateInstance(final Boolean... mockReturnValues) { final List> predicates = new ArrayList>(); for (final Boolean returnValue : mockReturnValues) { predicates.add(createMockPredicate(returnValue)); } return getPredicateInstance(predicates); } /** * Tests whether getInstance with a one element array returns the first element in the array. */ @SuppressWarnings("unchecked") public void singleElementArrayToGetInstance() { final Predicate predicate = createMockPredicate(null); final Predicate allPredicate = getPredicateInstance(predicate); Assert.assertSame("expected argument to be returned by getInstance()", predicate, allPredicate); } /** * Tests that passing a singleton collection to getInstance returns the single element in the * collection. */ public void singletonCollectionToGetInstance() { final Predicate predicate = createMockPredicate(null); final Predicate allPredicate = getPredicateInstance( Collections.>singleton(predicate)); Assert.assertSame("expected argument to be returned by getInstance()", predicate, allPredicate); } /** * Tests getInstance with a null predicate array. */ @Test(expected = IllegalArgumentException.class) public final void nullArrayToGetInstance() { getPredicateInstance((Predicate[]) null); } /** * Tests getInstance with a single null element in the predicate array. */ @SuppressWarnings({"unchecked"}) @Test(expected = IllegalArgumentException.class) public final void nullElementInArrayToGetInstance() { getPredicateInstance(new Predicate[] { null }); } /** * Tests getInstance with two null elements in the predicate array. */ @SuppressWarnings({"unchecked"}) @Test(expected = IllegalArgumentException.class) public final void nullElementsInArrayToGetInstance() { getPredicateInstance(new Predicate[] { null, null }); } /** * Tests getInstance with a null predicate collection */ @Test(expected = IllegalArgumentException.class) public final void nullCollectionToGetInstance() { getPredicateInstance((Collection>) null); } /** * Tests getInstance with a predicate collection that contains null elements */ @Test(expected = IllegalArgumentException.class) public final void nullElementsInCollectionToGetInstance() { final Collection> coll = new ArrayList>(); coll.add(null); coll.add(null); getPredicateInstance(coll); } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AbstractClosureTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AbstractClosureT100664 2410 12243235516 32000 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import org.apache.commons.collections4.Closure; import org.junit.Assert; import org.junit.Test; public abstract class AbstractClosureTest { @Test public void closureSanityTests() throws Exception { final Closure closure = generateClosure(); Assert.assertNotNull(closure); } /** * @return a closure for general sanity tests. */ protected abstract Closure generateClosure(); } ././@LongLink100644 0 0 170 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AbstractAnyAllOnePredicateTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AbstractAnyAllOn100664 6045 12243235516 31725 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import org.apache.commons.collections4.Predicate; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.junit.Test; import java.util.Collections; /** * Base class for tests of AnyPredicate, AllPredicate, and OnePredicate. * * @since 3.0 * @version $Id: AbstractAnyAllOnePredicateTest.java 1469004 2013-04-17 17:37:03Z tn $ */ public abstract class AbstractAnyAllOnePredicateTest extends AbstractCompositePredicateTest { /** * Creates a new TestCompositePredicate. * * @param testValue the value which the mock predicates should expect to see (may be null). */ protected AbstractAnyAllOnePredicateTest(final T testValue) { super(testValue); } /** * Tests whether getInstance with a one element array returns the first element in the array. */ @Override @SuppressWarnings("unchecked") @Test public final void singleElementArrayToGetInstance() { final Predicate predicate = createMockPredicate(null); final Predicate allPredicate = getPredicateInstance(predicate); assertSame("expected argument to be returned by getInstance()", predicate, allPredicate); } /** * Tests that passing a singleton collection to getInstance returns the single element in the * collection. */ @Override @Test public final void singletonCollectionToGetInstance() { final Predicate predicate = createMockPredicate(null); final Predicate allPredicate = getPredicateInstance( Collections.>singleton(predicate)); assertSame("expected singleton collection member to be returned by getInstance()", predicate, allPredicate); } /** * Tests creating composite predicate instances with single predicates and verifies that the composite returns * the same value as the single predicate does. */ @SuppressWarnings("boxing") public final void singleValues() { assertTrue(getPredicateInstance(true).evaluate(null)); assertFalse(getPredicateInstance(false).evaluate(null)); } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/NullPredicateTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/NullPredicateTes100664 3114 12243235516 31765 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import static org.apache.commons.collections4.functors.NullPredicate.nullPredicate; import static org.junit.Assert.assertSame; import org.apache.commons.collections4.Predicate; import org.junit.Test; public class NullPredicateTest extends AbstractPredicateTest { @Test public void testNullPredicate() { assertSame(NullPredicate.nullPredicate(), NullPredicate.nullPredicate()); assertTrue(nullPredicate(), null); } @Test public void ensurePredicateCanBeTypedWithoutWarning() throws Exception { final Predicate predicate = NullPredicate.nullPredicate(); assertFalse(predicate, cString); } @Override protected Predicate generatePredicate() { return nullPredicate(); } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AbstractPredicateTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AbstractPredicat100664 3557 12243235516 32010 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import org.apache.commons.collections4.Predicate; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public abstract class AbstractPredicateTest { protected Object cObject; protected String cString; protected Integer cInteger; @Before public void initialiseTestObjects() throws Exception { cObject = new Object(); cString = "Hello"; cInteger = Integer.valueOf(6); } @Test public void predicateSanityTests() throws Exception { final Predicate predicate = generatePredicate(); Assert.assertNotNull(predicate); } /** * @return a predicate for general sanity tests. */ protected abstract Predicate generatePredicate(); protected void assertFalse(final Predicate predicate, final T testObject) { Assert.assertFalse(predicate.evaluate(testObject)); } protected void assertTrue(final Predicate predicate, final T testObject) { Assert.assertTrue(predicate.evaluate(testObject)); } } ././@LongLink100644 0 0 164 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/CatchAndRethrowClosureTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/CatchAndRethrowC100664 5755 12243235516 31716 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.IOException; import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.FunctorException; import org.junit.Assert; import org.junit.Test; public class CatchAndRethrowClosureTest extends AbstractClosureTest { private static Closure generateIOExceptionClosure() { return new CatchAndRethrowClosure() { @Override protected void executeAndThrow(final T input) throws IOException { throw new IOException(); } }; } private static Closure generateNullPointerExceptionClosure() { return new CatchAndRethrowClosure() { @Override protected void executeAndThrow(final T input) { throw new NullPointerException(); } }; } private static Closure generateNoExceptionClosure() { return new CatchAndRethrowClosure() { @Override protected void executeAndThrow(final T input) { } }; } @Override protected Closure generateClosure() { return generateNoExceptionClosure(); } @Test public void testThrowingClosure() { Closure closure = generateNoExceptionClosure(); try { closure.execute(Integer.valueOf(0)); } catch (final FunctorException ex) { Assert.fail(); } catch (final RuntimeException ex) { Assert.fail(); } closure = generateIOExceptionClosure(); try { closure.execute(Integer.valueOf(0)); Assert.fail(); } catch (final FunctorException ex) { Assert.assertTrue(ex.getCause() instanceof IOException); } catch (final RuntimeException ex) { Assert.fail(); } closure = generateNullPointerExceptionClosure(); try { closure.execute(Integer.valueOf(0)); Assert.fail(); } catch (final FunctorException ex) { Assert.fail(); } catch (final RuntimeException ex) { Assert.assertTrue(ex instanceof NullPointerException); } } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AbstractMockPredicateTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/AbstractMockPred100664 6411 12243235516 31751 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.util.ArrayList; import java.util.List; import static org.easymock.EasyMock.verify; import static org.easymock.EasyMock.replay; import org.junit.Before; import org.junit.After; import org.apache.commons.collections4.Predicate; import org.easymock.EasyMock; /** * Base class for tests of predicates which delegate to other predicates when evaluating an object. This class * provides methods to create and verify mock predicates to which to delegate. * * @since 3.0 * @version $Id: AbstractMockPredicateTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ public abstract class AbstractMockPredicateTest { /** * Mock predicates created by a single test case which need to be verified after the test completes. */ private List> mockPredicatesToVerify; /** * The value to pass to mocks. */ private final T testValue; /** * Creates a new PredicateTestBase. * * @param testValue the value to pass to mock predicates. */ protected AbstractMockPredicateTest(final T testValue) { this.testValue = testValue; } /** * Creates the list of predicates to verify. */ @Before public final void createVerifyList() { mockPredicatesToVerify = new ArrayList>(); } /** * Verifies all the mock predicates created for the test. */ @After public final void verifyPredicates() { for (final Predicate predicate : mockPredicatesToVerify) { verify(predicate); } } /** * Gets the value which will be passed to the mock predicates. * * @return the test value. */ protected final T getTestValue() { return testValue; } /** * Creates a single mock predicate. * * @param returnValue the return value for the mock predicate, or null if the mock is not expected to be called. * * @return a single mock predicate. */ @SuppressWarnings({"unchecked", "boxing"}) protected final Predicate createMockPredicate(final Boolean returnValue) { final Predicate mockPredicate = EasyMock.createMock(Predicate.class); if (returnValue != null) { EasyMock.expect(mockPredicate.evaluate(testValue)).andReturn(returnValue); } replay(mockPredicate); mockPredicatesToVerify.add(mockPredicate); return mockPredicate; } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/ComparatorPredicateTest.javacommons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/functors/ComparatorPredic100664 6630 12243235516 32022 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import static org.apache.commons.collections4.functors.ComparatorPredicate.*; import java.util.Comparator; import org.apache.commons.collections4.Predicate; import org.junit.Test; public class ComparatorPredicateTest extends AbstractPredicateTest { private class TestComparator> implements Comparator { public int compare(final T first, final T second) { return first.compareTo(second); } } @Test public void compareEquals() { final Integer value = Integer.valueOf(10); final Predicate p = comparatorPredicate(value, new TestComparator()); assertFalse(p, Integer.valueOf(value.intValue() - 1)); assertTrue(p, Integer.valueOf(value.intValue())); assertFalse(p, Integer.valueOf(value.intValue() + 1)); } @Test public void compareGreater() { final Integer value = Integer.valueOf(10); final Predicate p = comparatorPredicate(value, new TestComparator(), Criterion.GREATER); assertTrue(p, Integer.valueOf(value.intValue() - 1)); assertFalse(p, Integer.valueOf(value.intValue())); assertFalse(p, Integer.valueOf(value.intValue() + 1)); } @Test public void compareLess() { final Integer value = Integer.valueOf(10); final Predicate p = comparatorPredicate(value, new TestComparator(), Criterion.LESS); assertFalse(p, Integer.valueOf(value.intValue() - 1)); assertFalse(p, Integer.valueOf(value.intValue())); assertTrue(p, Integer.valueOf(value.intValue() + 1)); } @Test public void compareGreaterOrEqual() { final Integer value = Integer.valueOf(10); final Predicate p = comparatorPredicate(value, new TestComparator(), Criterion.GREATER_OR_EQUAL); assertTrue(p, Integer.valueOf(value.intValue() - 1)); assertTrue(p, Integer.valueOf(value.intValue())); assertFalse(p, Integer.valueOf(value.intValue() + 1)); } @Test public void compareLessOrEqual() { final Integer value = Integer.valueOf(10); final Predicate p = comparatorPredicate(value, new TestComparator(), Criterion.LESS_OR_EQUAL); assertFalse(p, Integer.valueOf(value.intValue() - 1)); assertTrue(p, Integer.valueOf(value.intValue())); assertTrue(p, Integer.valueOf(value.intValue() + 1)); } @Override protected Predicate generatePredicate() { return comparatorPredicate(Integer.valueOf(10), new TestComparator()); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/TrieUtilsTest.java100664 3724 12243235516 30426 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import junit.framework.Test; import org.apache.commons.collections4.trie.PatriciaTrie; import org.apache.commons.collections4.trie.UnmodifiableTrie; /** * Tests for TrieUtils factory methods. * * @version $Id: TrieUtilsTest.java 1540763 2013-11-11 16:30:14Z tn $ */ public class TrieUtilsTest extends BulkTest { public TrieUtilsTest(final String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(TrieUtilsTest.class); } //---------------------------------------------------------------------- public void testUnmodifiableTrie() { Trie trie = TrieUtils.unmodifiableTrie(new PatriciaTrie()); assertTrue("Returned object should be an UnmodifiableTrie.", trie instanceof UnmodifiableTrie); try { TrieUtils.unmodifiableTrie(null); fail("Expecting IllegalArgumentException for null trie."); } catch (final IllegalArgumentException ex) { // expected } assertSame("UnmodifiableTrie shall not be decorated", trie, TrieUtils.unmodifiableTrie(trie)); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/ListUtilsTest.java100664 36677 12243235516 30473 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import junit.framework.Test; import org.apache.commons.collections4.functors.EqualPredicate; import org.apache.commons.collections4.list.PredicatedList; /** * Tests for ListUtils. * * @version $Id: ListUtilsTest.java 1540860 2013-11-11 21:58:27Z ebourg $ */ public class ListUtilsTest 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 ListUtilsTest(final String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(ListUtilsTest.class); } @Override public void setUp() { fullArray = new String[]{a, b, c, d, e}; fullList = new ArrayList(Arrays.asList(fullArray)); } public void testNothing() { } /** * Tests intersecting a non-empty list with an empty list. */ public void testIntersectNonEmptyWithEmptyList() { final List empty = Collections.emptyList(); assertTrue("result not empty", ListUtils.intersection(empty, fullList).isEmpty()); } /** * Tests intersecting a non-empty list with an empty list. */ public void testIntersectEmptyWithEmptyList() { final List empty = Collections.EMPTY_LIST; assertTrue("result not empty", ListUtils.intersection(empty, empty).isEmpty()); } /** * Tests intersecting a non-empty list with an subset of iteself. */ public void testIntersectNonEmptySubset() { // create a copy final List other = new ArrayList(fullList); // remove a few items assertNotNull(other.remove(0)); assertNotNull(other.remove(1)); // make sure the intersection is equal to the copy assertEquals(other, ListUtils.intersection(fullList, other)); } /** * Tests intersecting a non-empty list with an subset of iteself. */ public void testIntersectListWithNoOverlapAndDifferentTypes() { @SuppressWarnings("boxing") final List other = Arrays.asList(1, 23); assertTrue(ListUtils.intersection(fullList, other).isEmpty()); } /** * Tests intersecting a non-empty list with iteself. */ public void testIntersectListWithSelf() { assertEquals(fullList, ListUtils.intersection(fullList, fullList)); } /** * Tests intersecting two lists in different orders. */ public void testIntersectionOrderInsensitivity() { final List one = new ArrayList(); final List two = new ArrayList(); one.add("a"); one.add("b"); two.add("a"); two.add("a"); two.add("b"); two.add("b"); assertEquals(ListUtils.intersection(one,two),ListUtils.intersection(two, one)); } public void testPredicatedList() { final Predicate predicate = new Predicate() { public boolean evaluate(final Object o) { return o instanceof String; } }; List list = ListUtils.predicatedList(new ArrayList(), predicate); assertTrue("returned object should be a PredicatedList", list instanceof PredicatedList); try { ListUtils.predicatedList(new ArrayList(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (final IllegalArgumentException ex) { // expected } try { ListUtils.predicatedList(null, predicate); fail("Expecting IllegalArgumentException for null list."); } catch (final IllegalArgumentException ex) { // expected } } public void testLazyList() { final List list = ListUtils.lazyList(new ArrayList(), new Factory() { private int index; public Integer create() { index++; return Integer.valueOf(index); } }); assertNotNull(list.get(5)); assertEquals(6, list.size()); assertNotNull(list.get(5)); assertEquals(6, list.size()); } public void testEmptyIfNull() { assertTrue(ListUtils.emptyIfNull(null).isEmpty()); final List list = new ArrayList(); assertSame(list, ListUtils.emptyIfNull(list)); } public void testDefaultIfNull() { assertTrue(ListUtils.defaultIfNull(null, Collections.emptyList()).isEmpty()); final List list = new ArrayList(); assertSame(list, ListUtils.defaultIfNull(list, Collections.emptyList())); } public void testEquals() { final Collection data = Arrays.asList("a", "b", "c"); final List a = new ArrayList( data ); final 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() { final Collection data = Arrays.asList("a", "b", "c"); final List a = new ArrayList(data); final 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() { final List sub = new ArrayList(); sub.add(a); sub.add(b); sub.add(x); final 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 { ListUtils.retainAll(null, null); fail("expecting NullPointerException"); } catch(final NullPointerException npe){} // this is what we want } public void testRemoveAll() { final List sub = new ArrayList(); sub.add(a); sub.add(b); sub.add(x); final List remainder = ListUtils.removeAll(fullList, sub); assertTrue(remainder.size() == 3); fullList.removeAll(sub); assertTrue(remainder.equals(fullList)); try { ListUtils.removeAll(null, null); fail("expecting NullPointerException"); } catch(final NullPointerException npe) {} // this is what we want } public void testSubtract() { final List list = new ArrayList(); list.add(a); list.add(b); list.add(a); list.add(x); final List sub = new ArrayList(); sub.add(a); final List result = ListUtils.subtract(list, sub); assertTrue(result.size() == 3); final List expected = new ArrayList(); expected.add(b); expected.add(a); expected.add(x); assertEquals(expected, result); try { ListUtils.subtract(list, null); fail("expecting NullPointerException"); } catch(final NullPointerException npe) {} // this is what we want } public void testSubtractNullElement() { final List list = new ArrayList(); list.add(a); list.add(null); list.add(null); list.add(x); final List sub = new ArrayList(); sub.add(null); final List result = ListUtils.subtract(list, sub); assertTrue(result.size() == 3); final List expected = new ArrayList(); expected.add(a); expected.add(null); expected.add(x); assertEquals(expected, result); } /** * Tests the indexOf method in ListUtils class.. */ public void testIndexOf() { Predicate testPredicate = EqualPredicate.equalPredicate("d"); int index = ListUtils.indexOf(fullList, testPredicate); assertEquals(d, fullList.get(index)); testPredicate = EqualPredicate.equalPredicate("de"); index = ListUtils.indexOf(fullList, testPredicate); assertEquals(index, -1); assertEquals(ListUtils.indexOf(null,testPredicate), -1); assertEquals(ListUtils.indexOf(fullList, null), -1); } @SuppressWarnings("boxing") // OK in test code public void testLongestCommonSubsequence() { try { ListUtils.longestCommonSubsequence((List) null, null); fail("failed to check for null argument"); } catch (final IllegalArgumentException e) {} try { ListUtils.longestCommonSubsequence(Arrays.asList('A'), null); fail("failed to check for null argument"); } catch (final IllegalArgumentException e) {} try { ListUtils.longestCommonSubsequence(null, Arrays.asList('A')); fail("failed to check for null argument"); } catch (final IllegalArgumentException e) {} @SuppressWarnings("unchecked") List lcs = ListUtils.longestCommonSubsequence(Collections.EMPTY_LIST, Collections.EMPTY_LIST); assertEquals(0, lcs.size()); List list1 = Arrays.asList('B', 'A', 'N', 'A', 'N', 'A'); List list2 = Arrays.asList('A', 'N', 'A', 'N', 'A', 'S'); lcs = ListUtils.longestCommonSubsequence(list1, list2); List expected = Arrays.asList('A', 'N', 'A', 'N', 'A'); assertEquals(expected, lcs); List list3 = Arrays.asList('A', 'T', 'A', 'N', 'A'); lcs = ListUtils.longestCommonSubsequence(list1, list3); expected = Arrays.asList('A', 'A', 'N', 'A'); assertEquals(expected, lcs); List listZorro = Arrays.asList('Z', 'O', 'R', 'R', 'O'); lcs = ListUtils.longestCommonSubsequence(list1, listZorro); assertTrue(lcs.isEmpty()); } public void testLongestCommonSubsequenceWithString() { try { ListUtils.longestCommonSubsequence((String) null, null); fail("failed to check for null argument"); } catch (final IllegalArgumentException e) {} try { ListUtils.longestCommonSubsequence("A", null); fail("failed to check for null argument"); } catch (final IllegalArgumentException e) {} try { ListUtils.longestCommonSubsequence(null, "A"); fail("failed to check for null argument"); } catch (final IllegalArgumentException e) {} String lcs = ListUtils.longestCommonSubsequence("", ""); assertEquals(0, lcs.length()); String banana = "BANANA"; String ananas = "ANANAS"; lcs = ListUtils.longestCommonSubsequence(banana, ananas); assertEquals("ANANA", lcs); String atana = "ATANA"; lcs = ListUtils.longestCommonSubsequence(banana, atana); assertEquals("AANA", lcs); String zorro = "ZORRO"; lcs = ListUtils.longestCommonSubsequence(banana, zorro); assertEquals(0, lcs.length()); } @SuppressWarnings("boxing") // OK in test code public void testPartition() { final List strings = new ArrayList(); for (int i = 0; i <= 6; i++) { strings.add(i); } final List> partition = ListUtils.partition(strings, 3); assertNotNull(partition); assertEquals(3, partition.size()); assertEquals(1, partition.get(2).size()); try { ListUtils.partition(null, 3); fail("failed to check for null argument"); } catch (final IllegalArgumentException e) {} try { ListUtils.partition(strings, 0); fail("failed to check for size argument"); } catch (final IllegalArgumentException e) {} try { ListUtils.partition(strings, -10); fail("failed to check for size argument"); } catch (final IllegalArgumentException e) {} } private static Predicate EQUALS_TWO = new Predicate() { public boolean evaluate(final Number input) { return input.intValue() == 2; } }; @SuppressWarnings("boxing") // OK in test code public void testSelect() { final List list = new ArrayList(); list.add(1); list.add(2); list.add(3); list.add(4); // Ensure that the collection is the input type or a super type final List output1 = ListUtils.select(list, EQUALS_TWO); final List output2 = ListUtils.select(list, EQUALS_TWO); final HashSet output3 = CollectionUtils.select(list, EQUALS_TWO, new HashSet()); assertTrue(CollectionUtils.isEqualCollection(output1, output3)); assertEquals(4, list.size()); assertEquals(1, output1.size()); assertEquals(2, output2.iterator().next()); } @SuppressWarnings("boxing") // OK in test code public void testSelectRejected() { final List list = new ArrayList(); list.add(1L); list.add(2L); list.add(3L); list.add(4L); final List output1 = ListUtils.selectRejected(list, EQUALS_TWO); final List output2 = ListUtils.selectRejected(list, EQUALS_TWO); final HashSet output3 = CollectionUtils.selectRejected(list, EQUALS_TWO, new HashSet()); assertTrue(CollectionUtils.isEqualCollection(output1, output2)); assertTrue(CollectionUtils.isEqualCollection(output1, output3)); assertEquals(4, list.size()); assertEquals(3, output1.size()); assertTrue(output1.contains(1L)); assertTrue(output1.contains(3L)); assertTrue(output1.contains(4L)); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/CollectionUtilsTest.java100664 207625 12243235516 31664 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import static org.apache.commons.collections4.functors.EqualPredicate.equalPredicate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.util.*; import org.apache.commons.collections4.queue.CircularFifoQueue; import org.apache.commons.collections4.bag.HashBag; import org.apache.commons.collections4.collection.PredicatedCollection; import org.apache.commons.collections4.collection.SynchronizedCollection; import org.apache.commons.collections4.collection.TransformedCollection; import org.apache.commons.collections4.collection.UnmodifiableCollection; import org.apache.commons.collections4.functors.DefaultEquator; import org.junit.Before; import org.junit.Test; /** * Tests for CollectionUtils. * * @version $Id: CollectionUtilsTest.java 1542020 2013-11-14 19:00:59Z tn $ */ @SuppressWarnings("boxing") public class CollectionUtilsTest extends MockTestCase { /** * Collection of {@link Integer}s */ private List collectionA = null; /** * Collection of {@link Long}s */ private List collectionB = null; /** * Collection of {@link Integer}s that are equivalent to the Longs in * collectionB. */ private Collection collectionC = null; /** * Sorted Collection of {@link Integer}s */ private Collection collectionD = null; /** * Sorted Collection of {@link Integer}s */ private Collection collectionE = null; /** * Collection of {@link Integer}s, bound as {@link Number}s */ private Collection collectionA2 = null; /** * Collection of {@link Long}s, bound as {@link Number}s */ private Collection collectionB2 = null; /** * Collection of {@link Integer}s (cast as {@link Number}s) that are * equivalent to the Longs in collectionB. */ private Collection collectionC2 = null; private Iterable iterableA = null; private Iterable iterableB = null; private Iterable iterableC = null; private Iterable iterableA2 = null; private Iterable iterableB2 = null; private Collection emptyCollection = new ArrayList(1); @Before public void setUp() { collectionA = new ArrayList(); collectionA.add(1); collectionA.add(2); collectionA.add(2); collectionA.add(3); collectionA.add(3); collectionA.add(3); collectionA.add(4); collectionA.add(4); collectionA.add(4); collectionA.add(4); collectionB = new LinkedList(); collectionB.add(5L); collectionB.add(4L); collectionB.add(4L); collectionB.add(3L); collectionB.add(3L); collectionB.add(3L); collectionB.add(2L); collectionB.add(2L); collectionB.add(2L); collectionB.add(2L); collectionC = new ArrayList(); for (final Long l : collectionB) { collectionC.add(l.intValue()); } iterableA = collectionA; iterableB = collectionB; iterableC = collectionC; collectionA2 = new ArrayList(collectionA); collectionB2 = new LinkedList(collectionB); collectionC2 = new LinkedList(collectionC); iterableA2 = collectionA2; iterableB2 = collectionB2; collectionD = new ArrayList(); collectionD.add(1); collectionD.add(3); collectionD.add(3); collectionD.add(3); collectionD.add(5); collectionD.add(7); collectionD.add(7); collectionD.add(10); collectionE = new ArrayList(); collectionE.add(2); collectionE.add(4); collectionE.add(4); collectionE.add(5); collectionE.add(6); collectionE.add(6); collectionE.add(9); } @Test public void getCardinalityMap() { final Map freqA = CollectionUtils.getCardinalityMap(iterableA); assertEquals(1, (int) freqA.get(1)); assertEquals(2, (int) freqA.get(2)); assertEquals(3, (int) freqA.get(3)); assertEquals(4, (int) freqA.get(4)); assertNull(freqA.get(5)); final Map freqB = CollectionUtils.getCardinalityMap(iterableB); assertNull(freqB.get(1L)); assertEquals(4, (int) freqB.get(2L)); assertEquals(3, (int) freqB.get(3L)); assertEquals(2, (int) freqB.get(4L)); assertEquals(1, (int) freqB.get(5L)); } @Test public void cardinality() { assertEquals(1, CollectionUtils.cardinality(1, iterableA)); assertEquals(2, CollectionUtils.cardinality(2, iterableA)); assertEquals(3, CollectionUtils.cardinality(3, iterableA)); assertEquals(4, CollectionUtils.cardinality(4, iterableA)); assertEquals(0, CollectionUtils.cardinality(5, iterableA)); assertEquals(0, CollectionUtils.cardinality(1L, iterableB)); assertEquals(4, CollectionUtils.cardinality(2L, iterableB)); assertEquals(3, CollectionUtils.cardinality(3L, iterableB)); assertEquals(2, CollectionUtils.cardinality(4L, iterableB)); assertEquals(1, CollectionUtils.cardinality(5L, iterableB)); // Ensure that generic bounds accept valid parameters, but return // expected results // e.g. no longs in the "int" Iterable, and vice versa. assertEquals(0, CollectionUtils.cardinality(2L, iterableA2)); assertEquals(0, CollectionUtils.cardinality(2, iterableB2)); final 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)); final 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)); } @Test public void cardinalityOfNull() { final List list = new ArrayList(); assertEquals(0, CollectionUtils.cardinality(null, list)); { final Map freq = CollectionUtils.getCardinalityMap(list); assertNull(freq.get(null)); } list.add("A"); assertEquals(0, CollectionUtils.cardinality(null, list)); { final Map freq = CollectionUtils.getCardinalityMap(list); assertNull(freq.get(null)); } list.add(null); assertEquals(1, CollectionUtils.cardinality(null, list)); { final Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(Integer.valueOf(1), freq.get(null)); } list.add("B"); assertEquals(1, CollectionUtils.cardinality(null, list)); { final Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(Integer.valueOf(1), freq.get(null)); } list.add(null); assertEquals(2, CollectionUtils.cardinality(null, list)); { final Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(Integer.valueOf(2), freq.get(null)); } list.add("B"); assertEquals(2, CollectionUtils.cardinality(null, list)); { final Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(Integer.valueOf(2), freq.get(null)); } list.add(null); assertEquals(3, CollectionUtils.cardinality(null, list)); { final Map freq = CollectionUtils.getCardinalityMap(list); assertEquals(Integer.valueOf(3), freq.get(null)); } } @Test public void containsAll() { final Collection empty = new ArrayList(0); final Collection one = new ArrayList(1); one.add("1"); final Collection two = new ArrayList(1); two.add("2"); final Collection three = new ArrayList(1); three.add("3"); final Collection odds = new ArrayList(2); odds.add("1"); odds.add("3"); final Collection multiples = new ArrayList(3); multiples.add("1"); multiples.add("3"); multiples.add("1"); assertTrue("containsAll({1},{1,3}) should return false.", !CollectionUtils.containsAll(one, odds)); assertTrue("containsAll({1,3},{1}) should return true.", CollectionUtils.containsAll(odds, one)); assertTrue("containsAll({3},{1,3}) should return false.", !CollectionUtils.containsAll(three, odds)); assertTrue("containsAll({1,3},{3}) should return true.", CollectionUtils.containsAll(odds, three)); assertTrue("containsAll({2},{2}) should return true.", CollectionUtils.containsAll(two, two)); assertTrue("containsAll({1,3},{1,3}) should return true.", CollectionUtils.containsAll(odds, odds)); assertTrue("containsAll({2},{1,3}) should return false.", !CollectionUtils.containsAll(two, odds)); assertTrue("containsAll({1,3},{2}) should return false.", !CollectionUtils.containsAll(odds, two)); assertTrue("containsAll({1},{3}) should return false.", !CollectionUtils.containsAll(one, three)); assertTrue("containsAll({3},{1}) should return false.", !CollectionUtils.containsAll(three, one)); assertTrue("containsAll({1,3},{}) should return true.", CollectionUtils.containsAll(odds, empty)); assertTrue("containsAll({},{1,3}) should return false.", !CollectionUtils.containsAll(empty, odds)); assertTrue("containsAll({},{}) should return true.", CollectionUtils.containsAll(empty, empty)); assertTrue("containsAll({1,3},{1,3,1}) should return true.", CollectionUtils.containsAll(odds, multiples)); assertTrue("containsAll({1,3,1},{1,3,1}) should return true.", CollectionUtils.containsAll(odds, odds)); } @Test public void containsAny() { final Collection empty = new ArrayList(0); final Collection one = new ArrayList(1); one.add("1"); final Collection two = new ArrayList(1); two.add("2"); final Collection three = new ArrayList(1); three.add("3"); final 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)); } @Test public void union() { final Collection col = CollectionUtils.union(iterableA, iterableC); final Map freq = CollectionUtils.getCardinalityMap(col); assertEquals(Integer.valueOf(1), freq.get(1)); assertEquals(Integer.valueOf(4), freq.get(2)); assertEquals(Integer.valueOf(3), freq.get(3)); assertEquals(Integer.valueOf(4), freq.get(4)); assertEquals(Integer.valueOf(1), freq.get(5)); final Collection col2 = CollectionUtils.union(collectionC2, iterableA); final Map freq2 = CollectionUtils.getCardinalityMap(col2); assertEquals(Integer.valueOf(1), freq2.get(1)); assertEquals(Integer.valueOf(4), freq2.get(2)); assertEquals(Integer.valueOf(3), freq2.get(3)); assertEquals(Integer.valueOf(4), freq2.get(4)); assertEquals(Integer.valueOf(1), freq2.get(5)); } @Test public void intersection() { final Collection col = CollectionUtils.intersection(iterableA, iterableC); final Map freq = CollectionUtils.getCardinalityMap(col); assertNull(freq.get(1)); assertEquals(Integer.valueOf(2), freq.get(2)); assertEquals(Integer.valueOf(3), freq.get(3)); assertEquals(Integer.valueOf(2), freq.get(4)); assertNull(freq.get(5)); final Collection col2 = CollectionUtils.intersection(collectionC2, collectionA); final Map freq2 = CollectionUtils.getCardinalityMap(col2); assertNull(freq2.get(1)); assertEquals(Integer.valueOf(2), freq2.get(2)); assertEquals(Integer.valueOf(3), freq2.get(3)); assertEquals(Integer.valueOf(2), freq2.get(4)); assertNull(freq2.get(5)); } @Test public void disjunction() { final Collection col = CollectionUtils.disjunction(iterableA, iterableC); final Map freq = CollectionUtils.getCardinalityMap(col); assertEquals(Integer.valueOf(1), freq.get(1)); assertEquals(Integer.valueOf(2), freq.get(2)); assertNull(freq.get(3)); assertEquals(Integer.valueOf(2), freq.get(4)); assertEquals(Integer.valueOf(1), freq.get(5)); final Collection col2 = CollectionUtils.disjunction(collectionC2, collectionA); final Map freq2 = CollectionUtils.getCardinalityMap(col2); assertEquals(Integer.valueOf(1), freq2.get(1)); assertEquals(Integer.valueOf(2), freq2.get(2)); assertNull(freq2.get(3)); assertEquals(Integer.valueOf(2), freq2.get(4)); assertEquals(Integer.valueOf(1), freq2.get(5)); } @Test public void testDisjunctionAsUnionMinusIntersection() { final Collection dis = CollectionUtils.disjunction(collectionA, collectionC); final Collection un = CollectionUtils.union(collectionA, collectionC); final Collection inter = CollectionUtils.intersection(collectionA, collectionC); assertTrue(CollectionUtils.isEqualCollection(dis, CollectionUtils.subtract(un, inter))); } @Test public void testDisjunctionAsSymmetricDifference() { final Collection dis = CollectionUtils.disjunction(collectionA, collectionC); final Collection amb = CollectionUtils.subtract(collectionA, collectionC); final Collection bma = CollectionUtils.subtract(collectionC, collectionA); assertTrue(CollectionUtils.isEqualCollection(dis, CollectionUtils.union(amb, bma))); } @Test public void testSubtract() { final Collection col = CollectionUtils.subtract(iterableA, iterableC); final Map freq = CollectionUtils.getCardinalityMap(col); assertEquals(Integer.valueOf(1), freq.get(1)); assertNull(freq.get(2)); assertNull(freq.get(3)); assertEquals(Integer.valueOf(2), freq.get(4)); assertNull(freq.get(5)); final Collection col2 = CollectionUtils.subtract(collectionC2, collectionA); final Map freq2 = CollectionUtils.getCardinalityMap(col2); assertEquals(Integer.valueOf(1), freq2.get(5)); assertNull(freq2.get(4)); assertNull(freq2.get(3)); assertEquals(Integer.valueOf(2), freq2.get(2)); assertNull(freq2.get(1)); } @Test public void testSubtractWithPredicate() { // greater than 3 final Predicate predicate = new Predicate() { public boolean evaluate(final Number n) { return n.longValue() > 3L; } }; final Collection col = CollectionUtils.subtract(iterableA, collectionC, predicate); final Map freq2 = CollectionUtils.getCardinalityMap(col); assertEquals(Integer.valueOf(1), freq2.get(1)); assertEquals(Integer.valueOf(2), freq2.get(2)); assertEquals(Integer.valueOf(3), freq2.get(3)); assertEquals(Integer.valueOf(2), freq2.get(4)); assertNull(freq2.get(5)); } @Test public void testIsSubCollectionOfSelf() { assertTrue(CollectionUtils.isSubCollection(collectionA, collectionA)); assertTrue(CollectionUtils.isSubCollection(collectionB, collectionB)); } @Test public void testIsSubCollection() { assertTrue(!CollectionUtils.isSubCollection(collectionA, collectionC)); assertTrue(!CollectionUtils.isSubCollection(collectionC, collectionA)); } @Test public void testIsSubCollection2() { final Collection c = new ArrayList(); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add(1); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add(2); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add(2); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add(3); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add(3); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add(3); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add(4); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add(4); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add(4); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(!CollectionUtils.isSubCollection(collectionA, c)); c.add(4); assertTrue(CollectionUtils.isSubCollection(c, collectionA)); assertTrue(CollectionUtils.isSubCollection(collectionA, c)); c.add(5); assertTrue(!CollectionUtils.isSubCollection(c, collectionA)); assertTrue(CollectionUtils.isSubCollection(collectionA, c)); } @Test public void testIsEqualCollectionToSelf() { assertTrue(CollectionUtils.isEqualCollection(collectionA, collectionA)); assertTrue(CollectionUtils.isEqualCollection(collectionB, collectionB)); } @Test public void testIsEqualCollection() { assertTrue(!CollectionUtils.isEqualCollection(collectionA, collectionC)); assertTrue(!CollectionUtils.isEqualCollection(collectionC, collectionA)); } @Test public void testIsEqualCollectionReturnsFalse() { final List b = new ArrayList(collectionA); // remove an extra '2', and add a 5. This will increase the size of the cardinality b.remove(1); b.add(5); assertFalse(CollectionUtils.isEqualCollection(collectionA, b)); assertFalse(CollectionUtils.isEqualCollection(b, collectionA)); } @Test public void testIsEqualCollection2() { final Collection a = new ArrayList(); final 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)); } @Test public void testIsEqualCollectionEquator() { final Collection collB = CollectionUtils.collect(collectionB, TRANSFORM_TO_INTEGER); // odd / even equator final Equator e = new Equator() { public boolean equate(final Integer o1, final Integer o2) { if (o1.intValue() % 2 == 0 ^ o2.intValue() % 2 == 0) { return false; } else { return true; } } public int hash(final Integer o) { return o.intValue() % 2 == 0 ? Integer.valueOf(0).hashCode() : Integer.valueOf(1).hashCode(); } }; assertTrue(CollectionUtils.isEqualCollection(collectionA, collectionA, e)); assertTrue(CollectionUtils.isEqualCollection(collectionA, collB, e)); assertTrue(CollectionUtils.isEqualCollection(collB, collectionA, e)); final Equator defaultEquator = DefaultEquator.defaultEquator(); assertFalse(CollectionUtils.isEqualCollection(collectionA, collectionB, defaultEquator)); assertFalse(CollectionUtils.isEqualCollection(collectionA, collB, defaultEquator)); } @Test(expected=IllegalArgumentException.class) public void testIsEqualCollectionNullEquator() { CollectionUtils.isEqualCollection(collectionA, collectionA, null); } @Test public void testIsProperSubCollection() { final Collection a = new ArrayList(); final 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, collectionC), collectionA)); assertTrue(CollectionUtils.isProperSubCollection(CollectionUtils.subtract(a, b), a)); assertTrue(!CollectionUtils.isProperSubCollection(a, CollectionUtils.subtract(a, b))); } @Test public void find() { Predicate testPredicate = equalPredicate((Number) 4); Integer test = CollectionUtils.find(collectionA, testPredicate); assertTrue(test.equals(4)); testPredicate = equalPredicate((Number) 45); test = CollectionUtils.find(collectionA, testPredicate); assertTrue(test == null); assertNull(CollectionUtils.find(null,testPredicate)); assertNull(CollectionUtils.find(collectionA, null)); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void forAllDoCollection() { final Closure> testClosure = ClosureUtils.invokerClosure("clear"); final Collection> col = new ArrayList>(); col.add(collectionA); col.add(collectionB); Closure> resultClosure = CollectionUtils.forAllDo(col, testClosure); assertSame(testClosure, resultClosure); assertTrue(collectionA.isEmpty() && collectionB.isEmpty()); // fix for various java 1.6 versions: keep the cast resultClosure = CollectionUtils.forAllDo(col, (Closure>) null); assertNull(resultClosure); assertTrue(collectionA.isEmpty() && collectionB.isEmpty()); resultClosure = CollectionUtils.forAllDo((Collection) null, testClosure); col.add(null); // null should be OK CollectionUtils.forAllDo(col, testClosure); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void forAllDoIterator() { final Closure> testClosure = ClosureUtils.invokerClosure("clear"); final Collection> col = new ArrayList>(); col.add(collectionA); col.add(collectionB); Closure> resultClosure = CollectionUtils.forAllDo(col.iterator(), testClosure); assertSame(testClosure, resultClosure); assertTrue(collectionA.isEmpty() && collectionB.isEmpty()); // fix for various java 1.6 versions: keep the cast resultClosure = CollectionUtils.forAllDo(col.iterator(), (Closure>) null); assertNull(resultClosure); assertTrue(collectionA.isEmpty() && collectionB.isEmpty()); resultClosure = CollectionUtils.forAllDo((Iterator) null, testClosure); col.add(null); // null should be OK CollectionUtils.forAllDo(col.iterator(), testClosure); } @Test(expected = FunctorException.class) public void forAllDoFailure() { final Closure testClosure = ClosureUtils.invokerClosure("clear"); final Collection col = new ArrayList(); col.add("x"); CollectionUtils.forAllDo(col, testClosure); } @Test public void forAllButLastDoCollection() { final Closure> testClosure = ClosureUtils.invokerClosure("clear"); final Collection> col = new ArrayList>(); col.add(collectionA); col.add(collectionB); List lastElement = CollectionUtils.forAllButLastDo(col, testClosure); assertSame(lastElement, collectionB); assertTrue(collectionA.isEmpty() && !collectionB.isEmpty()); col.clear(); col.add(collectionB); lastElement = CollectionUtils.forAllButLastDo(col, testClosure); assertSame(lastElement, collectionB); assertTrue(!collectionB.isEmpty() ); col.clear(); lastElement = CollectionUtils.forAllButLastDo(col, testClosure); assertNull(lastElement); Collection strings = Arrays.asList("a", "b", "c"); final StringBuffer result = new StringBuffer(); result.append(CollectionUtils.forAllButLastDo(strings, new Closure() { public void execute(String input) { result.append(input+";"); } })); assertEquals("a;b;c", result.toString()); Collection oneString = Arrays.asList("a"); final StringBuffer resultOne = new StringBuffer(); resultOne.append(CollectionUtils.forAllButLastDo(oneString, new Closure() { public void execute(String input) { resultOne.append(input+";"); } })); assertEquals("a", resultOne.toString()); assertNull(CollectionUtils.forAllButLastDo(strings, (Closure) null)); // do not remove cast assertNull(CollectionUtils.forAllButLastDo((Collection) null, (Closure) null)); // do not remove cast } @Test public void forAllButLastDoIterator() { final Closure> testClosure = ClosureUtils.invokerClosure("clear"); final Collection> col = new ArrayList>(); col.add(collectionA); col.add(collectionB); List lastElement = CollectionUtils.forAllButLastDo(col.iterator(), testClosure); assertSame(lastElement, collectionB); assertTrue(collectionA.isEmpty() && !collectionB.isEmpty()); assertNull(CollectionUtils.forAllButLastDo(col.iterator(), (Closure>) null)); assertNull(CollectionUtils.forAllButLastDo((Iterator) null, (Closure) null)); // do not remove cast } @Test public void getFromMap() { // Unordered map, entries exist final Map expected = new HashMap(); expected.put("zeroKey", "zero"); expected.put("oneKey", "one"); final Map found = new HashMap(); Map.Entry entry = CollectionUtils.get(expected, 0); found.put(entry.getKey(), entry.getValue()); 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 (final IndexOutOfBoundsException e) { // expected } try { CollectionUtils.get(expected, -2); fail("Expecting IndexOutOfBoundsException."); } catch (final IndexOutOfBoundsException e) { // expected } // Sorted map, entries exist, should respect order final SortedMap map = new TreeMap(); map.put("zeroKey", "zero"); map.put("oneKey", "one"); Map.Entry test = CollectionUtils.get(map, 1); assertEquals("zeroKey", test.getKey()); assertEquals("zero", test.getValue()); test = CollectionUtils.get(map, 0); assertEquals("oneKey", test.getKey()); assertEquals("one", test.getValue()); } /** * Tests that {@link List}s are handled correctly - e.g. using * {@link List#get(int)}. */ @Test(expected=IndexOutOfBoundsException.class) public void getFromList() throws Exception { // List, entry exists final List list = createMock(List.class); expect(list.get(0)).andReturn("zero"); expect(list.get(1)).andReturn("one"); replay(); final String string = CollectionUtils.get(list, 0); assertEquals("zero", string); assertEquals("one", CollectionUtils.get(list, 1)); // list, non-existent entry -- IndexOutOfBoundsException CollectionUtils.get(new ArrayList(), 2); } @Test public void getFromIterator() throws Exception { // Iterator, entry exists Iterator iterator = iterableA.iterator(); assertEquals(1, (int) CollectionUtils.get(iterator, 0)); iterator = iterableA.iterator(); assertEquals(2, (int) CollectionUtils.get(iterator, 1)); // Iterator, non-existent entry try { CollectionUtils.get(iterator, 10); fail("Expecting IndexOutOfBoundsException."); } catch (final IndexOutOfBoundsException e) { // expected } assertTrue(!iterator.hasNext()); } @Test public void getFromEnumeration() throws Exception { // Enumeration, entry exists final 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 (final IndexOutOfBoundsException e) { // expected } assertTrue(!en.hasMoreElements()); } @Test(expected = IndexOutOfBoundsException.class) public void getFromIterable() throws Exception { // Collection, entry exists final Bag bag = new HashBag(); bag.add("element", 1); assertEquals("element", CollectionUtils.get(bag, 0)); // Collection, non-existent entry CollectionUtils.get(bag, 1); } @Test(expected = IndexOutOfBoundsException.class) public void getFromObjectArray() throws Exception { // Object array, entry exists final 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 CollectionUtils.get(objArray, 2); } @Test(expected = IndexOutOfBoundsException.class) public void getFromPrimativeArray() throws Exception { // Primitive array, entry exists final int[] array = new int[2]; array[0] = 10; array[1] = 20; assertEquals(10, CollectionUtils.get(array, 0)); assertEquals(20, CollectionUtils.get(array, 1)); // Object array, non-existent entry -- // ArrayIndexOutOfBoundsException CollectionUtils.get(array, 2); } @Test(expected=IllegalArgumentException.class) public void getFromObject() throws Exception { // Invalid object final Object obj = new Object(); CollectionUtils.get(obj, 0); } // ----------------------------------------------------------------------- @Test public void testSize_List() { List list = null; assertEquals(0, CollectionUtils.size(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)); } @Test public void testSize_Map() { final 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)); } @Test public void testSize_Array() { final Object[] objectArray = new Object[0]; assertEquals(0, CollectionUtils.size(objectArray)); final String[] stringArray = new String[3]; assertEquals(3, CollectionUtils.size(stringArray)); stringArray[0] = "a"; stringArray[1] = "b"; stringArray[2] = "c"; assertEquals(3, CollectionUtils.size(stringArray)); } @Test public void testSize_PrimitiveArray() { final int[] intArray = new int[0]; assertEquals(0, CollectionUtils.size(intArray)); final 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)); } @Test public void testSize_Enumeration() { final 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())); } @Test public void testSize_Iterator() { final 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())); } @Test(expected=IllegalArgumentException.class) public void testSize_Other() { CollectionUtils.size("not a list"); } // ----------------------------------------------------------------------- @Test public void testSizeIsEmpty_Null() { assertEquals(true, CollectionUtils.sizeIsEmpty(null)); } @Test public void testSizeIsEmpty_List() { final List list = new ArrayList(); assertEquals(true, CollectionUtils.sizeIsEmpty(list)); list.add("a"); assertEquals(false, CollectionUtils.sizeIsEmpty(list)); } @Test public void testSizeIsEmpty_Map() { final Map map = new HashMap(); assertEquals(true, CollectionUtils.sizeIsEmpty(map)); map.put("1", "a"); assertEquals(false, CollectionUtils.sizeIsEmpty(map)); } @Test public void testSizeIsEmpty_Array() { final Object[] objectArray = new Object[0]; assertEquals(true, CollectionUtils.sizeIsEmpty(objectArray)); final String[] stringArray = new String[3]; assertEquals(false, CollectionUtils.sizeIsEmpty(stringArray)); stringArray[0] = "a"; stringArray[1] = "b"; stringArray[2] = "c"; assertEquals(false, CollectionUtils.sizeIsEmpty(stringArray)); } @Test public void testSizeIsEmpty_PrimitiveArray() { final int[] intArray = new int[0]; assertEquals(true, CollectionUtils.sizeIsEmpty(intArray)); final 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)); } @Test public void testSizeIsEmpty_Enumeration() { final Vector list = new Vector(); assertEquals(true, CollectionUtils.sizeIsEmpty(list.elements())); list.add("a"); assertEquals(false, CollectionUtils.sizeIsEmpty(list.elements())); final Enumeration en = list.elements(); en.nextElement(); assertEquals(true, CollectionUtils.sizeIsEmpty(en)); } @Test public void testSizeIsEmpty_Iterator() { final List list = new ArrayList(); assertEquals(true, CollectionUtils.sizeIsEmpty(list.iterator())); list.add("a"); assertEquals(false, CollectionUtils.sizeIsEmpty(list.iterator())); final Iterator it = list.iterator(); it.next(); assertEquals(true, CollectionUtils.sizeIsEmpty(it)); } @Test public void testSizeIsEmpty_Other() { try { CollectionUtils.sizeIsEmpty("not a list"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { } } // ----------------------------------------------------------------------- @Test public void testIsEmptyWithEmptyCollection() { final Collection coll = new ArrayList(); assertEquals(true, CollectionUtils.isEmpty(coll)); } @Test public void testIsEmptyWithNonEmptyCollection() { final Collection coll = new ArrayList(); coll.add("item"); assertEquals(false, CollectionUtils.isEmpty(coll)); } @Test public void testIsEmptyWithNull() { final Collection coll = null; assertEquals(true, CollectionUtils.isEmpty(coll)); } @Test public void testIsNotEmptyWithEmptyCollection() { final Collection coll = new ArrayList(); assertEquals(false, CollectionUtils.isNotEmpty(coll)); } @Test public void testIsNotEmptyWithNonEmptyCollection() { final Collection coll = new ArrayList(); coll.add("item"); assertEquals(true, CollectionUtils.isNotEmpty(coll)); } @Test public void testIsNotEmptyWithNull() { final Collection coll = null; assertEquals(false, CollectionUtils.isNotEmpty(coll)); } // ----------------------------------------------------------------------- private static Predicate EQUALS_TWO = new Predicate() { public boolean evaluate(final Number input) { return input.intValue() == 2; } }; //Up to here @Test public void filter() { final List ints = new ArrayList(); ints.add(1); ints.add(2); ints.add(3); ints.add(3); final Iterable iterable = ints; assertTrue(CollectionUtils.filter(iterable, EQUALS_TWO)); assertEquals(1, ints.size()); assertEquals(2, (int) ints.get(0)); } @Test public void filterNullParameters() throws Exception { final List longs = Collections.nCopies(4, 10L); assertFalse(CollectionUtils.filter(longs, null)); assertEquals(4, longs.size()); assertFalse(CollectionUtils.filter(null, EQUALS_TWO)); assertEquals(4, longs.size()); assertFalse(CollectionUtils.filter(null, null)); assertEquals(4, longs.size()); } @Test public void filterInverse() { final List ints = new ArrayList(); ints.add(1); ints.add(2); ints.add(3); ints.add(3); final Iterable iterable = ints; assertTrue(CollectionUtils.filterInverse(iterable, EQUALS_TWO)); assertEquals(3, ints.size()); assertEquals(1, (int) ints.get(0)); assertEquals(3, (int) ints.get(1)); assertEquals(3, (int) ints.get(2)); } @Test public void filterInverseNullParameters() throws Exception { final List longs = Collections.nCopies(4, 10L); assertFalse(CollectionUtils.filterInverse(longs, null)); assertEquals(4, longs.size()); assertFalse(CollectionUtils.filterInverse(null, EQUALS_TWO)); assertEquals(4, longs.size()); assertFalse(CollectionUtils.filterInverse(null, null)); assertEquals(4, longs.size()); } @Test public void countMatches() { assertEquals(4, CollectionUtils.countMatches(iterableB, EQUALS_TWO)); assertEquals(0, CollectionUtils.countMatches(iterableA, null)); assertEquals(0, CollectionUtils.countMatches(null, EQUALS_TWO)); assertEquals(0, CollectionUtils.countMatches(null, null)); } @Test public void exists() { final List list = new ArrayList(); assertFalse(CollectionUtils.exists(null, null)); assertFalse(CollectionUtils.exists(list, null)); assertFalse(CollectionUtils.exists(null, EQUALS_TWO)); assertFalse(CollectionUtils.exists(list, EQUALS_TWO)); list.add(1); list.add(3); list.add(4); assertFalse(CollectionUtils.exists(list, EQUALS_TWO)); list.add(2); assertEquals(true, CollectionUtils.exists(list, EQUALS_TWO)); } @Test public void select() { final List list = new ArrayList(); list.add(1); list.add(2); list.add(3); list.add(4); // Ensure that the collection is the input type or a super type final Collection output1 = CollectionUtils.select(list, EQUALS_TWO); final Collection output2 = CollectionUtils.select(list, EQUALS_TWO); final HashSet output3 = CollectionUtils.select(list, EQUALS_TWO, new HashSet()); assertTrue(CollectionUtils.isEqualCollection(output1, output3)); assertEquals(4, list.size()); assertEquals(1, output1.size()); assertEquals(2, output2.iterator().next()); } @Test public void selectRejected() { final List list = new ArrayList(); list.add(1L); list.add(2L); list.add(3L); list.add(4L); final Collection output1 = CollectionUtils.selectRejected(list, EQUALS_TWO); final Collection output2 = CollectionUtils.selectRejected(list, EQUALS_TWO); final HashSet output3 = CollectionUtils.selectRejected(list, EQUALS_TWO, new HashSet()); assertTrue(CollectionUtils.isEqualCollection(output1, output2)); assertTrue(CollectionUtils.isEqualCollection(output1, output3)); assertEquals(4, list.size()); assertEquals(3, output1.size()); assertTrue(output1.contains(1L)); assertTrue(output1.contains(3L)); assertTrue(output1.contains(4L)); } @Test public void collect() { final Transformer transformer = TransformerUtils.constantTransformer(2L); Collection collection = CollectionUtils.collect(iterableA, transformer); assertTrue(collection.size() == collectionA.size()); assertCollectResult(collection); ArrayList list; list = CollectionUtils.collect(collectionA, transformer, new ArrayList()); assertTrue(list.size() == collectionA.size()); assertCollectResult(list); Iterator iterator = null; list = CollectionUtils.collect(iterator, transformer, new ArrayList()); iterator = iterableA.iterator(); list = CollectionUtils.collect(iterator, transformer, list); assertTrue(collection.size() == collectionA.size()); assertCollectResult(collection); iterator = collectionA.iterator(); collection = CollectionUtils.collect(iterator, transformer); assertTrue(collection.size() == collectionA.size()); assertTrue(collection.contains(2L) && !collection.contains(1)); collection = CollectionUtils.collect((Iterator) null, (Transformer) null); assertTrue(collection.size() == 0); final int size = collectionA.size(); collectionB = CollectionUtils.collect((Collection) null, transformer, collectionB); assertTrue(collectionA.size() == size && collectionA.contains(1)); CollectionUtils.collect(collectionB, null, collectionA); assertTrue(collectionA.size() == size && collectionA.contains(1)); } private void assertCollectResult(final Collection collection) { assertTrue(collectionA.contains(1) && !collectionA.contains(2L)); assertTrue(collection.contains(2L) && !collection.contains(1)); } Transformer TRANSFORM_TO_INTEGER = new Transformer() { public Integer transform(final Object input) { return Integer.valueOf(((Long)input).intValue()); } }; @Test public void transform1() { List list = new ArrayList(); list.add(1L); list.add(2L); list.add(3L); CollectionUtils.transform(list, TRANSFORM_TO_INTEGER); assertEquals(3, list.size()); assertEquals(1, list.get(0)); assertEquals(2, list.get(1)); assertEquals(3, list.get(2)); list = new ArrayList(); list.add(1L); list.add(2L); list.add(3L); 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()); } @Test public void transform2() { final Set set = new HashSet(); set.add(1L); set.add(2L); set.add(3L); CollectionUtils.transform(set, new Transformer() { public Integer transform(final Object input) { return 4; } }); assertEquals(1, set.size()); assertEquals(4, set.iterator().next()); } // ----------------------------------------------------------------------- @Test public void addIgnoreNull() { final Set set = new HashSet(); set.add("1"); set.add("2"); set.add("3"); assertFalse(CollectionUtils.addIgnoreNull(set, null)); assertEquals(3, set.size()); assertFalse(CollectionUtils.addIgnoreNull(set, "1")); assertEquals(3, set.size()); assertEquals(true, CollectionUtils.addIgnoreNull(set, "4")); assertEquals(4, set.size()); assertEquals(true, set.contains("4")); } // ----------------------------------------------------------------------- @Test public void predicatedCollection() { final Predicate predicate = PredicateUtils.instanceofPredicate(Integer.class); Collection collection = CollectionUtils.predicatedCollection(new ArrayList(), predicate); assertTrue("returned object should be a PredicatedCollection", collection instanceof PredicatedCollection); try { CollectionUtils.predicatedCollection(new ArrayList(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (final IllegalArgumentException ex) { // expected } try { CollectionUtils.predicatedCollection(null, predicate); fail("Expecting IllegalArgumentException for null collection."); } catch (final IllegalArgumentException ex) { // expected } } @Test public void isFull() { final Set set = new HashSet(); set.add("1"); set.add("2"); set.add("3"); try { CollectionUtils.isFull(null); fail(); } catch (final NullPointerException ex) { } assertFalse(CollectionUtils.isFull(set)); final CircularFifoQueue buf = new CircularFifoQueue(set); assertEquals(false, CollectionUtils.isFull(buf)); buf.remove("2"); assertFalse(CollectionUtils.isFull(buf)); buf.add("2"); assertEquals(false, CollectionUtils.isFull(buf)); } @Test public void isEmpty() { assertFalse(CollectionUtils.isNotEmpty(null)); assertTrue(CollectionUtils.isNotEmpty(collectionA)); } @Test public void maxSize() { final Set set = new HashSet(); set.add("1"); set.add("2"); set.add("3"); try { CollectionUtils.maxSize(null); fail(); } catch (final NullPointerException ex) { } assertEquals(-1, CollectionUtils.maxSize(set)); final Queue buf = new CircularFifoQueue(set); assertEquals(3, CollectionUtils.maxSize(buf)); buf.remove("2"); assertEquals(3, CollectionUtils.maxSize(buf)); buf.add("2"); assertEquals(3, CollectionUtils.maxSize(buf)); } @Test public void intersectionUsesMethodEquals() { // Let elta and eltb be objects... final Integer elta = new Integer(17); // Cannot use valueOf here final Integer 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... final Collection cola = new ArrayList(); final 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. final 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. final 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); } // ----------------------------------------------------------------------- //Up to here @Test public void testRetainAll() { final List base = new ArrayList(); base.add("A"); base.add("B"); base.add("C"); final List sub = new ArrayList(); sub.add("A"); sub.add("C"); sub.add("X"); final Collection result = CollectionUtils.retainAll(base, sub); assertEquals(2, result.size()); assertEquals(true, result.contains("A")); assertFalse(result.contains("B")); assertEquals(true, result.contains("C")); assertEquals(3, base.size()); assertEquals(true, base.contains("A")); assertEquals(true, base.contains("B")); assertEquals(true, base.contains("C")); assertEquals(3, sub.size()); assertEquals(true, sub.contains("A")); assertEquals(true, sub.contains("C")); assertEquals(true, sub.contains("X")); try { CollectionUtils.retainAll(null, null); fail("expecting NullPointerException"); } catch (final NullPointerException npe) { } // this is what we want } @Test public void testRemoveAll() { final List base = new ArrayList(); base.add("A"); base.add("B"); base.add("C"); final List sub = new ArrayList(); sub.add("A"); sub.add("C"); sub.add("X"); final Collection result = CollectionUtils.removeAll(base, sub); assertEquals(1, result.size()); assertFalse(result.contains("A")); assertEquals(true, result.contains("B")); assertFalse(result.contains("C")); assertEquals(3, base.size()); assertEquals(true, base.contains("A")); assertEquals(true, base.contains("B")); assertEquals(true, base.contains("C")); assertEquals(3, sub.size()); assertEquals(true, sub.contains("A")); assertEquals(true, sub.contains("C")); assertEquals(true, sub.contains("X")); try { CollectionUtils.removeAll(null, null); fail("expecting NullPointerException"); } catch (final NullPointerException npe) { } // this is what we want } // ----------------------------------------------------------------------- @Test public void testTransformedCollection() { final Transformer transformer = TransformerUtils.nopTransformer(); Collection collection = CollectionUtils.transformingCollection(new ArrayList(), transformer); assertTrue("returned object should be a TransformedCollection", collection instanceof TransformedCollection); try { CollectionUtils.transformingCollection(new ArrayList(), null); fail("Expecting IllegalArgumentException for null transformer."); } catch (final IllegalArgumentException ex) { // expected } try { CollectionUtils.transformingCollection(null, transformer); fail("Expecting IllegalArgumentException for null collection."); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testTransformedCollection_2() { final List list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); final Collection result = CollectionUtils.transformingCollection(list, TRANSFORM_TO_INTEGER); assertEquals(true, result.contains("1")); // untransformed assertEquals(true, result.contains("2")); // untransformed assertEquals(true, result.contains("3")); // untransformed } @Test public void testSynchronizedCollection() { Collection col = CollectionUtils.synchronizedCollection(new ArrayList()); assertTrue("Returned object should be a SynchronizedCollection.", col instanceof SynchronizedCollection); try { CollectionUtils.synchronizedCollection(null); fail("Expecting IllegalArgumentException for null collection."); } catch (final IllegalArgumentException ex) { // expected } } @Test public void testUnmodifiableCollection() { Collection col = CollectionUtils.unmodifiableCollection(new ArrayList()); assertTrue("Returned object should be a UnmodifiableCollection.", col instanceof UnmodifiableCollection); try { CollectionUtils.unmodifiableCollection(null); fail("Expecting IllegalArgumentException for null collection."); } catch (final IllegalArgumentException ex) { // expected } } @Test public void emptyCollection() throws Exception { final Collection coll = CollectionUtils.emptyCollection(); assertEquals(CollectionUtils.EMPTY_COLLECTION, coll); } @Test public void emptyIfNull() { assertTrue(CollectionUtils.emptyIfNull(null).isEmpty()); final Collection collection = new ArrayList(); assertSame(collection, CollectionUtils.emptyIfNull(collection)); } /** * This test ensures that {@link Iterable}s are supported by {@link CollectionUtils}. * Specifically, it uses mocks to ensure that if the passed in * {@link Iterable} is a {@link Collection} then * {@link Collection#addAll(Collection)} is called instead of iterating. */ @Test public void addAllForIterable() { final Collection inputCollection = createMock(Collection.class); final Iterable inputIterable = inputCollection; final Iterable iterable = createMock(Iterable.class); final Iterator iterator = createMock(Iterator.class); final Collection c = createMock(Collection.class); expect(iterable.iterator()).andReturn(iterator); next(iterator, 1L); next(iterator, 2L); next(iterator, 3L); expect(iterator.hasNext()).andReturn(false); expect(c.add(1L)).andReturn(true); expect(c.add(2L)).andReturn(true); expect(c.add(3L)).andReturn(true); // Check that the collection is added using // Collection.addAll(Collection) expect(c.addAll(inputCollection)).andReturn(true); // Ensure the method returns false if nothing is added expect(iterable.iterator()).andReturn(iterator); next(iterator, 1L); expect(iterator.hasNext()).andReturn(false); expect(c.add(1L)).andReturn(false); expect(c.addAll(inputCollection)).andReturn(false); replay(); assertTrue(CollectionUtils.addAll(c, iterable)); assertTrue(CollectionUtils.addAll(c, inputIterable)); assertFalse(CollectionUtils.addAll(c, iterable)); assertFalse(CollectionUtils.addAll(c, inputIterable)); verify(); } @Test public void addAllForEnumeration() { final Hashtable h = new Hashtable(); h.put(5, 5); final Enumeration enumeration = h.keys(); CollectionUtils.addAll(collectionA, enumeration); assertTrue(collectionA.contains(5)); } @Test public void addAllForElements() { CollectionUtils.addAll(collectionA, new Integer[]{5}); assertTrue(collectionA.contains(5)); } @Test(expected=IndexOutOfBoundsException.class) public void getNegative() { CollectionUtils.get((Object)collectionA, -3); } @Test(expected=IndexOutOfBoundsException.class) public void getPositiveOutOfBounds() { CollectionUtils.get((Object)collectionA.iterator(), 30); } @Test(expected=IllegalArgumentException.class) public void get1() { CollectionUtils.get((Object)null, 0); } @Test public void get() { assertEquals(2, CollectionUtils.get((Object)collectionA, 2)); assertEquals(2, CollectionUtils.get((Object)collectionA.iterator(), 2)); final Map map = CollectionUtils.getCardinalityMap(collectionA); assertEquals(map.entrySet().iterator().next(), CollectionUtils.get( (Object)map, 0)); } @Test public void reverse() { CollectionUtils.reverseArray(new Object[] {}); final Integer[] a = collectionA.toArray(new Integer[collectionA.size()]); CollectionUtils.reverseArray(a); // assume our implementation is correct if it returns the same order as the Java function Collections.reverse(collectionA); assertEquals(collectionA, Arrays.asList(a)); } @Test public void extractSingleton() { ArrayList coll = null; try { CollectionUtils.extractSingleton(coll); fail("expected IllegalArgumentException from extractSingleton(null)"); } catch (final IllegalArgumentException e) { } coll = new ArrayList(); try { CollectionUtils.extractSingleton(coll); fail("expected IllegalArgumentException from extractSingleton(empty)"); } catch (final IllegalArgumentException e) { } coll.add("foo"); assertEquals("foo", CollectionUtils.extractSingleton(coll)); coll.add("bar"); try { CollectionUtils.extractSingleton(coll); fail("expected IllegalArgumentException from extractSingleton(size == 2)"); } catch (final IllegalArgumentException e) { } } /** * Records the next object returned for a mock iterator */ private void next(final Iterator iterator, final T t) { expect(iterator.hasNext()).andReturn(true); expect(iterator.next()).andReturn(t); } @Test(expected=IllegalArgumentException.class) public void collateException1() { CollectionUtils.collate(collectionA, null); } @Test(expected=IllegalArgumentException.class) public void collateException2() { CollectionUtils.collate(collectionA, collectionC, null); } @Test public void testCollate() { List result = CollectionUtils.collate(emptyCollection, emptyCollection); assertEquals("Merge empty with empty", 0, result.size()); result = CollectionUtils.collate(collectionA, emptyCollection); assertEquals("Merge empty with non-empty", collectionA, result); List result1 = CollectionUtils.collate(collectionD, collectionE); List result2 = CollectionUtils.collate(collectionE, collectionD); assertEquals("Merge two lists 1", result1, result2); List combinedList = new ArrayList(); combinedList.addAll(collectionD); combinedList.addAll(collectionE); Collections.sort(combinedList); assertEquals("Merge two lists 2", combinedList, result2); final Comparator reverseComparator = ComparatorUtils.reversedComparator(ComparatorUtils.naturalComparator()); result = CollectionUtils.collate(emptyCollection, emptyCollection, reverseComparator); assertEquals("Comparator Merge empty with empty", 0, result.size()); Collections.reverse((List) collectionD); Collections.reverse((List) collectionE); Collections.reverse(combinedList); result1 = CollectionUtils.collate(collectionD, collectionE, reverseComparator); result2 = CollectionUtils.collate(collectionE, collectionD, reverseComparator); assertEquals("Comparator Merge two lists 1", result1, result2); assertEquals("Comparator Merge two lists 2", combinedList, result2); } @Test public void testCollateIgnoreDuplicates() { List result1 = CollectionUtils.collate(collectionD, collectionE, false); List result2 = CollectionUtils.collate(collectionE, collectionD, false); assertEquals("Merge two lists 1 - ignore duplicates", result1, result2); Set combinedSet = new HashSet(); combinedSet.addAll(collectionD); combinedSet.addAll(collectionE); List combinedList = new ArrayList(combinedSet); Collections.sort(combinedList); assertEquals("Merge two lists 2 - ignore duplicates", combinedList, result2); } @Test(expected=NullPointerException.class) public void testPermutationsWithNullCollection() { CollectionUtils.permutations(null); } @Test public void testPermutations() { List sample = collectionA.subList(0, 5); Collection> permutations = CollectionUtils.permutations(sample); // result size = n! int collSize = sample.size(); int factorial = 1; for (int i = 1; i <= collSize; i++) { factorial *= i; } assertEquals(factorial, permutations.size()); } @Test public void testMatchesAll() { assertFalse(CollectionUtils.matchesAll(null, null)); assertFalse(CollectionUtils.matchesAll(collectionA, null)); Predicate lessThanFive = new Predicate() { public boolean evaluate(Integer object) { return object < 5; } }; assertTrue(CollectionUtils.matchesAll(collectionA, lessThanFive)); Predicate lessThanFour = new Predicate() { public boolean evaluate(Integer object) { return object < 4; } }; assertFalse(CollectionUtils.matchesAll(collectionA, lessThanFour)); assertTrue(CollectionUtils.matchesAll(null, lessThanFour)); assertTrue(CollectionUtils.matchesAll(emptyCollection, lessThanFour)); } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/QueueUtilsTest.java100664 10601 12243235516 30617 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.LinkedList; import java.util.Queue; import junit.framework.Test; import org.apache.commons.collections4.functors.TruePredicate; import org.apache.commons.collections4.queue.PredicatedQueue; import org.apache.commons.collections4.queue.TransformedQueue; import org.apache.commons.collections4.queue.UnmodifiableQueue; /** * Tests for QueueUtils factory methods. * * @version $Id: QueueUtilsTest.java 1540768 2013-11-11 16:48:35Z tn $ */ public class QueueUtilsTest extends BulkTest { public QueueUtilsTest(final String name) { super(name); } public static Test suite() { return BulkTest.makeSuite(QueueUtilsTest.class); } // ---------------------------------------------------------------------- protected Class stringClass = this.getName().getClass(); protected Predicate truePredicate = TruePredicate.truePredicate(); protected Transformer nopTransformer = TransformerUtils.nopTransformer(); // ---------------------------------------------------------------------- public void testUnmodifiableQueue() { Queue queue = QueueUtils.unmodifiableQueue(new LinkedList()); assertTrue("Returned object should be an UnmodifiableQueue.", queue instanceof UnmodifiableQueue); try { QueueUtils.unmodifiableQueue(null); fail("Expecting IllegalArgumentException for null queue."); } catch (final IllegalArgumentException ex) { // expected } assertSame("UnmodifiableQueue shall not be decorated", queue, QueueUtils.unmodifiableQueue(queue)); } public void testPredicatedQueue() { Queue queue = QueueUtils.predicatedQueue(new LinkedList(), truePredicate); assertTrue("Returned object should be a PredicatedQueue.", queue instanceof PredicatedQueue); try { QueueUtils.predicatedQueue(null, truePredicate); fail("Expecting IllegalArgumentException for null queue."); } catch (final IllegalArgumentException ex) { // expected } try { QueueUtils.predicatedQueue(new LinkedList(), null); fail("Expecting IllegalArgumentException for null predicate."); } catch (final IllegalArgumentException ex) { // expected } } public void testTransformedQueue() { Queue queue = QueueUtils.transformingQueue(new LinkedList(), nopTransformer); assertTrue("Returned object should be an TransformedQueue.", queue instanceof TransformedQueue); try { QueueUtils.transformingQueue(null, nopTransformer); fail("Expecting IllegalArgumentException for null queue."); } catch (final IllegalArgumentException ex) { // expected } try { QueueUtils.transformingQueue(new LinkedList(), null); fail("Expecting IllegalArgumentException for null transformer."); } catch (final IllegalArgumentException ex) { // expected } } public void testEmptyQueue() { Queue queue = QueueUtils.emptyQueue(); assertTrue("Returned object should be an UnmodifiableQueue.", queue instanceof UnmodifiableQueue); assertTrue("Returned queue is not empty.", queue.isEmpty()); try { queue.add(new Object()); fail("Expecting UnsupportedOperationException for empty queue."); } catch (final UnsupportedOperationException ex) { // expected } } } commons-collections4-4.0-src/src/test/java/org/apache/commons/collections4/PredicateUtilsTest.java100664 77452 12243235516 31454 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import static org.apache.commons.collections4.functors.NullPredicate.nullPredicate; import static org.apache.commons.collections4.functors.TruePredicate.truePredicate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; 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 org.apache.commons.collections4.functors.AbstractPredicateTest; import org.apache.commons.collections4.functors.AllPredicate; import org.apache.commons.collections4.functors.EqualPredicate; import org.apache.commons.collections4.functors.ExceptionPredicate; import org.apache.commons.collections4.functors.FalsePredicate; import org.apache.commons.collections4.functors.NotNullPredicate; import org.apache.commons.collections4.functors.NullPredicate; import org.apache.commons.collections4.functors.TruePredicate; import org.junit.Test; /** * Tests the PredicateUtils class. * * @since 3.0 * @version $Id: PredicateUtilsTest.java 1540695 2013-11-11 13:01:13Z ebourg $ */ @SuppressWarnings("boxing") public class PredicateUtilsTest extends AbstractPredicateTest { /** * 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 //------------------------------------------------------------------ @Test public void testExceptionPredicate() { assertNotNull(PredicateUtils.exceptionPredicate()); assertSame(PredicateUtils.exceptionPredicate(), PredicateUtils.exceptionPredicate()); try { PredicateUtils.exceptionPredicate().evaluate(null); } catch (final FunctorException ex) { try { PredicateUtils.exceptionPredicate().evaluate(cString); } catch (final FunctorException ex2) { return; } } fail(); } // notNullPredicate //------------------------------------------------------------------ @Test 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)); } // identityPredicate //------------------------------------------------------------------ @Test public void testIdentityPredicate() { assertSame(nullPredicate(), PredicateUtils.identityPredicate(null)); assertNotNull(PredicateUtils.identityPredicate(Integer.valueOf(6))); assertEquals(false, PredicateUtils.identityPredicate(Integer.valueOf(6)).evaluate(null)); assertEquals(false, PredicateUtils.identityPredicate(Integer.valueOf(6)).evaluate(cObject)); assertEquals(false, PredicateUtils.identityPredicate(Integer.valueOf(6)).evaluate(cString)); assertEquals(false, PredicateUtils.identityPredicate(new Integer(6)).evaluate(cInteger)); // Cannot use valueOf here assertEquals(true, PredicateUtils.identityPredicate(cInteger).evaluate(cInteger)); } // truePredicate //------------------------------------------------------------------ @Test public void testTruePredicate() { assertNotNull(TruePredicate.truePredicate()); assertSame(TruePredicate.truePredicate(), TruePredicate.truePredicate()); assertEquals(true, TruePredicate.truePredicate().evaluate(null)); assertEquals(true, TruePredicate.truePredicate().evaluate(cObject)); assertEquals(true, TruePredicate.truePredicate().evaluate(cString)); assertEquals(true, TruePredicate.truePredicate().evaluate(cInteger)); } // falsePredicate //------------------------------------------------------------------ @Test public void testFalsePredicate() { assertNotNull(FalsePredicate.falsePredicate()); assertSame(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()); assertEquals(false, FalsePredicate.falsePredicate().evaluate(null)); assertEquals(false, FalsePredicate.falsePredicate().evaluate(cObject)); assertEquals(false, FalsePredicate.falsePredicate().evaluate(cString)); assertEquals(false, FalsePredicate.falsePredicate().evaluate(cInteger)); } // notPredicate //------------------------------------------------------------------ @Test public void testNotPredicate() { assertNotNull(PredicateUtils.notPredicate(TruePredicate.truePredicate())); assertEquals(false, PredicateUtils.notPredicate(TruePredicate.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.notPredicate(TruePredicate.truePredicate()).evaluate(cObject)); assertEquals(false, PredicateUtils.notPredicate(TruePredicate.truePredicate()).evaluate(cString)); assertEquals(false, PredicateUtils.notPredicate(TruePredicate.truePredicate()).evaluate(cInteger)); } @Test(expected=IllegalArgumentException.class) public void testNotPredicateEx() { PredicateUtils.notPredicate(null); } // andPredicate //------------------------------------------------------------------ @Test public void testAndPredicate() { assertEquals(true, PredicateUtils.andPredicate(TruePredicate.truePredicate(), TruePredicate.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.andPredicate(TruePredicate.truePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.andPredicate(FalsePredicate.falsePredicate(), TruePredicate.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.andPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); } @Test(expected=IllegalArgumentException.class) public void testAndPredicateEx() { PredicateUtils.andPredicate(null, null); } // allPredicate //------------------------------------------------------------------ @SuppressWarnings("unchecked") @Test public void testAllPredicate() { assertTrue(AllPredicate.allPredicate(new Predicate[] {}), null); assertEquals(true, AllPredicate.allPredicate(new Predicate[] { TruePredicate.truePredicate(), TruePredicate.truePredicate(), TruePredicate.truePredicate()}).evaluate(null)); assertEquals(false, AllPredicate.allPredicate(new Predicate[] { TruePredicate.truePredicate(), FalsePredicate.falsePredicate(), TruePredicate.truePredicate()}).evaluate(null)); assertEquals(false, AllPredicate.allPredicate(new Predicate[] { FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate(), TruePredicate.truePredicate()}).evaluate(null)); assertEquals(false, AllPredicate.allPredicate(new Predicate[] { FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()}).evaluate(null)); final Collection> coll = new ArrayList>(); coll.add(TruePredicate.truePredicate()); coll.add(TruePredicate.truePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(true, AllPredicate.allPredicate(coll).evaluate(null)); coll.clear(); coll.add(TruePredicate.truePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(false, AllPredicate.allPredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(false, AllPredicate.allPredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); assertEquals(false, AllPredicate.allPredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); assertFalse(AllPredicate.allPredicate(coll), null); coll.clear(); coll.add(TruePredicate.truePredicate()); assertTrue(AllPredicate.allPredicate(coll), null); coll.clear(); assertTrue(AllPredicate.allPredicate(coll), null); } @Test(expected=IllegalArgumentException.class) public void testAllPredicateEx1() { AllPredicate.allPredicate((Predicate[]) null); } @SuppressWarnings("unchecked") @Test(expected=IllegalArgumentException.class) public void testAllPredicateEx2() { AllPredicate.allPredicate(new Predicate[] { null }); } @SuppressWarnings("unchecked") @Test(expected=IllegalArgumentException.class) public void testAllPredicateEx3() { AllPredicate.allPredicate(new Predicate[] { null, null }); } @Test(expected=IllegalArgumentException.class) public void testAllPredicateEx4() { AllPredicate.allPredicate((Collection>) null); } @Test public void testAllPredicateEx5() { AllPredicate.allPredicate(Collections.>emptyList()); } @Test(expected=IllegalArgumentException.class) public void testAllPredicateEx6() { final Collection> coll = new ArrayList>(); coll.add(null); coll.add(null); AllPredicate.allPredicate(coll); } // orPredicate //------------------------------------------------------------------ @Test public void testOrPredicate() { assertEquals(true, PredicateUtils.orPredicate(TruePredicate.truePredicate(), TruePredicate.truePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.orPredicate(TruePredicate.truePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.orPredicate(FalsePredicate.falsePredicate(), TruePredicate.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.orPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); } @Test(expected=IllegalArgumentException.class) public void testOrPredicateEx() { PredicateUtils.orPredicate(null, null); } // anyPredicate //------------------------------------------------------------------ @SuppressWarnings("unchecked") @Test public void testAnyPredicate() { assertFalse(PredicateUtils.anyPredicate(new Predicate[] {}), null); assertEquals(true, PredicateUtils.anyPredicate(new Predicate[] { TruePredicate.truePredicate(), TruePredicate.truePredicate(), TruePredicate.truePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.anyPredicate(new Predicate[] { TruePredicate.truePredicate(), FalsePredicate.falsePredicate(), TruePredicate.truePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.anyPredicate(new Predicate[] { FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate(), TruePredicate.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.anyPredicate(new Predicate[] { FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()}).evaluate(null)); final Collection> coll = new ArrayList>(); coll.add(TruePredicate.truePredicate()); coll.add(TruePredicate.truePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(true, PredicateUtils.anyPredicate(coll).evaluate(null)); coll.clear(); coll.add(TruePredicate.truePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(true, PredicateUtils.anyPredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(true, PredicateUtils.anyPredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); assertEquals(false, PredicateUtils.anyPredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); assertFalse(PredicateUtils.anyPredicate(coll), null); coll.clear(); coll.add(TruePredicate.truePredicate()); assertTrue(PredicateUtils.anyPredicate(coll), null); coll.clear(); assertFalse(PredicateUtils.anyPredicate(coll), null); } @Test(expected=IllegalArgumentException.class) public void testAnyPredicateEx1() { PredicateUtils.anyPredicate((Predicate[]) null); } @SuppressWarnings("unchecked") @Test(expected=IllegalArgumentException.class) public void testAnyPredicateEx2() { PredicateUtils.anyPredicate(new Predicate[] {null}); } @SuppressWarnings("unchecked") @Test(expected=IllegalArgumentException.class) public void testAnyPredicateEx3() { PredicateUtils.anyPredicate(new Predicate[] {null, null}); } @Test(expected=IllegalArgumentException.class) public void testAnyPredicateEx4() { PredicateUtils.anyPredicate((Collection>) null); } @Test public void testAnyPredicateEx5() { PredicateUtils.anyPredicate(Collections.>emptyList()); } @Test(expected=IllegalArgumentException.class) public void testAnyPredicateEx6() { final Collection> coll = new ArrayList>(); coll.add(null); coll.add(null); PredicateUtils.anyPredicate(coll); } // eitherPredicate //------------------------------------------------------------------ @Test public void testEitherPredicate() { assertEquals(false, PredicateUtils.eitherPredicate(TruePredicate.truePredicate(), TruePredicate.truePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.eitherPredicate(TruePredicate.truePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.eitherPredicate(FalsePredicate.falsePredicate(), TruePredicate.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.eitherPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); } @Test(expected=IllegalArgumentException.class) public void testEitherPredicateEx() { PredicateUtils.eitherPredicate(null, null); } // onePredicate //------------------------------------------------------------------ @SuppressWarnings("unchecked") @Test public void testOnePredicate() { assertFalse(PredicateUtils.onePredicate((Predicate[]) new Predicate[] {}), null); assertEquals(false, PredicateUtils.onePredicate(new Predicate[] { TruePredicate.truePredicate(), TruePredicate.truePredicate(), TruePredicate.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.onePredicate(new Predicate[] { TruePredicate.truePredicate(), FalsePredicate.falsePredicate(), TruePredicate.truePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.onePredicate(new Predicate[] { TruePredicate.truePredicate(), FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.onePredicate(new Predicate[] { FalsePredicate.falsePredicate(), TruePredicate.truePredicate(), FalsePredicate.falsePredicate()}).evaluate(null)); assertEquals(true, PredicateUtils.onePredicate(new Predicate[] { FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate(), TruePredicate.truePredicate()}).evaluate(null)); assertEquals(false, PredicateUtils.onePredicate(new Predicate[] { FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()}).evaluate(null)); final Collection> coll = new ArrayList>(); coll.add(TruePredicate.truePredicate()); coll.add(TruePredicate.truePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(false, PredicateUtils.onePredicate(coll).evaluate(null)); coll.clear(); coll.add(TruePredicate.truePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(false, PredicateUtils.onePredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(true, PredicateUtils.onePredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); assertEquals(false, PredicateUtils.onePredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); assertFalse(PredicateUtils.onePredicate(coll), null); coll.clear(); coll.add(TruePredicate.truePredicate()); assertTrue(PredicateUtils.onePredicate(coll), null); coll.clear(); assertFalse(PredicateUtils.onePredicate(coll), null); } @Test(expected=IllegalArgumentException.class) public void testOnePredicateEx1() { PredicateUtils.onePredicate((Predicate[]) null); } @SuppressWarnings("unchecked") @Test(expected=IllegalArgumentException.class) public void testOnePredicateEx2() { PredicateUtils.onePredicate(new Predicate[] {null}); } @SuppressWarnings("unchecked") @Test(expected=IllegalArgumentException.class) public void testOnePredicateEx3() { PredicateUtils.onePredicate(new Predicate[] {null, null}); } @Test(expected=IllegalArgumentException.class) public void testOnePredicateEx4() { PredicateUtils.onePredicate((Collection>) null); } @SuppressWarnings("unchecked") @Test public void testOnePredicateEx5() { PredicateUtils.onePredicate(Collections.EMPTY_LIST); } @Test(expected=IllegalArgumentException.class) public void testOnePredicateEx6() { final Collection> coll = new ArrayList>(); coll.add(null); coll.add(null); PredicateUtils.onePredicate(coll); } // neitherPredicate //------------------------------------------------------------------ @Test public void testNeitherPredicate() { assertEquals(false, PredicateUtils.neitherPredicate(TruePredicate.truePredicate(), TruePredicate.truePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.neitherPredicate(TruePredicate.truePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); assertEquals(false, PredicateUtils.neitherPredicate(FalsePredicate.falsePredicate(), TruePredicate.truePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.neitherPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); } @Test(expected=IllegalArgumentException.class) public void testNeitherPredicateEx() { PredicateUtils.neitherPredicate(null, null); } // nonePredicate //------------------------------------------------------------------ @SuppressWarnings("unchecked") @Test public void testNonePredicate() { assertTrue(PredicateUtils.nonePredicate(new Predicate[] {}), null); assertEquals(false, PredicateUtils.nonePredicate(new Predicate[] { TruePredicate.truePredicate(), TruePredicate.truePredicate(), TruePredicate.truePredicate() }).evaluate(null)); assertEquals(false, PredicateUtils.nonePredicate(new Predicate[] { TruePredicate.truePredicate(), FalsePredicate.falsePredicate(), TruePredicate.truePredicate() }).evaluate(null)); assertEquals(false, PredicateUtils.nonePredicate(new Predicate[] { FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate(), TruePredicate.truePredicate() }).evaluate(null)); assertEquals(true, PredicateUtils.nonePredicate(new Predicate[] { FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate() }).evaluate(null)); final Collection> coll = new ArrayList>(); coll.add(TruePredicate.truePredicate()); coll.add(TruePredicate.truePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(false, PredicateUtils.nonePredicate(coll).evaluate(null)); coll.clear(); coll.add(TruePredicate.truePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(false, PredicateUtils.nonePredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(TruePredicate.truePredicate()); assertEquals(false, PredicateUtils.nonePredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); coll.add(FalsePredicate.falsePredicate()); assertEquals(true, PredicateUtils.nonePredicate(coll).evaluate(null)); coll.clear(); coll.add(FalsePredicate.falsePredicate()); assertTrue(PredicateUtils.nonePredicate(coll), null); coll.clear(); coll.add(TruePredicate.truePredicate()); assertFalse(PredicateUtils.nonePredicate(coll), null); coll.clear(); assertTrue(PredicateUtils.nonePredicate(coll), null); } @Test(expected=IllegalArgumentException.class) public void testNonePredicateEx1() { PredicateUtils.nonePredicate((Predicate[]) null); } @SuppressWarnings("unchecked") @Test(expected=IllegalArgumentException.class) public void testNonePredicateEx2() { PredicateUtils.nonePredicate(new Predicate[] {null}); } @SuppressWarnings("unchecked") @Test(expected=IllegalArgumentException.class) public void testNonePredicateEx3() { PredicateUtils.nonePredicate(new Predicate[] {null, null}); } @Test(expected=IllegalArgumentException.class) public void testNonePredicateEx4() { PredicateUtils.nonePredicate((Collection>) null); } @Test public void testNonePredicateEx5() { PredicateUtils.nonePredicate(Collections.>emptyList()); } @Test(expected=IllegalArgumentException.class) public void testNonePredicateEx6() { final Collection> coll = new ArrayList>(); coll.add(null); coll.add(null); PredicateUtils.nonePredicate(coll); } // instanceofPredicate //------------------------------------------------------------------ @Test 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 //------------------------------------------------------------------ @Test public void testUniquePredicate() { final 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) //------------------------------------------------------------------ @Test public void testAsPredicateTransformer() { assertEquals(false, PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(false)); assertEquals(true, PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(true)); } @Test(expected=IllegalArgumentException.class) public void testAsPredicateTransformerEx1() { PredicateUtils.asPredicate(null); } @Test(expected=FunctorException.class) public void testAsPredicateTransformerEx2() { PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(null); } // invokerPredicate //------------------------------------------------------------------ @Test public void testInvokerPredicate() { final List list = new ArrayList(); assertEquals(true, PredicateUtils.invokerPredicate("isEmpty").evaluate(list)); list.add(new Object()); assertEquals(false, PredicateUtils.invokerPredicate("isEmpty").evaluate(list)); } @Test(expected=IllegalArgumentException.class) public void testInvokerPredicateEx1() { PredicateUtils.invokerPredicate(null); } @Test(expected=FunctorException.class) public void testInvokerPredicateEx2() { PredicateUtils.invokerPredicate("isEmpty").evaluate(null); } @Test(expected=FunctorException.class) public void testInvokerPredicateEx3() { PredicateUtils.invokerPredicate("noSuchMethod").evaluate(new Object()); } // invokerPredicate2 //------------------------------------------------------------------ @Test public void testInvokerPredicate2() { final 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)); } @Test(expected=IllegalArgumentException.class) public void testInvokerPredicate2Ex1() { PredicateUtils.invokerPredicate(null, null, null); } @Test(expected=FunctorException.class) public void testInvokerPredicate2Ex2() { PredicateUtils.invokerPredicate("contains", new Class[] {Object.class}, new Object[] {cString}).evaluate(null); } @Test(expected=FunctorException.class) public void testInvokerPredicate2Ex3() { PredicateUtils.invokerPredicate( "noSuchMethod", new Class[] {Object.class}, new Object[] {cString}).evaluate(new Object()); } // nullIsException //------------------------------------------------------------------ @Test(expected=FunctorException.class) public void testNullIsExceptionPredicate() { assertEquals(true, PredicateUtils.nullIsExceptionPredicate(TruePredicate.truePredicate()).evaluate(new Object())); PredicateUtils.nullIsExceptionPredicate(TruePredicate.truePredicate()).evaluate(null); } @Test(expected=IllegalArgumentException.class) public void testNullIsExceptionPredicateEx1() { PredicateUtils.nullIsExceptionPredicate(null); } // nullIsTrue //------------------------------------------------------------------ @Test public void testNullIsTruePredicate() { assertEquals(true, PredicateUtils.nullIsTruePredicate(TruePredicate.truePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.nullIsTruePredicate(TruePredicate.truePredicate()).evaluate(new Object())); assertEquals(false, PredicateUtils.nullIsTruePredicate(FalsePredicate.falsePredicate()).evaluate(new Object())); } @Test(expected=IllegalArgumentException.class) public void testNullIsTruePredicateEx1() { PredicateUtils.nullIsTruePredicate(null); } // nullIsFalse //------------------------------------------------------------------ @Test public void testNullIsFalsePredicate() { assertEquals(false, PredicateUtils.nullIsFalsePredicate(TruePredicate.truePredicate()).evaluate(null)); assertEquals(true, PredicateUtils.nullIsFalsePredicate(TruePredicate.truePredicate()).evaluate(new Object())); assertEquals(false, PredicateUtils.nullIsFalsePredicate(FalsePredicate.falsePredicate()).evaluate(new Object())); } @Test(expected=IllegalArgumentException.class) public void testNullIsFalsePredicateEx1() { PredicateUtils.nullIsFalsePredicate(null); } // transformed //------------------------------------------------------------------ @Test public void testTransformedPredicate() { assertEquals(true, PredicateUtils.transformedPredicate( TransformerUtils.nopTransformer(), TruePredicate.truePredicate()).evaluate(new Object())); final Map map = new HashMap(); map.put(Boolean.TRUE, "Hello"); final Transformer t = TransformerUtils.mapTransformer(map); final Predicate p = EqualPredicate.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 (final IllegalArgumentException ex) {} } // misc tests //------------------------------------------------------------------ /** * Test that all Predicate singletones hold singleton pattern in * serialization/deserialization process. */ @Test public void testSingletonPatternInSerialization() { final Object[] singletones = new Object[] { ExceptionPredicate.INSTANCE, FalsePredicate.INSTANCE, NotNullPredicate.INSTANCE, NullPredicate.INSTANCE, TruePredicate.INSTANCE }; for (final Object original : singletones) { TestUtils.assertSameAfterSerialization( "Singletone patern broken for " + original.getClass(), original ); } } @Override protected Predicate generatePredicate() { return truePredicate(); //Just return something to satisfy super class. } } commons-collections4-4.0-src/src/main/assembly/bin.xml100664 3137 12243235516 21045 0ustartntn 0 0 bin tar.gz zip false LICENSE.txt NOTICE.txt README.txt RELEASE-NOTES.txt target *.jar target/site/apidocs apidocs commons-collections4-4.0-src/src/main/assembly/src.xml100664 3351 12243235516 21062 0ustartntn 0 0 src tar.gz zip ${project.artifactId}-${project.version}-src build.xml default.properties build.properties.sample DEVELOPERS-GUIDE.html LICENSE.txt NOTICE.txt pom.xml PROPOSAL.html README.txt RELEASE-NOTES.txt src **/*.cgi ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/AbstractKeyValue.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/AbstractKeyValue100664 4630 12243235516 31722 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import org.apache.commons.collections4.KeyValue; /** * Abstract pair class to assist with creating KeyValue * and {@link java.util.Map.Entry Map.Entry} implementations. * * @since 3.0 * @version $Id: AbstractKeyValue.java 1477753 2013-04-30 18:24:24Z tn $ */ public abstract class AbstractKeyValue implements KeyValue { /** The key */ private K key; /** The value */ private V value; /** * Constructs a new pair with the specified key and given value. * * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ protected AbstractKeyValue(final K key, final V value) { super(); this.key = key; this.value = value; } /** * Gets the key from the pair. * * @return the key */ public K getKey() { return key; } protected K setKey(K key) { final K old = this.key; this.key = key; return old; } /** * Gets the value from the pair. * * @return the value */ public V getValue() { return value; } protected V setValue(V value) { final V old = this.value; this.value = value; return old; } /** * Gets a debugging String view of the pair. * * @return a String view of the entry */ @Override public String toString() { return new StringBuilder() .append(getKey()) .append('=') .append(getValue()) .toString(); } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/AbstractMapEntry.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/AbstractMapEntry100664 6063 12243235516 31736 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.util.Map; /** * Abstract Pair class to assist with creating correct * {@link java.util.Map.Entry Map.Entry} implementations. * * @since 3.0 * @version $Id: AbstractMapEntry.java 1477753 2013-04-30 18:24:24Z tn $ */ 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(final K key, final V value) { super(key, value); } // Map.Entry interface //------------------------------------------------------------------------- /** * Sets the value stored in this Map.Entry. *

* This Map.Entry is not connected to a Map, so only the * local data is changed. * * @param value the new value * @return the previous value */ @Override public V setValue(final V value) { return super.setValue(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 */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } final 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 */ @Override public int hashCode() { return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/AbstractMapEntryDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/AbstractMapEntry100664 5030 12243235516 31727 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.util.Map; import org.apache.commons.collections4.KeyValue; /** * Provides a base decorator that allows additional functionality to be * added to a {@link java.util.Map.Entry Map.Entry}. * * @since 3.0 * @version $Id: AbstractMapEntryDecorator.java 1477753 2013-04-30 18:24:24Z tn $ */ public abstract class AbstractMapEntryDecorator implements Map.Entry, KeyValue { /** The Map.Entry to decorate */ private 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(final Map.Entry entry) { if (entry == null) { throw new IllegalArgumentException("Map Entry must not be null"); } this.entry = entry; } /** * Gets the map being decorated. * * @return the decorated map */ protected Map.Entry getMapEntry() { return entry; } //----------------------------------------------------------------------- public K getKey() { return entry.getKey(); } public V getValue() { return entry.getValue(); } public V setValue(final V object) { return entry.setValue(object); } @Override public boolean equals(final Object object) { if (object == this) { return true; } return entry.equals(object); } @Override public int hashCode() { return entry.hashCode(); } @Override public String toString() { return entry.toString(); } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/DefaultKeyValue.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/DefaultKeyValue.100664 11615 12243235516 31642 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.util.Map; import org.apache.commons.collections4.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 3.0 * @version $Id: DefaultKeyValue.java 1533984 2013-10-20 21:12:51Z tn $ */ public class DefaultKeyValue extends AbstractKeyValue { /** * Constructs a new pair with a null key and null value. */ public DefaultKeyValue() { super(null, null); } /** * Constructs a new pair with the specified key and given value. * * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ public DefaultKeyValue(final K key, final V value) { super(key, value); } /** * Constructs a new pair from the specified KeyValue. * * @param pair the pair to copy, must not be null * @throws NullPointerException if the entry is null */ public DefaultKeyValue(final KeyValue pair) { super(pair.getKey(), pair.getValue()); } /** * Constructs a new pair from the specified 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 */ @Override public K setKey(final K key) { if (key == this) { throw new IllegalArgumentException("DefaultKeyValue may not contain itself as a key."); } return super.setKey(key); } /** * Sets the value. * * @return the old value of the value * @param value the new value * @throws IllegalArgumentException if value is this object */ @Override public V setValue(final V value) { if (value == this) { throw new IllegalArgumentException("DefaultKeyValue may not contain itself as a value."); } return super.setValue(value); } //----------------------------------------------------------------------- /** * 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 */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof DefaultKeyValue == false) { return false; } final 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 */ @Override public int hashCode() { return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/TiedMapEntry.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/TiedMapEntry.jav100664 10006 12243235516 31647 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.io.Serializable; import java.util.Map; import org.apache.commons.collections4.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 3.0 * @version $Id: TiedMapEntry.java 1477753 2013-04-30 18:24:24Z tn $ */ public class TiedMapEntry implements Map.Entry, KeyValue, Serializable { /** Serialization version */ private static final long serialVersionUID = -8453869361373831205L; /** The map underlying the entry/iterator */ private final Map map; /** The key */ private final K key; /** * Constructs a new entry with the given Map and key. * * @param map the map * @param key the key */ public TiedMapEntry(final Map map, final K key) { super(); this.map = map; this.key = key; } // Map.Entry interface //------------------------------------------------------------------------- /** * Gets the key of this entry * * @return the key */ public K getKey() { return key; } /** * Gets the value of this entry direct from the map. * * @return the value */ public V getValue() { return map.get(key); } /** * Sets the value associated with the key direct onto the map. * * @param value the new value * @return the old value * @throws IllegalArgumentException if the value is set to this map entry */ public V setValue(final V 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 */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } final Map.Entry other = (Map.Entry) obj; final 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 */ @Override public int hashCode() { final 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 */ @Override public String toString() { return getKey() + "=" + getValue(); } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/package-info.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/package-info.jav100664 2540 12243235516 31612 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This 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 *
* * @version $Id: package-info.java 1469004 2013-04-17 17:37:03Z tn $ */ package org.apache.commons.collections4.keyvalue; ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/DefaultMapEntry.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/DefaultMapEntry.100664 4275 12243235516 31640 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.util.Map; import org.apache.commons.collections4.KeyValue; /** * A restricted implementation of {@link java.util.Map.Entry Map.Entry} that prevents * the {@link java.util.Map.Entry Map.Entry} contract from being broken. * * @since 3.0 * @version $Id: DefaultMapEntry.java 1533984 2013-10-20 21:12:51Z tn $ */ public final class DefaultMapEntry extends AbstractMapEntry { /** * Constructs a new entry with the specified key and given value. * * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ public DefaultMapEntry(final K key, final V value) { super(key, value); } /** * Constructs a new entry from the specified KeyValue. * * @param pair the pair to copy, must not be null * @throws NullPointerException if the entry is null */ public DefaultMapEntry(final KeyValue pair) { super(pair.getKey(), pair.getValue()); } /** * Constructs a new entry from the specified 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()); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/MultiKey.java100664 21430 12243235516 31211 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 look up a file name 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 retrieve the localized text
 * MultiKey multiKey = new MultiKey(key, locale);
 * String localizedText = (String) map.get(multiKey);
 * 
* * @since 3.0 * @version $Id: MultiKey.java 1477753 2013-04-30 18:24:24Z tn $ */ public class MultiKey implements Serializable { // This class could implement List, but that would confuse it's purpose /** Serialisation version */ private static final long serialVersionUID = 4465448607415788805L; /** The individual keys */ private final K[] keys; /** The cached hashCode */ private transient 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 */ @SuppressWarnings("unchecked") public MultiKey(final K key1, final K key2) { this((K[]) 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 */ @SuppressWarnings("unchecked") public MultiKey(final K key1, final K key2, final K key3) { this((K[]) 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 */ @SuppressWarnings("unchecked") public MultiKey(final K key1, final K key2, final K key3, final K key4) { this((K[]) 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 */ @SuppressWarnings("unchecked") public MultiKey(final K key1, final K key2, final K key3, final K key4, final K key5) { this((K[]) 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(final K[] keys) { this(keys, true); } /** * Constructor taking an array of keys, optionally choosing whether to clone. *

* If the array is not cloned, then it must not be modified. *

* This method is public for performance reasons only, to avoid a clone. * The hashcode is calculated once here in this method. * Therefore, changing the array passed in would not change the hashcode but * would change the equals method, which is a bug. *

* This is the only fully safe usage of this constructor, as the object array * is never made available in a variable: *

     * new MultiKey(new Object[] {...}, false);
     * 
*

* The keys should be immutable * If they are not then they must not be changed after adding to the MultiKey. * * @param keys the array of keys, not null * @param makeClone true to clone the array, false to assign it * @throws IllegalArgumentException if the key array is null * @since 3.1 */ public MultiKey(final K[] keys, final boolean makeClone) { super(); if (keys == null) { throw new IllegalArgumentException("The array of keys must not be null"); } if (makeClone) { this.keys = keys.clone(); } else { this.keys = keys; } calculateHashCode(keys); } //----------------------------------------------------------------------- /** * Gets a clone of the array of keys. *

* The keys should be immutable * If they are not then they must not be changed. * * @return the individual keys */ public K[] getKeys() { return keys.clone(); } /** * Gets the key at the specified index. *

* The key should be immutable. * If it is not then it must not be changed. * * @param index the index to retrieve * @return the key at the index * @throws IndexOutOfBoundsException if the index is invalid * @since 3.1 */ public K getKey(final int index) { return keys[index]; } /** * Gets the size of the list of keys. * * @return the size of the list of keys * @since 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 */ @Override public boolean equals(final Object other) { if (other == this) { return true; } if (other instanceof MultiKey) { final 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 */ @Override public int hashCode() { return hashCode; } /** * Gets a debugging string version of the key. * * @return a debugging string */ @Override public String toString() { return "MultiKey" + Arrays.toString(keys); } /** * Calculate the hash code of the instance using the provided keys. * @param keys the keys to calculate the hash code for */ private void calculateHashCode(final Object[] keys) { int total = 0; for (final Object key : keys) { if (key != null) { total ^= key.hashCode(); } } hashCode = total; } /** * Recalculate the hash code after deserialization. The hash code of some * keys might have change (hash codes based on the system hash code are * only stable for the same process). * @return the instance with recalculated hash code */ private Object readResolve() { calculateHashCode(keys); return this; } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/UnmodifiableMapEntry.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/keyvalue/UnmodifiableMapE100664 5113 12243235516 31647 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.keyvalue; import java.util.Map; import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.Unmodifiable; /** * A {@link java.util.Map.Entry Map.Entry} that throws * UnsupportedOperationException when setValue is called. * * @since 3.0 * @version $Id: UnmodifiableMapEntry.java 1533984 2013-10-20 21:12:51Z tn $ */ public final class UnmodifiableMapEntry extends AbstractMapEntry implements Unmodifiable { /** * Constructs a new entry with the specified key and given value. * * @param key the key for the entry, may be null * @param value the value for the entry, may be null */ public UnmodifiableMapEntry(final K key, final V value) { super(key, value); } /** * Constructs a new entry from the specified KeyValue. * * @param pair the pair to copy, must not be null * @throws NullPointerException if the entry is null */ public UnmodifiableMapEntry(final KeyValue pair) { super(pair.getKey(), pair.getValue()); } /** * Constructs a new entry from the specified 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 */ @Override public V setValue(final V value) { throw new UnsupportedOperationException("setValue() is not supported"); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/Trie.java100664 3511 12243235516 26504 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.SortedMap; /** * Defines the interface for a prefix tree, an ordered tree data structure. For * more information, see Tries. * * @since 4.0 * @version $Id: Trie.java 1543279 2013-11-19 00:54:31Z ggregory $ */ public interface Trie extends IterableSortedMap { /** * Returns a view of this {@link Trie} of all elements that are prefixed * by the given key. *

* In a {@link Trie} with fixed size keys, this is essentially a * {@link #get(Object)} operation. *

* For example, if the {@link Trie} contains 'Anna', 'Anael', * 'Analu', 'Andreas', 'Andrea', 'Andres', and 'Anatole', then * a lookup of 'And' would return 'Andreas', 'Andrea', and 'Andres'. * * @param key the key used in the search * @return a {@link SortedMap} view of this {@link Trie} with all elements whose * key is prefixed by the search key */ SortedMap prefixMap(K key); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/Get.java100664 3504 12243235516 26322 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Collection; import java.util.Set; /** * The "read" subset of the {@link java.util.Map} interface. * * @since 4.0 * @version $Id: Get.java 1543265 2013-11-19 00:48:44Z ggregory $ * * @see Put */ public interface Get { /** * @see java.util.Map#containsKey(Object) */ boolean containsKey(Object key); /** * @see java.util.Map#containsValue(Object) */ boolean containsValue(Object value); /** * @see java.util.Map#entrySet() */ Set> entrySet(); /** * @see java.util.Map#get(Object) */ V get(Object key); /** * @see java.util.Map#remove(Object) */ V remove(Object key); /** * @see java.util.Map#isEmpty() */ boolean isEmpty(); /** * @see java.util.Map#keySet() */ Set keySet(); /** * @see java.util.Map#size() */ int size(); /** * @see java.util.Map#values() */ Collection values(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/Transformer.java100664 4044 12243235516 30105 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * 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 invocation, returning a constant, * cloning and returning the string value. * * @param the input type to the transformer * @param the output type from the transformer * * @since 1.0 * @version $Id: Transformer.java 1543278 2013-11-19 00:54:07Z ggregory $ */ 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 */ O transform(I input); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/BoundedMap.java100664 3050 12243235517 27616 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * 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 3.0 * @version $Id: BoundedMap.java 1477779 2013-04-30 18:55:24Z tn $ */ public interface BoundedMap extends IterableMap { /** * 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(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/Equator.java100664 4061 12243235517 27223 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable * law or agreed to in writing, software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License * for the specific language governing permissions and limitations under the License. */ package org.apache.commons.collections4; /** * An equation function, which determines equality between objects of type T. *

* It is the functional sibling of {@link java.util.Comparator}; {@link Equator} is to * {@link Object} as {@link java.util.Comparator} is to {@link java.lang.Comparable}. * * @param the types of object this {@link Equator} can evaluate. * @since 4.0 * @version $Id: Equator.java 1540567 2013-11-10 22:19:29Z tn $ */ public interface Equator { /** * Evaluates the two arguments for their equality. * * @param o1 the first object to be equated. * @param o2 the second object to be equated. * @return whether the two objects are equal. */ boolean equate(T o1, T o2); /** * Calculates the hash for the object, based on the method of equality used in the equate * method. This is used for classes that delegate their {@link Object#equals(Object) equals(Object)} method to an * Equator (and so must also delegate their {@link Object#hashCode() hashCode()} method), or for implementations * of {@link org.apache.commons.collections4.map.HashedMap} that use an Equator for the key objects. * * @param o the object to calculate the hash for. * @return the hash of the object. */ int hash(T o); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/ResettableIterator.java100664 2477 12243235516 31417 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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. * * @param the type to iterate over * @since 3.0 * @version $Id: ResettableIterator.java 1543263 2013-11-19 00:47:55Z ggregory $ */ public interface ResettableIterator extends Iterator { /** * Resets the iterator back to the position at which the iterator * was created. */ void reset(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/FunctorException.java100664 4526 12243235516 31107 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * Runtime exception thrown from functors. * If required, a root cause error can be wrapped within this one. * * @since 3.0 * @version $Id: FunctorException.java 1477779 2013-04-30 18:55:24Z tn $ */ public class FunctorException extends RuntimeException { /** Serialization version */ private static final long serialVersionUID = -4704772662059351193L; /** * Constructs a new FunctorException without specified * detail message. */ public FunctorException() { super(); } /** * Constructs a new FunctorException with specified * detail message. * * @param msg the error message. */ public FunctorException(final String msg) { super(msg); } /** * 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(final Throwable rootCause) { super(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(final String msg, final Throwable rootCause) { super(msg, rootCause); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/OrderedMap.java100664 4432 12243235517 27627 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * Defines a map that maintains order and allows both forward and backward * iteration through that order. * * @param the type of the keys in the map * @param the type of the values in the map * * @since 3.0 * @version $Id: OrderedMap.java 1543259 2013-11-19 00:47:07Z ggregory $ */ 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. * * @return a map iterator */ OrderedMapIterator mapIterator(); /** * 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 */ K firstKey(); /** * Gets the last key currently in this map. * * @return the last key currently in this map * @throws java.util.NoSuchElementException if this map is empty */ K lastKey(); /** * Gets the next key after the one specified. * * @param key the key to search for next from * @return the next key, null if no match or at end */ K nextKey(K key); /** * Gets the previous key before the one specified. * * @param key the key to search for previous from * @return the previous key, null if no match or at start */ K previousKey(K key); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/BagUtils.java100664 24760 12243235516 27344 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import org.apache.commons.collections4.bag.CollectionBag; import org.apache.commons.collections4.bag.HashBag; import org.apache.commons.collections4.bag.PredicatedBag; import org.apache.commons.collections4.bag.PredicatedSortedBag; import org.apache.commons.collections4.bag.SynchronizedBag; import org.apache.commons.collections4.bag.SynchronizedSortedBag; import org.apache.commons.collections4.bag.TransformedBag; import org.apache.commons.collections4.bag.TransformedSortedBag; import org.apache.commons.collections4.bag.TreeBag; import org.apache.commons.collections4.bag.UnmodifiableBag; import org.apache.commons.collections4.bag.UnmodifiableSortedBag; /** * Provides utility methods and decorators for {@link Bag} and {@link SortedBag} instances. * * @since 2.1 * @version $Id: BagUtils.java 1543964 2013-11-20 21:53:39Z tn $ */ public class BagUtils { /** * An empty unmodifiable bag. */ @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type public static final Bag EMPTY_BAG = UnmodifiableBag.unmodifiableBag(new HashBag()); /** * An empty unmodifiable sorted bag. */ @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type public static final Bag EMPTY_SORTED_BAG = UnmodifiableSortedBag.unmodifiableSortedBag(new TreeBag()); /** * Instantiation of BagUtils is not intended or required. */ private 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 the element type * @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(final Bag bag) { return SynchronizedBag.synchronizedBag(bag); } /** * Returns an unmodifiable view of the given bag. Any modification attempts * to the returned bag will raise an {@link UnsupportedOperationException}. * * @param the element type * @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(final Bag bag) { return UnmodifiableBag.unmodifiableBag(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 the element type * @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(final Bag bag, final Predicate predicate) { return PredicatedBag.predicatedBag(bag, predicate); } /** * 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. *

* Existing entries in the specified bag will not be transformed. * If you want that behaviour, see {@link TransformedBag#transformedBag(Bag, Transformer)}. * * @param the element type * @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 transformingBag(final Bag bag, final Transformer transformer) { return TransformedBag.transformingBag(bag, transformer); } /** * Returns a bag that complies to the Collection contract, backed by the given bag. * * @param the element type * @param bag the bag to decorate, must not be null * @return a Bag that complies to the Collection contract * @throws IllegalArgumentException if bag is null * @since 4.0 */ public static Bag collectionBag(final Bag bag) { return CollectionBag.collectionBag(bag); } //----------------------------------------------------------------------- /** * 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 the element type * @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(final SortedBag bag) { return SynchronizedSortedBag.synchronizedSortedBag(bag); } /** * Returns an unmodifiable view of the given sorted bag. Any modification * attempts to the returned bag will raise an * {@link UnsupportedOperationException}. * * @param the element type * @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(final SortedBag bag) { return UnmodifiableSortedBag.unmodifiableSortedBag(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 the element type * @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(final SortedBag bag, final Predicate predicate) { return PredicatedSortedBag.predicatedSortedBag(bag, predicate); } /** * 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. *

* Existing entries in the specified bag will not be transformed. * If you want that behaviour, see * {@link TransformedSortedBag#transformedSortedBag(SortedBag, Transformer)}. * * @param the element type * @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 transformingSortedBag(final SortedBag bag, final Transformer transformer) { return TransformedSortedBag.transformingSortedBag(bag, transformer); } /** * Get an empty Bag. * * @param the element type * @return an empty Bag */ @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type public static Bag emptyBag() { return (Bag) EMPTY_BAG; } /** * Get an empty SortedBag. * * @param the element type * @return an empty sorted Bag */ @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type public static SortedBag emptySortedBag() { return (SortedBag) EMPTY_SORTED_BAG; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/AbstractMapBag.java100664 45554 12243235516 31202 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.Map.Entry; import java.util.Set; import org.apache.commons.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.Bag; /** * 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 3.0 (previously DefaultMapBag v2.0) * @version $Id: AbstractMapBag.java 1491258 2013-06-09 18:35:24Z tn $ */ 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(final 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(final Object object) { final MutableInteger count = map.get(object); if (count != null) { return count.value; } return 0; } //----------------------------------------------------------------------- /** * Determines if the bag contains the given element by checking if the * underlying map contains the element as a key. * * @param object the object to search for * @return true if the bag contains the given element */ public boolean contains(final 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(final 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(final Bag other) { final Iterator it = other.uniqueSet().iterator(); while (it.hasNext()) { final Object current = it.next(); if (getCount(current) < other.getCount(current)) { return false; } } return true; } //----------------------------------------------------------------------- /** * 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 final AbstractMapBag parent; private final Iterator> entryIterator; private Map.Entry current; private int itemCount; private final int mods; private boolean canRemove; /** * Constructor. * * @param parent the parent bag */ public BagIterator(final AbstractMapBag parent) { this.parent = parent; this.entryIterator = parent.map.entrySet().iterator(); this.current = null; this.mods = parent.modCount; this.canRemove = false; } /** {@inheritDoc} */ public boolean hasNext() { return itemCount > 0 || entryIterator.hasNext(); } /** {@inheritDoc} */ public E next() { if (parent.modCount != mods) { throw new ConcurrentModificationException(); } if (itemCount == 0) { current = entryIterator.next(); itemCount = current.getValue().value; } canRemove = true; itemCount--; return current.getKey(); } /** {@inheritDoc} */ public void remove() { if (parent.modCount != mods) { throw new ConcurrentModificationException(); } if (canRemove == false) { throw new IllegalStateException(); } final MutableInteger mut = 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(final E object) { return add(object, 1); } /** * Adds a new element to the bag, incrementing its count in the map. * * @param object the object to search for * @param nCopies the number of copies to add * @return true if the object was not already in the uniqueSet */ public boolean add(final E object, final int nCopies) { modCount++; if (nCopies > 0) { final MutableInteger mut = map.get(object); size += nCopies; if (mut == null) { map.put(object, new MutableInteger(nCopies)); return true; } mut.value += nCopies; return false; } 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(final Collection coll) { boolean changed = false; final Iterator i = coll.iterator(); while (i.hasNext()) { final 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(final Object object) { final MutableInteger mut = map.get(object); if (mut == null) { return false; } modCount++; map.remove(object); size -= mut.value; return true; } /** * Removes a specified number of copies of an object from the bag. * * @param object the object to remove * @param nCopies the number of copies to remove * @return true if the bag changed */ public boolean remove(final Object object, final int nCopies) { final MutableInteger mut = 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(final Collection coll) { boolean result = false; if (coll != null) { final Iterator i = coll.iterator(); while (i.hasNext()) { final 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(final 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(final Bag other) { boolean result = false; final Bag excess = new HashBag(); final Iterator i = uniqueSet().iterator(); while (i.hasNext()) { final E current = i.next(); final int myCount = getCount(current); final 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(final int value) { this.value = value; } @Override public boolean equals(final Object obj) { if (obj instanceof MutableInteger == false) { return false; } return ((MutableInteger) obj).value == value; } @Override 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() { final Object[] result = new Object[size()]; int i = 0; final Iterator it = map.keySet().iterator(); while (it.hasNext()) { final E current = it.next(); for (int index = getCount(current); index > 0; index--) { result[i++] = current; } } return result; } /** * Returns an array of all of this bag's elements. * If the input array has more elements than are in the bag, * trailing elements will be set to null. * * @param the type of the array elements * @param array the array to populate * @return an array of all of this bag's elements * @throws ArrayStoreException if the runtime type of the specified array is not * a supertype of the runtime type of the elements in this list * @throws NullPointerException if the specified array is null */ public T[] toArray(T[] array) { final int size = size(); if (array.length < size) { @SuppressWarnings("unchecked") // safe as both are of type T final T[] unchecked = (T[]) Array.newInstance(array.getClass().getComponentType(), size); array = unchecked; } int i = 0; final Iterator it = map.keySet().iterator(); while (it.hasNext()) { final E current = it.next(); for (int index = getCount(current); index > 0; index--) { // unsafe, will throw ArrayStoreException if types are not compatible, see javadoc @SuppressWarnings("unchecked") final T unchecked = (T) current; array[i++] = unchecked; } } while (i < array.length) { array[i++] = 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. unmodifiableSet(map.keySet()); } return uniqueSet; } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * @param out the output stream * @throws IOException any of the usual I/O related exceptions */ protected void doWriteObject(final ObjectOutputStream out) throws IOException { out.writeInt(map.size()); for (final Entry entry : map.entrySet()) { out.writeObject(entry.getKey()); out.writeInt(entry.getValue().value); } } /** * Read the map in using a custom routine. * @param map the map to use * @param in the input stream * @throws IOException any of the usual I/O related exceptions * @throws ClassNotFoundException if the stream contains an object which class can not be loaded * @throws ClassCastException if the stream does not contain the correct objects */ protected void doReadObject(final Map map, final ObjectInputStream in) throws IOException, ClassNotFoundException { this.map = map; final int entrySize = in.readInt(); for (int i = 0; i < entrySize; i++) { @SuppressWarnings("unchecked") // This will fail at runtime if the stream is incorrect final E obj = (E) in.readObject(); final 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 */ @Override public boolean equals(final Object object) { if (object == this) { return true; } if (object instanceof Bag == false) { return false; } final Bag other = (Bag) object; if (other.size() != size()) { return false; } for (final E element : map.keySet()) { 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 */ @Override public int hashCode() { int total = 0; for (final Entry entry : map.entrySet()) { final E element = entry.getKey(); final MutableInteger count = entry.getValue(); total += (element == null ? 0 : element.hashCode()) ^ count.value; } return total; } /** * Implement a toString() method suitable for debugging. * * @return a debugging toString */ @Override public String toString() { if (size() == 0) { return "[]"; } final StringBuilder buf = new StringBuilder(); buf.append('['); final Iterator it = uniqueSet().iterator(); while (it.hasNext()) { final Object current = it.next(); final int count = getCount(current); buf.append(count); buf.append(':'); buf.append(current); if (it.hasNext()) { buf.append(','); } } buf.append(']'); return buf.toString(); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/PredicatedSortedBag.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/PredicatedSortedBag.j100664 7422 12243235516 31506 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Comparator; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.SortedBag; /** * Decorates another {@link 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 {@link 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 3.0 * @version $Id: PredicatedSortedBag.java 1479399 2013-05-05 21:46:48Z tn $ */ 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 the type of the elements in the bag * @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 * @since 4.0 */ public static PredicatedSortedBag predicatedSortedBag(final SortedBag bag, final 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(final SortedBag bag, final Predicate predicate) { super(bag, predicate); } /** * Gets the decorated sorted bag. * * @return the decorated bag */ @Override protected SortedBag decorated() { return (SortedBag) super.decorated(); } //----------------------------------------------------------------------- public E first() { return decorated().first(); } public E last() { return decorated().last(); } public Comparator comparator() { return decorated().comparator(); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/TransformedBag.java100664 12175 12243235516 31256 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Set; import org.apache.commons.collections4.set.TransformedSet; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.collection.TransformedCollection; /** * Decorates another {@link 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 3.0 * @version $Id: TransformedBag.java 1494280 2013-06-18 20:07:04Z tn $ */ 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. Contrast this with {@link #transformedBag(Bag, Transformer)}. * * @param the type of the elements in the bag * @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 * @since 4.0 */ public static Bag transformingBag(final Bag bag, final Transformer transformer) { return new TransformedBag(bag, transformer); } /** * Factory method to create a transforming bag that will transform * existing contents of the specified bag. *

* If there are any elements already in the bag being decorated, they * will be transformed by this method. * Contrast this with {@link #transformingBag(Bag, Transformer)}. * * @param the type of the elements in the bag * @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 * @since 4.0 */ public static Bag transformedBag(final Bag bag, final Transformer transformer) { final TransformedBag decorated = new TransformedBag(bag, transformer); if (transformer != null && bag != null && bag.size() > 0) { @SuppressWarnings("unchecked") // Bag is of type E final E[] values = (E[]) bag.toArray(); // NOPMD - false positive for generics bag.clear(); for (final E value : values) { decorated.decorated().add(transformer.transform(value)); } } return decorated; } //----------------------------------------------------------------------- /** * 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(final Bag bag, final Transformer transformer) { super(bag, transformer); } /** * Gets the decorated bag. * * @return the decorated bag */ protected Bag getBag() { return (Bag) decorated(); } //----------------------------------------------------------------------- public int getCount(final Object object) { return getBag().getCount(object); } public boolean remove(final Object object, final int nCopies) { return getBag().remove(object, nCopies); } //----------------------------------------------------------------------- public boolean add(final E object, final int nCopies) { return getBag().add(transform(object), nCopies); } public Set uniqueSet() { final Set set = getBag().uniqueSet(); return TransformedSet.transformingSet(set, transformer); } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/SynchronizedSortedBag.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/SynchronizedSortedBag100664 6513 12243235516 31671 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Comparator; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.SortedBag; /** * Decorates another {@link 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 3.0 * @version $Id: SynchronizedSortedBag.java 1479399 2013-05-05 21:46:48Z tn $ */ public class SynchronizedSortedBag extends SynchronizedBag implements SortedBag { /** Serialization version */ private static final long serialVersionUID = 722374056718497858L; /** * Factory method to create a synchronized sorted bag. * * @param the type of the elements in the bag * @param bag the bag to decorate, must not be null * @return a new synchronized SortedBag * @throws IllegalArgumentException if bag is null * @since 4.0 */ public static SynchronizedSortedBag synchronizedSortedBag(final 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(final 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(final Bag bag, final Object lock) { super(bag, lock); } /** * Gets the bag being decorated. * * @return the decorated bag */ protected SortedBag getSortedBag() { return (SortedBag) decorated(); } //----------------------------------------------------------------------- public synchronized E first() { synchronized (lock) { return getSortedBag().first(); } } public synchronized E last() { synchronized (lock) { return getSortedBag().last(); } } public synchronized Comparator comparator() { synchronized (lock) { return getSortedBag().comparator(); } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/UnmodifiableBag.java100664 12146 12243235516 31366 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableIterator; import org.apache.commons.collections4.set.UnmodifiableSet; /** * Decorates another {@link Bag} to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableBag.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class UnmodifiableBag extends AbstractBagDecorator implements Unmodifiable { /** 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 the type of the elements in the bag * @param bag the bag to decorate, must not be null * @return an unmodifiable Bag * @throws IllegalArgumentException if bag is null * @since 4.0 */ public static Bag unmodifiableBag(final Bag bag) { if (bag instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final Bag tmpBag = (Bag) bag; return tmpBag; } 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 */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableBag(final Bag bag) { super((Bag) bag); } //----------------------------------------------------------------------- /** * Write the collection out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(decorated()); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @throws ClassCastException if deserialised object has wrong type */ @SuppressWarnings("unchecked") // will throw CCE, see Javadoc private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); setCollection((Collection) in.readObject()); } //----------------------------------------------------------------------- @Override public Iterator iterator() { return UnmodifiableIterator. unmodifiableIterator(decorated().iterator()); } @Override public boolean add(final E object) { throw new UnsupportedOperationException(); } @Override public boolean addAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- @Override public boolean add(final E object, final int count) { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object, final int count) { throw new UnsupportedOperationException(); } @Override public Set uniqueSet() { final Set set = decorated().uniqueSet(); return UnmodifiableSet. unmodifiableSet(set); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/HashBag.java100664 5320 12243235516 27627 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.HashMap; /** * Implements {@link Bag}, using a {@link HashMap} to provide the * data storage. This is the standard implementation of a bag. *

* A {@link 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 * {@link Collection} interface specification. * * @since 3.0 (previously in main package v2.0) * @version $Id: HashBag.java 1543928 2013-11-20 20:15:35Z tn $ */ public class HashBag extends AbstractMapBag implements Serializable { /** Serial version lock */ private static final long serialVersionUID = -6561115435802554013L; /** * Constructs an empty {@link 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(final Collection coll) { this(); addAll(coll); } //----------------------------------------------------------------------- /** * Write the bag out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); super.doWriteObject(out); } /** * Read the bag in using a custom routine. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); super.doReadObject(new HashMap(), in); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/CollectionSortedBag.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/CollectionSortedBag.j100664 12707 12243235516 31557 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections4.SortedBag; /** * Decorates another {@link SortedBag} to comply with the Collection contract. * * @since 4.0 * @version $Id: CollectionSortedBag.java 1543168 2013-11-18 21:22:43Z ggregory $ */ public final class CollectionSortedBag extends AbstractSortedBagDecorator { /** Serialization version */ private static final long serialVersionUID = -2560033712679053143L; /** * Factory method to create a sorted bag that complies to the Collection contract. * * @param the type of the elements in the bag * @param bag the sorted bag to decorate, must not be null * @return a SortedBag that complies to the Collection contract * @throws IllegalArgumentException if bag is null */ public static SortedBag collectionSortedBag(final SortedBag bag) { return new CollectionSortedBag(bag); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param bag the sorted bag to decorate, must not be null * @throws IllegalArgumentException if bag is null */ public CollectionSortedBag(final SortedBag bag) { super(bag); } //----------------------------------------------------------------------- /** * Write the collection out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(decorated()); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @throws ClassCastException if deserialised object has wrong type */ @SuppressWarnings("unchecked") // will throw CCE, see Javadoc private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); setCollection((Collection) in.readObject()); } //----------------------------------------------------------------------- // Collection interface //----------------------------------------------------------------------- @Override public boolean containsAll(final Collection coll) { final Iterator e = coll.iterator(); while (e.hasNext()) { if(!contains(e.next())) { return false; } } return true; } @Override public boolean add(final E object) { return add(object, 1); } @Override public boolean addAll(final Collection coll) { boolean changed = false; final Iterator i = coll.iterator(); while (i.hasNext()) { final boolean added = add(i.next(), 1); changed = changed || added; } return changed; } @Override public boolean remove(final Object object) { return remove(object, 1); } @Override public boolean removeAll(final Collection coll) { if (coll != null) { boolean result = false; final Iterator i = coll.iterator(); while (i.hasNext()) { final Object obj = i.next(); final boolean changed = remove(obj, getCount(obj)); result = result || changed; } return result; } else { // let the decorated bag handle the case of null argument return decorated().removeAll(null); } } @Override public boolean retainAll(final Collection coll) { if (coll != null) { boolean modified = false; final Iterator e = iterator(); while (e.hasNext()) { if (!coll.contains(e.next())) { e.remove(); modified = true; } } return modified; } else { // let the decorated bag handle the case of null argument return decorated().retainAll(null); } } //----------------------------------------------------------------------- // Bag interface //----------------------------------------------------------------------- @Override public boolean add(final E object, final int count) { decorated().add(object, count); return true; } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/AbstractSortedBagDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/AbstractSortedBagDeco100664 4472 12243235516 31552 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Comparator; import org.apache.commons.collections4.SortedBag; /** * Decorates another SortedBag to provide additional behaviour. *

* Methods are forwarded directly to the decorated bag. * * @since 3.0 * @version $Id: AbstractSortedBagDecorator.java 1477752 2013-04-30 18:21:52Z tn $ */ public abstract class AbstractSortedBagDecorator extends AbstractBagDecorator implements SortedBag { /** Serialization version */ private static final long serialVersionUID = -8223473624050467718L; /** * Constructor only used in deserialization, do not use otherwise. * @since 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(final SortedBag bag) { super(bag); } /** * Gets the bag being decorated. * * @return the decorated bag */ @Override protected SortedBag decorated() { return (SortedBag) super.decorated(); } //----------------------------------------------------------------------- public E first() { return decorated().first(); } public E last() { return decorated().last(); } public Comparator comparator() { return decorated().comparator(); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/PredicatedBag.java100664 7620 12243235516 31015 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Set; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.collection.PredicatedCollection; /** * Decorates another {@link 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 {@link 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 3.0 * @version $Id: PredicatedBag.java 1479399 2013-05-05 21:46:48Z tn $ */ 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 the type of the elements in the bag * @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 * @since 4.0 */ public static PredicatedBag predicatedBag(final Bag bag, final 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(final Bag bag, final Predicate predicate) { super(bag, predicate); } /** * Gets the decorated bag. * * @return the decorated bag */ @Override protected Bag decorated() { return (Bag) super.decorated(); } //----------------------------------------------------------------------- public boolean add(final E object, final int count) { validate(object); return decorated().add(object, count); } public boolean remove(final Object object, final int count) { return decorated().remove(object, count); } public Set uniqueSet() { return decorated().uniqueSet(); } public int getCount(final Object object) { return decorated().getCount(object); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/SynchronizedBag.java100664 10106 12243235516 31441 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Set; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.collection.SynchronizedCollection; /** * Decorates another {@link 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 3.0 * @version $Id: SynchronizedBag.java 1479399 2013-05-05 21:46:48Z tn $ */ public class SynchronizedBag extends SynchronizedCollection implements Bag { /** Serialization version */ private static final long serialVersionUID = 8084674570753837109L; /** * Factory method to create a synchronized bag. * * @param the type of the elements in the bag * @param bag the bag to decorate, must not be null * @return a new synchronized Bag * @throws IllegalArgumentException if bag is null * @since 4.0 */ public static SynchronizedBag synchronizedBag(final 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(final 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(final Bag bag, final Object lock) { super(bag, lock); } /** * Gets the bag being decorated. * * @return the decorated bag */ protected Bag getBag() { return (Bag) decorated(); } //----------------------------------------------------------------------- public boolean add(final E object, final int count) { synchronized (lock) { return getBag().add(object, count); } } public boolean remove(final Object object, final int count) { synchronized (lock) { return getBag().remove(object, count); } } public Set uniqueSet() { synchronized (lock) { final Set set = getBag().uniqueSet(); return new SynchronizedBagSet(set, lock); } } public int getCount(final Object object) { synchronized (lock) { return getBag().getCount(object); } } //----------------------------------------------------------------------- /** * Synchronized Set for the Bag class. */ class SynchronizedBagSet extends SynchronizedCollection implements Set { /** Serialization version */ private static final long serialVersionUID = 2990565892366827855L; /** * Constructor. * @param set the set to decorate * @param lock the lock to use, shared with the bag */ SynchronizedBagSet(final Set set, final Object lock) { super(set, lock); } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/TreeBag.java100664 11243 12243235516 27664 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.SortedBag; /** * Implements {@link SortedBag}, using a {@link 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 {@link org.apache.commons.collections4.Bag 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 {@link Collection} interface specification. * * @since 3.0 (previously in main package v2.0) * @version $Id: TreeBag.java 1477752 2013-04-30 18:21:52Z tn $ */ public class TreeBag extends AbstractMapBag implements SortedBag, Serializable { /** Serial version lock */ private static final long serialVersionUID = -7740146511091606676L; /** * Constructs an empty {@link 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(final Comparator comparator) { super(new TreeMap(comparator)); } /** * Constructs a {@link TreeBag} containing all the members of the * specified collection. * * @param coll the collection to copy into the bag */ public TreeBag(final Collection coll) { this(); addAll(coll); } //----------------------------------------------------------------------- /** * {@inheritDoc} * * @throws IllegalArgumentException if the object to be added does not implement * {@link Comparable} and the {@link TreeBag} is using natural ordering */ @Override public boolean add(final E object) { if(comparator() == null && !(object instanceof Comparable)) { throw new IllegalArgumentException("Objects of type " + object.getClass() + " cannot be added to " + "a naturally ordered TreeBag as it does not implement Comparable"); } return super.add(object); } //----------------------------------------------------------------------- public E first() { return getMap().firstKey(); } public E last() { return getMap().lastKey(); } public Comparator comparator() { return getMap().comparator(); } @Override protected SortedMap getMap() { return (SortedMap) super.getMap(); } //----------------------------------------------------------------------- /** * Write the bag out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(comparator()); super.doWriteObject(out); } /** * Read the bag in using a custom routine. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); @SuppressWarnings("unchecked") // This will fail at runtime if the stream is incorrect final Comparator comp = (Comparator) in.readObject(); super.doReadObject(new TreeMap(comp), in); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/package-info.java100664 3533 12243235516 30662 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains implementations of the {@link org.apache.commons.collections4.Bag Bag} and * {@link org.apache.commons.collections4.SortedBag SortedBag} interfaces. * A bag stores an object and a count of the number of occurrences 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 *
  • Transformed - transforms each element added to the bag *
  • Collection - ensures compliance with the java.util.Collection contract *
* * @version $Id: package-info.java 1540804 2013-11-11 18:58:31Z tn $ */ package org.apache.commons.collections4.bag; ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/TransformedSortedBag.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/TransformedSortedBag.100664 11571 12243235516 31574 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Comparator; import org.apache.commons.collections4.SortedBag; import org.apache.commons.collections4.Transformer; /** * Decorates another {@link 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 3.0 * @version $Id: TransformedSortedBag.java 1494280 2013-06-18 20:07:04Z tn $ */ 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. Contrast this with {@link #transformedSortedBag(SortedBag, Transformer)}. * * @param the type of the elements in the bag * @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 * @since 4.0 */ public static TransformedSortedBag transformingSortedBag(final SortedBag bag, final Transformer transformer) { return new TransformedSortedBag(bag, transformer); } /** * Factory method to create a transforming sorted bag that will transform * existing contents of the specified sorted bag. *

* If there are any elements already in the bag being decorated, they * will be transformed by this method. * Contrast this with {@link #transformingSortedBag(SortedBag, Transformer)}. * * @param the type of the elements in the bag * @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 * @since 4.0 */ public static TransformedSortedBag transformedSortedBag(final SortedBag bag, final Transformer transformer) { final TransformedSortedBag decorated = new TransformedSortedBag(bag, transformer); if (transformer != null && bag != null && bag.size() > 0) { @SuppressWarnings("unchecked") // bag is type E final E[] values = (E[]) bag.toArray(); // NOPMD - false positive for generics bag.clear(); for (final E value : values) { decorated.decorated().add(transformer.transform(value)); } } return decorated; } //----------------------------------------------------------------------- /** * 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(final SortedBag bag, final Transformer transformer) { super(bag, transformer); } /** * Gets the decorated bag. * * @return the decorated bag */ protected SortedBag getSortedBag() { return (SortedBag) decorated(); } //----------------------------------------------------------------------- public E first() { return getSortedBag().first(); } public E last() { return getSortedBag().last(); } public Comparator comparator() { return getSortedBag().comparator(); } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/UnmodifiableSortedBag.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/UnmodifiableSortedBag100664 11744 12243235516 31632 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.apache.commons.collections4.SortedBag; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableIterator; import org.apache.commons.collections4.set.UnmodifiableSet; /** * Decorates another {@link SortedBag} to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableSortedBag.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class UnmodifiableSortedBag extends AbstractSortedBagDecorator implements Unmodifiable { /** 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 the type of the elements in the bag * @param bag the bag to decorate, must not be null * @return an unmodifiable SortedBag * @throws IllegalArgumentException if bag is null * @since 4.0 */ public static SortedBag unmodifiableSortedBag(final 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(final SortedBag bag) { super(bag); } //----------------------------------------------------------------------- /** * Write the collection out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(decorated()); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @throws ClassCastException if deserialised object has wrong type */ @SuppressWarnings("unchecked") // will throw CCE, see Javadoc private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); setCollection((Collection) in.readObject()); } //----------------------------------------------------------------------- @Override public Iterator iterator() { return UnmodifiableIterator.unmodifiableIterator(decorated().iterator()); } @Override public boolean add(final E object) { throw new UnsupportedOperationException(); } @Override public boolean addAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- @Override public boolean add(final E object, final int count) { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object, final int count) { throw new UnsupportedOperationException(); } @Override public Set uniqueSet() { final Set set = decorated().uniqueSet(); return UnmodifiableSet.unmodifiableSet(set); } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/AbstractBagDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/AbstractBagDecorator.100664 5010 12243235516 31504 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.util.Set; import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.collection.AbstractCollectionDecorator; /** * Decorates another Bag to provide additional behaviour. *

* Methods are forwarded directly to the decorated bag. * * @since 3.0 * @version $Id: AbstractBagDecorator.java 1477752 2013-04-30 18:21:52Z tn $ */ public abstract class AbstractBagDecorator extends AbstractCollectionDecorator implements Bag { /** Serialization version */ private static final long serialVersionUID = -3768146017343785417L; /** * Constructor only used in deserialization, do not use otherwise. * @since 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(final Bag bag) { super(bag); } /** * Gets the bag being decorated. * * @return the decorated bag */ @Override protected Bag decorated() { return (Bag) super.decorated(); } //----------------------------------------------------------------------- public int getCount(final Object object) { return decorated().getCount(object); } public boolean add(final E object, final int count) { return decorated().add(object, count); } public boolean remove(final Object object, final int count) { return decorated().remove(object, count); } public Set uniqueSet() { return decorated().uniqueSet(); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bag/CollectionBag.java100664 12552 12243235516 31064 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bag; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections4.Bag; /** * Decorates another {@link Bag} to comply with the Collection contract. * * @since 4.0 * @version $Id: CollectionBag.java 1543168 2013-11-18 21:22:43Z ggregory $ */ public final class CollectionBag extends AbstractBagDecorator { /** Serialization version */ private static final long serialVersionUID = -2560033712679053143L; /** * Factory method to create a bag that complies to the Collection contract. * * @param the type of the elements in the bag * @param bag the bag to decorate, must not be null * @return a Bag that complies to the Collection contract * @throws IllegalArgumentException if bag is null */ public static Bag collectionBag(final Bag bag) { return new CollectionBag(bag); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param bag the bag to decorate, must not be null * @throws IllegalArgumentException if bag is null */ public CollectionBag(final Bag bag) { super(bag); } //----------------------------------------------------------------------- /** * Write the collection out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(decorated()); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException * @throws ClassCastException if deserialised object has wrong type */ @SuppressWarnings("unchecked") // will throw CCE, see Javadoc private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); setCollection((Collection) in.readObject()); } //----------------------------------------------------------------------- // Collection interface //----------------------------------------------------------------------- @Override public boolean containsAll(final Collection coll) { final Iterator e = coll.iterator(); while (e.hasNext()) { if(!contains(e.next())) { return false; } } return true; } @Override public boolean add(final E object) { return add(object, 1); } @Override public boolean addAll(final Collection coll) { boolean changed = false; final Iterator i = coll.iterator(); while (i.hasNext()) { final boolean added = add(i.next(), 1); changed = changed || added; } return changed; } @Override public boolean remove(final Object object) { return remove(object, 1); } @Override public boolean removeAll(final Collection coll) { if (coll != null) { boolean result = false; final Iterator i = coll.iterator(); while (i.hasNext()) { final Object obj = i.next(); final boolean changed = remove(obj, getCount(obj)); result = result || changed; } return result; } else { // let the decorated bag handle the case of null argument return decorated().removeAll(null); } } @Override public boolean retainAll(final Collection coll) { if (coll != null) { boolean modified = false; final Iterator e = iterator(); while (e.hasNext()) { if (!coll.contains(e.next())) { e.remove(); modified = true; } } return modified; } else { // let the decorated bag handle the case of null argument return decorated().retainAll(null); } } //----------------------------------------------------------------------- // Bag interface //----------------------------------------------------------------------- @Override public boolean add(final E object, final int count) { decorated().add(object, count); return true; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/OrderedIterator.java100664 3232 12243235516 30677 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Iterator; /** * Defines an iterator that operates over an ordered container. Subset of {@link java.util.ListIterator}. *

* This iterator allows both forward and reverse iteration through the container. * * @param the type to iterate over * @since 3.0 * @version $Id: OrderedIterator.java 1469004 2013-04-17 17:37:03Z tn $ */ 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 container. * * @return the previous element in the iteration * @throws java.util.NoSuchElementException if the iteration is finished */ E previous(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/SortedBidiMap.java100664 4460 12243235517 30274 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Comparator; 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. * * @param the type of the keys in the map * @param the type of the values in the map * @since 3.0 * @version $Id: SortedBidiMap.java 1543255 2013-11-19 00:45:24Z ggregory $ */ 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 */ SortedBidiMap inverseBidiMap(); /** * Get the comparator used for the values in the value-to-key map aspect. * @return Comparator */ Comparator valueComparator(); } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/PredicatedSortedMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/PredicatedSortedMap.j100664 11640 12243235516 31573 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.Comparator; import java.util.SortedMap; import org.apache.commons.collections4.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 3.0 * @version $Id: PredicatedSortedMap.java 1479407 2013-05-05 22:07:53Z tn $ */ 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 the key type * @param the value type * @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 * @return a new predicated sorted map * @throws IllegalArgumentException if the map is null * @since 4.0 */ public static PredicatedSortedMap predicatedSortedMap(final SortedMap map, final Predicate keyPredicate, final 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(final SortedMap map, final Predicate keyPredicate, final Predicate valuePredicate) { super(map, keyPredicate, valuePredicate); } //----------------------------------------------------------------------- /** * Gets the map being decorated. * * @return the decorated map */ protected SortedMap getSortedMap() { return (SortedMap) map; } //----------------------------------------------------------------------- public K firstKey() { return getSortedMap().firstKey(); } public K lastKey() { return getSortedMap().lastKey(); } public Comparator comparator() { return getSortedMap().comparator(); } public SortedMap subMap(final K fromKey, final K toKey) { final SortedMap map = getSortedMap().subMap(fromKey, toKey); return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } public SortedMap headMap(final K toKey) { final SortedMap map = getSortedMap().headMap(toKey); return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } public SortedMap tailMap(final K fromKey) { final SortedMap map = getSortedMap().tailMap(fromKey); return new PredicatedSortedMap(map, keyPredicate, valuePredicate); } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractOrderedMapDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractOrderedMapDec100664 5574 12243235516 31573 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.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 3.0 * @version $Id: AbstractOrderedMapDecorator.java 1477799 2013-04-30 19:56:11Z tn $ */ public abstract class AbstractOrderedMapDecorator extends AbstractMapDecorator implements OrderedMap { /** * Constructor only used in deserialization, do not use otherwise. * @since 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(final OrderedMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ @Override protected OrderedMap decorated() { return (OrderedMap) super.decorated(); } //----------------------------------------------------------------------- public K firstKey() { return decorated().firstKey(); } public K lastKey() { return decorated().lastKey(); } public K nextKey(final K key) { return decorated().nextKey(key); } public K previousKey(final K key) { return decorated().previousKey(key); } @Override public OrderedMapIterator mapIterator() { return decorated().mapIterator(); } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/CaseInsensitiveMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/CaseInsensitiveMap.ja100664 13405 12243235516 31604 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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. *

* Before keys are added to the map or compared to other existing keys, they are converted * to all lowercase in a locale-independent fashion by using information from the Unicode * data file. *

* Null keys are supported. *

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

* Example: *


 *  Map<String, String> map = new CaseInsensitiveMap<String, String>();
 *  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}. *

* 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. In particular, you can't * use decorators like {@link ListOrderedMap} on it, which silently assume that these * contracts are fulfilled. *

* 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 3.0 * @version $Id: CaseInsensitiveMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 negative */ public CaseInsensitiveMap(final 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 negative * @throws IllegalArgumentException if the load factor is less than zero */ public CaseInsensitiveMap(final int initialCapacity, final 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(final Map map) { super(map); } //----------------------------------------------------------------------- /** * Overrides convertKey() from {@link AbstractHashedMap} to convert keys to * lower case. *

* Returns {@link AbstractHashedMap#NULL} if key is null. * * @param key the key convert * @return the converted key */ @Override protected Object convertKey(final Object key) { if (key != null) { final char[] chars = key.toString().toCharArray(); for (int i = chars.length - 1; i >= 0; i--) { chars[i] = Character.toLowerCase(Character.toUpperCase(chars[i])); } return new String(chars); } return AbstractHashedMap.NULL; } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ @Override public CaseInsensitiveMap clone() { return (CaseInsensitiveMap) super.clone(); } /** * Write the map out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractLinkedMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractLinkedMap.jav100664 47562 12243235516 31603 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import org.apache.commons.collections4.OrderedIterator; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.ResettableIterator; import org.apache.commons.collections4.iterators.EmptyOrderedIterator; import org.apache.commons.collections4.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 3.0 * @version $Id: AbstractLinkedMap.java 1533984 2013-10-20 21:12:51Z tn $ */ public abstract class AbstractLinkedMap extends AbstractHashedMap implements OrderedMap { /** Header in the linked list */ 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(final int initialCapacity, final float loadFactor, final 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 negative */ protected AbstractLinkedMap(final 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 negative * @throws IllegalArgumentException if the load factor is less than zero */ protected AbstractLinkedMap(final int initialCapacity, final 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(final 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. */ @Override protected void init() { header = 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 */ @Override public boolean containsValue(final 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. */ @Override 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 first inserted. * * @return the eldest key */ public K firstKey() { if (size == 0) { throw new NoSuchElementException("Map is empty"); } return header.after.getKey(); } /** * Gets the last key in the map, which is the most recently inserted. * * @return the most recently inserted key */ public K lastKey() { if (size == 0) { throw new NoSuchElementException("Map is empty"); } return header.before.getKey(); } /** * Gets the next key in sequence. * * @param key the key to get after * @return the next key */ public K nextKey(final Object key) { final LinkEntry entry = getEntry(key); return entry == null || entry.after == header ? null : entry.after.getKey(); } @Override protected LinkEntry getEntry(final Object key) { return (LinkEntry) super.getEntry(key); } /** * Gets the previous key in sequence. * * @param key the key to get before * @return the previous key */ public K previousKey(final Object key) { final LinkEntry entry = 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(final 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 */ @Override protected void addEntry(final HashEntry entry, final int hashIndex) { final LinkEntry link = (LinkEntry) entry; link.after = header; link.before = header.before; header.before.after = link; header.before = link; data[hashIndex] = link; } /** * 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 */ @Override protected LinkEntry createEntry(final HashEntry next, final int hashCode, final K key, final V value) { return new LinkEntry(next, hashCode, convertKey(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 */ @Override protected void removeEntry(final HashEntry entry, final int hashIndex, final HashEntry previous) { final 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 3.1 */ protected LinkEntry entryBefore(final 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 3.1 */ protected LinkEntry entryAfter(final LinkEntry entry) { return entry.after; } //----------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public OrderedMapIterator mapIterator() { if (size == 0) { return EmptyOrderedMapIterator.emptyOrderedMapIterator(); } return new LinkMapIterator(this); } /** * MapIterator implementation. */ protected static class LinkMapIterator extends LinkIterator implements OrderedMapIterator, ResettableIterator { protected LinkMapIterator(final AbstractLinkedMap parent) { super(parent); } public K next() { return super.nextEntry().getKey(); } public K previous() { return super.previousEntry().getKey(); } public K getKey() { final LinkEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } public V getValue() { final LinkEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } public V setValue(final V value) { final LinkEntry 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 */ @Override protected Iterator> createEntrySetIterator() { if (size() == 0) { return EmptyOrderedIterator.>emptyOrderedIterator(); } return new EntrySetIterator(this); } /** * EntrySet iterator. */ protected static class EntrySetIterator extends LinkIterator implements OrderedIterator>, ResettableIterator> { protected EntrySetIterator(final AbstractLinkedMap parent) { super(parent); } public Map.Entry next() { return super.nextEntry(); } public Map.Entry previous() { return super.previousEntry(); } } //----------------------------------------------------------------------- /** * Creates a key set iterator. * Subclasses can override this to return iterators with different properties. * * @return the keySet iterator */ @Override protected Iterator createKeySetIterator() { if (size() == 0) { return EmptyOrderedIterator.emptyOrderedIterator(); } return new KeySetIterator(this); } /** * KeySet iterator. */ protected static class KeySetIterator extends LinkIterator implements OrderedIterator, ResettableIterator { @SuppressWarnings("unchecked") protected KeySetIterator(final AbstractLinkedMap parent) { super((AbstractLinkedMap) parent); } public K next() { return super.nextEntry().getKey(); } public K previous() { return super.previousEntry().getKey(); } } //----------------------------------------------------------------------- /** * Creates a values iterator. * Subclasses can override this to return iterators with different properties. * * @return the values iterator */ @Override protected Iterator createValuesIterator() { if (size() == 0) { return EmptyOrderedIterator.emptyOrderedIterator(); } return new ValuesIterator(this); } /** * Values iterator. */ protected static class ValuesIterator extends LinkIterator implements OrderedIterator, ResettableIterator { @SuppressWarnings("unchecked") protected ValuesIterator(final AbstractLinkedMap parent) { super((AbstractLinkedMap) parent); } public V next() { return super.nextEntry().getValue(); } public V previous() { return super.previousEntry().getValue(); } } //----------------------------------------------------------------------- /** * LinkEntry that stores the data. *

* If you subclass AbstractLinkedMap but not LinkEntry * then you will not be able to access the protected fields. * The entryXxx() methods on AbstractLinkedMap exist * to provide the necessary access. */ protected static class LinkEntry extends HashEntry { /** The entry before this one in the order */ protected LinkEntry before; /** The entry after this one in the order */ protected LinkEntry after; /** * Constructs a new entry. * * @param next the next entry in the hash bucket sequence * @param hashCode the hash code * @param key the key * @param value the value */ protected LinkEntry(final HashEntry next, final int hashCode, final Object key, final V value) { super(next, hashCode, key, value); } } /** * Base Iterator that iterates in link order. */ protected static abstract class LinkIterator { /** The parent map */ protected final AbstractLinkedMap parent; /** The current (last returned) entry */ protected LinkEntry last; /** The next entry */ protected LinkEntry next; /** The modification count expected */ protected int expectedModCount; protected LinkIterator(final 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(); } final 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; } @Override public String toString() { if (last != null) { return "Iterator[" + last.getKey() + "=" + last.getValue() + "]"; } return "Iterator[]"; } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/ReferenceMap.java100664 20764 12243235516 30743 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.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 collector 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 3.0 (previously in main package v2.1) * @version $Id: ReferenceMap.java 1477799 2013-04-30 19:56:11Z tn $ */ 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(ReferenceStrength.HARD, ReferenceStrength.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 AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} */ public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength 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 AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param purgeValues should the value be automatically purged when the * key is garbage collected */ public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength valueType, final 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 AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map */ public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity, final 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 AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK 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(final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity, final float loadFactor, final boolean purgeValues) { super(keyType, valueType, capacity, loadFactor, purgeValues); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/MultiValueMap.java100664 47011 12243235516 31126 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; 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.collections4.CollectionUtils; import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.FunctorException; import org.apache.commons.collections4.MultiMap; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.iterators.EmptyIterator; import org.apache.commons.collections4.iterators.IteratorChain; import org.apache.commons.collections4.iterators.LazyIteratorChain; import org.apache.commons.collections4.iterators.TransformIterator; /** * 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. * * @since 3.2 * @version $Id: MultiValueMap.java 1542763 2013-11-17 17:10:33Z tn $ */ public class MultiValueMap extends AbstractMapDecorator implements MultiMap, Serializable { /** Serialization version */ private static final long serialVersionUID = -2214159910087182007L; /** The factory for creating value collections. */ private final Factory> collectionFactory; /** The cached values. */ private transient Collection valuesView; /** * Creates a map which wraps the given map and * maps keys to ArrayLists. * * @param the key type * @param the value type * @param map the map to wrap * @return a new multi-value map * @since 4.0 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static MultiValueMap multiValueMap(final Map> map) { return MultiValueMap. multiValueMap((Map) map, ArrayList.class); } /** * Creates a map which decorates the given map and * maps keys to collections of type collectionClass. * * @param the key type * @param the value type * @param the collection class type * @param map the map to wrap * @param collectionClass the type of the collection class * @return a new multi-value map * @since 4.0 */ public static > MultiValueMap multiValueMap(final Map map, final 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 the key type * @param the value type * @param the collection class type * @param map the map to decorate * @param collectionFactory the collection factory (must return a Collection object). * @return a new multi-value map * @since 4.0 */ public static > MultiValueMap multiValueMap(final Map map, final Factory collectionFactory) { return new MultiValueMap(map, collectionFactory); } //----------------------------------------------------------------------- /** * Creates a MultiValueMap based on a HashMap and * storing the multiple values in an ArrayList. */ @SuppressWarnings({ "unchecked", "rawtypes" }) 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 the collection class type * @param map the map to decorate * @param collectionFactory the collection factory which must return a Collection instance */ @SuppressWarnings("unchecked") protected > MultiValueMap(final Map map, final Factory collectionFactory) { super((Map) map); if (collectionFactory == null) { throw new IllegalArgumentException("The factory must not be null"); } this.collectionFactory = collectionFactory; } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since 4.0 */ private void writeObject(final 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 4.0 */ @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); // (1) } //----------------------------------------------------------------------- /** * Clear the map. */ @Override 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(); // } decorated().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 subsequent get(key). * * @param key the key to remove from * @param value the value to remove * @return {@code true} if the mapping was removed, {@code false} otherwise */ public boolean removeMapping(final Object key, final Object value) { final Collection valuesForKey = getCollection(key); if (valuesForKey == null) { return false; } final boolean removed = valuesForKey.remove(value); if (removed == false) { return false; } if (valuesForKey.isEmpty()) { remove(key); } return true; } /** * 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 */ @Override @SuppressWarnings("unchecked") public boolean containsValue(final Object value) { final Set> pairs = decorated().entrySet(); if (pairs != null) { for (final Map.Entry entry : pairs) { if (((Collection) entry.getValue()).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 */ @Override @SuppressWarnings("unchecked") public Object put(final K key, final Object value) { boolean result = false; Collection coll = getCollection(key); if (coll == null) { coll = createCollection(1); // might produce a non-empty collection coll.add((V) value); if (coll.size() > 0) { // only add if non-zero size to maintain class state decorated().put(key, coll); result = true; // map definitely changed } } else { result = coll.add((V) 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) */ @Override @SuppressWarnings("unchecked") public void putAll(final Map map) { if (map instanceof MultiMap) { for (final Map.Entry entry : ((MultiMap) map).entrySet()) { putAll(entry.getKey(), (Collection) entry.getValue()); } } else { for (final Map.Entry entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } } /** * {@inheritDoc} *

* NOTE: the returned Entry objects will contain as value a {@link Collection} * of all values that are mapped to the given key. To get a "flattened" version * of all mappings contained in this map, use {@link #iterator()}. * * @see #iterator() */ @Override public Set> entrySet() { return super.entrySet(); } /** * 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 */ @Override @SuppressWarnings("unchecked") public Collection values() { final Collection vs = valuesView; return (Collection) (vs != null ? vs : (valuesView = new Values())); } /** * Checks whether the collection at the specified key contains the value. * * @param key the key to search for * @param value the value to search for * @return true if the map contains the value */ public boolean containsValue(final Object key, final Object value) { final 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 */ @SuppressWarnings("unchecked") public Collection getCollection(final Object key) { return (Collection) decorated().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(final Object key) { final 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(final K key, final Collection values) { if (values == null || values.size() == 0) { return false; } boolean result = false; Collection coll = getCollection(key); if (coll == null) { coll = createCollection(values.size()); // might produce a non-empty collection coll.addAll(values); if (coll.size() > 0) { // only add if non-zero size to maintain class state decorated().put(key, coll); result = true; // map definitely changed } } else { result = coll.addAll(values); } return result; } /** * 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(final Object key) { if (!containsKey(key)) { return EmptyIterator.emptyIterator(); } return new ValuesIterator(key); } /** * Gets an iterator for all mappings stored in this {@link MultiValueMap}. *

* The iterator will return multiple Entry objects with the same key * if there are multiple values mapped to this key. *

* NOTE: calling {@link java.util.Map.Entry#setValue(Object)} on any of the returned * elements will result in a {@link UnsupportedOperationException}. * * @return the iterator of all mappings in this map * @since 4.0 */ public Iterator> iterator() { final Collection allKeys = new ArrayList(keySet()); final Iterator keyIterator = allKeys.iterator(); return new LazyIteratorChain>() { @Override protected Iterator> nextIterator(int count) { if ( ! keyIterator.hasNext() ) { return null; } final K key = keyIterator.next(); final Transformer> transformer = new Transformer>() { public Entry transform(final V input) { return new Entry() { public K getKey() { return key; } public V getValue() { return input; } public V setValue(V value) { throw new UnsupportedOperationException(); } }; } }; return new TransformIterator>(new ValuesIterator(key), transformer); } }; } /** * 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; for (final Object v : decorated().values()) { total += CollectionUtils.size(v); } 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(final int size) { return collectionFactory.create(); } //----------------------------------------------------------------------- /** * Inner class that provides the values view. */ private class Values extends AbstractCollection { @Override public Iterator iterator() { final IteratorChain chain = new IteratorChain(); for (final K k : keySet()) { chain.addIterator(new ValuesIterator(k)); } return chain; } @Override public int size() { return totalSize(); } @Override 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(final 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 V next() { return iterator.next(); } } /** * Inner class that provides a simple reflection factory. */ private static class ReflectionFactory> implements Factory, Serializable { /** Serialization version */ private static final long serialVersionUID = 2986114157496788874L; private final Class clazz; public ReflectionFactory(final Class clazz) { this.clazz = clazz; } public T create() { try { return clazz.newInstance(); } catch (final Exception ex) { throw new FunctorException("Cannot instantiate class: " + clazz, ex); } } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/LRUMap.java100664 43022 12243235516 27477 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.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. *

* A somewhat subtle ramification of the least recently used * algorithm is that calls to {@link #get(Object)} stand a very good chance * of modifying the map's iteration order and thus invalidating any * iterators currently in use. It is therefore suggested that iterations * over an {@link LRUMap} instance access entry values only through a * {@link org.apache.commons.collections4.MapIterator MapIterator} or {@link #entrySet()} iterator. *

* 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 3.0 (previously in main package v1.0) * @version $Id: LRUMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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(final 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 3.1 */ public LRUMap(final int maxSize, final 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 * @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(final int maxSize, final 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 ma * @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 3.1 */ public LRUMap(final int maxSize, final float loadFactor, final 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(final 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 3.1 */ public LRUMap(final Map map, final 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 */ @Override public V get(final Object key) { final LinkEntry entry = 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(final LinkEntry entry) { if (entry.after != header) { modCount++; // remove if(entry.before == null) { throw new IllegalStateException("Entry.before is null." + " Please check that your keys are immutable, and that you have used synchronization properly." + " If so, then please report this to dev@commons.apache.org as a bug."); } 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 dev@commons.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 */ @Override protected void updateEntry(final HashEntry entry, final V newValue) { moveToMRU((LinkEntry) entry); // handles modCount entry.setValue(newValue); } /** * Adds a new key-value mapping into this map. *

* This implementation checks the LRU size and determines whether to * discard an entry or not using {@link #removeLRU(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 */ @Override protected void addMapping(final int hashIndex, final int hashCode, final K key, final V 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 dev@commons.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 dev@commons.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(final LinkEntry entry, final int hashIndex, final int hashCode, final K key, final V value) { // find the entry before the entry specified in the hash table // remember that the parameters (except the first) refer to the new entry, // not the old one try { final int removeIndex = hashIndex(entry.hashCode, data.length); final 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 dev@commons.apache.org as a bug."); } // reuse the entry modCount++; removeEntry(entry, removeIndex, previous); reuseEntry(entry, hashIndex, hashCode, key, value); addEntry(entry, hashIndex); } catch (final 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 dev@commons.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 * @return {@code true} */ protected boolean removeLRU(final 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 3.1 */ public boolean isScanUntilRemovable() { return scanUntilRemovable; } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ @Override public LRUMap clone() { return (LRUMap) super.clone(); } /** * Write the map out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } /** * Writes the data necessary for put() to work in deserialization. * * @param out the output stream * @throws IOException if an error occurs while writing to the stream */ @Override protected void doWriteObject(final ObjectOutputStream out) throws IOException { out.writeInt(maxSize); super.doWriteObject(out); } /** * Reads the data necessary for put() to work in the superclass. * * @param in the input stream * @throws IOException if an error occurs while reading from the stream * @throws ClassNotFoundException if an object read from the stream can not be loaded */ @Override protected void doReadObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { maxSize = in.readInt(); super.doReadObject(in); } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/FixedSizeSortedMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/FixedSizeSortedMap.ja100664 14240 12243235516 31561 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 java.util.SortedMap; import org.apache.commons.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.BoundedMap; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.collection.UnmodifiableCollection; /** * 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 3.0 * @version $Id: FixedSizeSortedMap.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public class FixedSizeSortedMap extends AbstractSortedMapDecorator implements BoundedMap, Serializable { /** Serialization version */ private static final long serialVersionUID = 3126019624511683653L; /** * Factory method to create a fixed size sorted map. * * @param the key type * @param the value type * @param map the map to decorate, must not be null * @return a new fixed size sorted map * @throws IllegalArgumentException if map is null * @since 4.0 */ public static FixedSizeSortedMap fixedSizeSortedMap(final 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(final 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(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * Read the map in using a custom routine. */ @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); // (1) } //----------------------------------------------------------------------- @Override public V put(final K key, final V value) { if (map.containsKey(key) == false) { throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); } return map.put(key, value); } @Override public void putAll(final Map mapToCopy) { if (CollectionUtils.isSubCollection(mapToCopy.keySet(), keySet())) { throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); } map.putAll(mapToCopy); } @Override public void clear() { throw new UnsupportedOperationException("Map is fixed size"); } @Override public V remove(final Object key) { throw new UnsupportedOperationException("Map is fixed size"); } @Override public Set> entrySet() { return UnmodifiableSet.unmodifiableSet(map.entrySet()); } @Override public Set keySet() { return UnmodifiableSet.unmodifiableSet(map.keySet()); } @Override public Collection values() { return UnmodifiableCollection.unmodifiableCollection(map.values()); } //----------------------------------------------------------------------- @Override public SortedMap subMap(final K fromKey, final K toKey) { return new FixedSizeSortedMap(getSortedMap().subMap(fromKey, toKey)); } @Override public SortedMap headMap(final K toKey) { return new FixedSizeSortedMap(getSortedMap().headMap(toKey)); } @Override public SortedMap tailMap(final K fromKey) { return new FixedSizeSortedMap(getSortedMap().tailMap(fromKey)); } public boolean isFull() { return true; } public int maxSize() { return size(); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/FixedSizeMap.java100664 13324 12243235516 30731 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.BoundedMap; import org.apache.commons.collections4.collection.UnmodifiableCollection; /** * 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 3.0 * @version $Id: FixedSizeMap.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public class FixedSizeMap extends AbstractMapDecorator implements BoundedMap, Serializable { /** Serialization version */ private static final long serialVersionUID = 7450927208116179316L; /** * Factory method to create a fixed size map. * * @param the key type * @param the value type * @param map the map to decorate, must not be null * @return a new fixed size map * @throws IllegalArgumentException if map is null * @since 4.0 */ public static FixedSizeMap fixedSizeMap(final 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(final Map map) { super(map); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since 3.1 */ private void writeObject(final 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 3.1 */ @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); // (1) } //----------------------------------------------------------------------- @Override public V put(final K key, final V value) { if (map.containsKey(key) == false) { throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); } return map.put(key, value); } @Override public void putAll(final Map mapToCopy) { for (final K key : mapToCopy.keySet()) { if (!containsKey(key)) { throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size"); } } map.putAll(mapToCopy); } @Override public void clear() { throw new UnsupportedOperationException("Map is fixed size"); } @Override public V remove(final Object key) { throw new UnsupportedOperationException("Map is fixed size"); } @Override public Set> entrySet() { final Set> set = map.entrySet(); // unmodifiable set will still allow modification via Map.Entry objects return UnmodifiableSet.unmodifiableSet(set); } @Override public Set keySet() { final Set set = map.keySet(); return UnmodifiableSet.unmodifiableSet(set); } @Override public Collection values() { final Collection coll = map.values(); return UnmodifiableCollection.unmodifiableCollection(coll); } public boolean isFull() { return true; } public int maxSize() { return size(); } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/EntrySetToMapIteratorAdapter.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/EntrySetToMapIterator100664 5470 12243235516 31674 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.ResettableIterator; /** * Adapts a Map entrySet to the MapIterator interface. * * @since 4.0 * @version $Id: EntrySetToMapIteratorAdapter.java 1494296 2013-06-18 20:54:29Z tn $ */ public class EntrySetToMapIteratorAdapter implements MapIterator, ResettableIterator { /** The adapted Map entry Set. */ Set> entrySet; /** The resettable iterator in use. */ transient Iterator> iterator; /** The currently positioned Map entry. */ transient Map.Entry entry; /** * Create a new EntrySetToMapIteratorAdapter. * @param entrySet the entrySet to adapt */ public EntrySetToMapIteratorAdapter(final Set> entrySet) { this.entrySet = entrySet; reset(); } /** * {@inheritDoc} */ public K getKey() { return current().getKey(); } /** * {@inheritDoc} */ public V getValue() { return current().getValue(); } /** * {@inheritDoc} */ public V setValue(final V value) { return current().setValue(value); } /** * {@inheritDoc} */ public boolean hasNext() { return iterator.hasNext(); } /** * {@inheritDoc} */ public K next() { entry = iterator.next(); return getKey(); } /** * {@inheritDoc} */ public synchronized void reset() { iterator = entrySet.iterator(); } /** * {@inheritDoc} */ public void remove() { iterator.remove(); entry = null; } /** * Get the currently active entry. * @return Map.Entry */ protected synchronized Map.Entry current() { if (entry == null) { throw new IllegalStateException(); } return entry; } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/ReferenceIdentityMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/ReferenceIdentityMap.100664 24340 12243235516 31605 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.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 collector 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 3.0 (previously in main package v2.1) * @version $Id: ReferenceIdentityMap.java 1477799 2013-04-30 19:56:11Z tn $ */ 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(ReferenceStrength.HARD, ReferenceStrength.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 AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} */ public ReferenceIdentityMap(final ReferenceStrength keyType, final ReferenceStrength 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 AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param purgeValues should the value be automatically purged when the * key is garbage collected */ public ReferenceIdentityMap(final ReferenceStrength keyType, final ReferenceStrength valueType, final 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 AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map */ public ReferenceIdentityMap(final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity, final 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 AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD}, * {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT}, * {@link AbstractReferenceMap.ReferenceStrength#WEAK 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(final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity, final float loadFactor, final 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 */ @Override protected int hash(final 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 */ @Override protected int hashEntry(final Object key, final 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 */ @Override protected boolean isEqualKey(final Object key1, Object key2) { key2 = isKeyType(ReferenceStrength.HARD) ? key2 : ((Reference) key2).get(); 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 */ @Override protected boolean isEqualValue(final Object value1, final Object value2) { return value1 == value2; } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/TransformedMap.java100664 22002 12243235516 31314 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.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. *

* @see org.apache.commons.collections4.splitmap.TransformedSplitMap * * @since 3.0 * @version $Id: TransformedMap.java 1491944 2013-06-11 20:29:22Z tn $ */ 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. * Contrast this with {@link #transformedMap(Map, Transformer, Transformer)}. * * @param the key type * @param the value type * @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 * @return a new transformed map * @throws IllegalArgumentException if map is null * @since 4.0 */ public static TransformedMap transformingMap(final Map map, final Transformer keyTransformer, final 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. * Contrast this with {@link #transformingMap(Map, Transformer, Transformer)}. * * @param the key type * @param the value type * @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 * @return a new transformed map * @throws IllegalArgumentException if map is null * @since 4.0 */ public static TransformedMap transformedMap(final Map map, final Transformer keyTransformer, final Transformer valueTransformer) { final TransformedMap decorated = new TransformedMap(map, keyTransformer, valueTransformer); if (map.size() > 0) { final Map transformed = decorated.transformMap(map); decorated.clear(); decorated.decorated().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(final Map map, final Transformer keyTransformer, final 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 3.1 */ private void writeObject(final 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 3.1 */ @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); // (1) } //----------------------------------------------------------------------- /** * Transforms a key. *

* The transformer itself may throw an exception if necessary. * * @param object the object to transform * @return the transformed object */ protected K transformKey(final K 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 * @return the transformed object */ protected V transformValue(final V 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 * @return the transformed object */ @SuppressWarnings("unchecked") protected Map transformMap(final Map map) { if (map.isEmpty()) { return (Map) map; } final Map result = new LinkedMap(map.size()); for (final Map.Entry entry : map.entrySet()) { 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 3.1 */ @Override protected V checkSetValue(final V 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 3.1 */ @Override protected boolean isSetValueChecking() { return valueTransformer != null; } //----------------------------------------------------------------------- @Override public V put(K key, V value) { key = transformKey(key); value = transformValue(value); return decorated().put(key, value); } @Override public void putAll(Map mapToCopy) { mapToCopy = transformMap(mapToCopy); decorated().putAll(mapToCopy); } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/UnmodifiableSortedMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/UnmodifiableSortedMap100664 12665 12243235516 31705 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.collection.UnmodifiableCollection; /** * Decorates another SortedMap to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableSortedMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 the key type * @param the value type * @param map the map to decorate, must not be null * @return a new unmodifiable sorted map * @throws IllegalArgumentException if map is null * @since 4.0 */ public static SortedMap unmodifiableSortedMap(final SortedMap map) { if (map instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final SortedMap tmpMap = (SortedMap) map; return tmpMap; } 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 */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableSortedMap(final SortedMap map) { super((SortedMap) map); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since 3.1 */ private void writeObject(final 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 3.1 */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- @Override public void clear() { throw new UnsupportedOperationException(); } @Override public V put(final K key, final V value) { throw new UnsupportedOperationException(); } @Override public void putAll(final Map mapToCopy) { throw new UnsupportedOperationException(); } @Override public V remove(final Object key) { throw new UnsupportedOperationException(); } @Override public Set> entrySet() { return UnmodifiableEntrySet.unmodifiableEntrySet(super.entrySet()); } @Override public Set keySet() { return UnmodifiableSet.unmodifiableSet(super.keySet()); } @Override public Collection values() { return UnmodifiableCollection.unmodifiableCollection(super.values()); } //----------------------------------------------------------------------- @Override public K firstKey() { return decorated().firstKey(); } @Override public K lastKey() { return decorated().lastKey(); } @Override public Comparator comparator() { return decorated().comparator(); } @Override public SortedMap subMap(final K fromKey, final K toKey) { return new UnmodifiableSortedMap(decorated().subMap(fromKey, toKey)); } @Override public SortedMap headMap(final K toKey) { return new UnmodifiableSortedMap(decorated().headMap(toKey)); } @Override public SortedMap tailMap(final K fromKey) { return new UnmodifiableSortedMap(decorated().tailMap(fromKey)); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/LinkedMap.java100664 23324 12243235516 30246 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.iterators.UnmodifiableIterator; import org.apache.commons.collections4.iterators.UnmodifiableListIterator; import org.apache.commons.collections4.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.collections4.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 3.0 * @version $Id: LinkedMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 negative */ public LinkedMap(final 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 negative * @throws IllegalArgumentException if the load factor is less than zero */ public LinkedMap(final int initialCapacity, final 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(final Map map) { super(map); } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ @Override public LinkedMap clone() { return (LinkedMap) super.clone(); } /** * Write the map out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } //----------------------------------------------------------------------- /** * Gets the key at the specified index. * * @param index the index to retrieve * @return the key at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public K get(final 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 * @throws IndexOutOfBoundsException if the index is invalid */ public V getValue(final 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 V remove(final 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 { private final LinkedMap parent; LinkedMapList(final LinkedMap parent) { this.parent = parent; } @Override public int size() { return parent.size(); } @Override public K get(final int index) { return parent.get(index); } @Override public boolean contains(final Object obj) { return parent.containsKey(obj); } @Override public int indexOf(final Object obj) { return parent.indexOf(obj); } @Override public int lastIndexOf(final Object obj) { return parent.indexOf(obj); } @Override public boolean containsAll(final Collection coll) { return parent.keySet().containsAll(coll); } @Override public K remove(final int index) { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object obj) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { return parent.keySet().toArray(); } @Override public T[] toArray(final T[] array) { return parent.keySet().toArray(array); } @Override public Iterator iterator() { return UnmodifiableIterator.unmodifiableIterator(parent.keySet().iterator()); } @Override public ListIterator listIterator() { return UnmodifiableListIterator.umodifiableListIterator(super.listIterator()); } @Override public ListIterator listIterator(final int fromIndex) { return UnmodifiableListIterator.umodifiableListIterator(super.listIterator(fromIndex)); } @Override public List subList(final int fromIndexInclusive, final int toIndexExclusive) { return UnmodifiableList.unmodifiableList(super.subList(fromIndexInclusive, toIndexExclusive)); } } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractIterableMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractIterableMap.j100664 2503 12243235516 31537 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.MapIterator; /** * Provide a basic {@link IterableMap} implementation. * * @since 4.0 * @version $Id: AbstractIterableMap.java 1469004 2013-04-17 17:37:03Z tn $ */ public abstract class AbstractIterableMap implements IterableMap { /** * {@inheritDoc} */ public MapIterator mapIterator() { return new EntrySetToMapIteratorAdapter(entrySet()); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/MultiKeyMap.java100664 103536 12243235516 30627 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.MapIterator; import org.apache.commons.collections4.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.multiKeyMap(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 3.1 * @version $Id: MultiKeyMap.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public class MultiKeyMap extends AbstractMapDecorator, V> implements Serializable, Cloneable { /** Serialisation version */ private static final long serialVersionUID = -1788199231038721040L; //----------------------------------------------------------------------- /** * Decorates the specified map to add the MultiKeyMap API and fast query. * The map must not be null and must be empty. * * @param the key type * @param the value type * @param map the map to decorate, not null * @return a new multi key map * @throws IllegalArgumentException if the map is null or not empty * @since 4.0 */ public static MultiKeyMap multiKeyMap(final AbstractHashedMap, V> map) { if (map == null) { throw new IllegalArgumentException("Map must not be null"); } if (map.size() > 0) { throw new IllegalArgumentException("Map must be empty"); } return new MultiKeyMap(map); } //----------------------------------------------------------------------- /** * Constructs a new MultiKeyMap that decorates a HashedMap. */ public MultiKeyMap() { this(new HashedMap, V>()); } /** * Constructor that decorates the specified map and is called from * {@link #multiKeyMap(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(final AbstractHashedMap, V> map) { super(map); 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 V get(final Object key1, final Object key2) { final int hashCode = hash(key1, key2); AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().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(final Object key1, final Object key2) { final int hashCode = hash(key1, key2); AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().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 V put(final K key1, final K key2, final V value) { final int hashCode = hash(key1, key2); final int index = decorated().hashIndex(hashCode, decorated().data.length); AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2)) { final V oldValue = entry.getValue(); decorated().updateEntry(entry, value); return oldValue; } entry = entry.next; } decorated().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 * @since 4.0 (previous name: remove(Object, Object)) */ public V removeMultiKey(final Object key1, final Object key2) { final int hashCode = hash(key1, key2); final int index = decorated().hashIndex(hashCode, decorated().data.length); AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; AbstractHashedMap.HashEntry, V> previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2)) { final V oldValue = entry.getValue(); decorated().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(final Object key1, final 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(final AbstractHashedMap.HashEntry, V> entry, final Object key1, final Object key2) { final MultiKey multi = entry.getKey(); return multi.size() == 2 && (key1 == multi.getKey(0) || key1 != null && key1.equals(multi.getKey(0))) && (key2 == multi.getKey(1) || key1 != 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 V get(final Object key1, final Object key2, final Object key3) { final int hashCode = hash(key1, key2, key3); AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().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(final Object key1, final Object key2, final Object key3) { final int hashCode = hash(key1, key2, key3); AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().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 V put(final K key1, final K key2, final K key3, final V value) { final int hashCode = hash(key1, key2, key3); final int index = decorated().hashIndex(hashCode, decorated().data.length); AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3)) { final V oldValue = entry.getValue(); decorated().updateEntry(entry, value); return oldValue; } entry = entry.next; } decorated().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 * @since 4.0 (previous name: remove(Object, Object, Object)) */ public V removeMultiKey(final Object key1, final Object key2, final Object key3) { final int hashCode = hash(key1, key2, key3); final int index = decorated().hashIndex(hashCode, decorated().data.length); AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; AbstractHashedMap.HashEntry, V> previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3)) { final V oldValue = entry.getValue(); decorated().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(final Object key1, final Object key2, final 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(final AbstractHashedMap.HashEntry, V> entry, final Object key1, final Object key2, final Object key3) { final MultiKey multi = entry.getKey(); return multi.size() == 3 && (key1 == multi.getKey(0) || key1 != null && key1.equals(multi.getKey(0))) && (key2 == multi.getKey(1) || key2 != null && key2.equals(multi.getKey(1))) && (key3 == multi.getKey(2) || key3 != 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 V get(final Object key1, final Object key2, final Object key3, final Object key4) { final int hashCode = hash(key1, key2, key3, key4); AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().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(final Object key1, final Object key2, final Object key3, final Object key4) { final int hashCode = hash(key1, key2, key3, key4); AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().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 V put(final K key1, final K key2, final K key3, final K key4, final V value) { final int hashCode = hash(key1, key2, key3, key4); final int index = decorated().hashIndex(hashCode, decorated().data.length); AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4)) { final V oldValue = entry.getValue(); decorated().updateEntry(entry, value); return oldValue; } entry = entry.next; } decorated().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 * @since 4.0 (previous name: remove(Object, Object, Object, Object)) */ public V removeMultiKey(final Object key1, final Object key2, final Object key3, final Object key4) { final int hashCode = hash(key1, key2, key3, key4); final int index = decorated().hashIndex(hashCode, decorated().data.length); AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; AbstractHashedMap.HashEntry, V> previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4)) { final V oldValue = entry.getValue(); decorated().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(final Object key1, final Object key2, final Object key3, final 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(final AbstractHashedMap.HashEntry, V> entry, final Object key1, final Object key2, final Object key3, final Object key4) { final MultiKey multi = entry.getKey(); return multi.size() == 4 && (key1 == multi.getKey(0) || key1 != null && key1.equals(multi.getKey(0))) && (key2 == multi.getKey(1) || key2 != null && key2.equals(multi.getKey(1))) && (key3 == multi.getKey(2) || key3 != null && key3.equals(multi.getKey(2))) && (key4 == multi.getKey(3) || key4 != 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 V get(final Object key1, final Object key2, final Object key3, final Object key4, final Object key5) { final int hashCode = hash(key1, key2, key3, key4, key5); AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().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(final Object key1, final Object key2, final Object key3, final Object key4, final Object key5) { final int hashCode = hash(key1, key2, key3, key4, key5); AbstractHashedMap.HashEntry, V> entry = decorated().data[decorated().hashIndex(hashCode, decorated().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 V put(final K key1, final K key2, final K key3, final K key4, final K key5, final V value) { final int hashCode = hash(key1, key2, key3, key4, key5); final int index = decorated().hashIndex(hashCode, decorated().data.length); AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4, key5)) { final V oldValue = entry.getValue(); decorated().updateEntry(entry, value); return oldValue; } entry = entry.next; } decorated().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 * @since 4.0 (previous name: remove(Object, Object, Object, Object, Object)) */ public V removeMultiKey(final Object key1, final Object key2, final Object key3, final Object key4, final Object key5) { final int hashCode = hash(key1, key2, key3, key4, key5); final int index = decorated().hashIndex(hashCode, decorated().data.length); AbstractHashedMap.HashEntry, V> entry = decorated().data[index]; AbstractHashedMap.HashEntry, V> previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(entry, key1, key2, key3, key4, key5)) { final V oldValue = entry.getValue(); decorated().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(final Object key1, final Object key2, final Object key3, final Object key4, final 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(final AbstractHashedMap.HashEntry, V> entry, final Object key1, final Object key2, final Object key3, final Object key4, final Object key5) { final MultiKey multi = entry.getKey(); return multi.size() == 5 && (key1 == multi.getKey(0) || key1 != null && key1.equals(multi.getKey(0))) && (key2 == multi.getKey(1) || key2 != null && key2.equals(multi.getKey(1))) && (key3 == multi.getKey(2) || key3 != null && key3.equals(multi.getKey(2))) && (key4 == multi.getKey(3) || key4 != null && key4.equals(multi.getKey(3))) && (key5 == multi.getKey(4) || key5 != 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(final Object key1) { boolean modified = false; final MapIterator, V> it = mapIterator(); while (it.hasNext()) { final MultiKey multi = 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(final Object key1, final Object key2) { boolean modified = false; final MapIterator, V> it = mapIterator(); while (it.hasNext()) { final MultiKey multi = 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(final Object key1, final Object key2, final Object key3) { boolean modified = false; final MapIterator, V> it = mapIterator(); while (it.hasNext()) { final MultiKey multi = 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(final Object key1, final Object key2, final Object key3, final Object key4) { boolean modified = false; final MapIterator, V> it = mapIterator(); while (it.hasNext()) { final MultiKey multi = 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(final MultiKey key) { if (key == null) { throw new NullPointerException("Key must not be null"); } } /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ @SuppressWarnings("unchecked") @Override public MultiKeyMap clone() { try { return (MultiKeyMap) super.clone(); } catch (final CloneNotSupportedException e) { throw new InternalError(); } } /** * 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 */ @Override public V put(final MultiKey key, final V value) { checkKey(key); return super.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 */ @Override public void putAll(final Map, ? extends V> mapToCopy) { for (final MultiKey key : mapToCopy.keySet()) { checkKey(key); } super.putAll(mapToCopy); } //----------------------------------------------------------------------- @Override public MapIterator, V> mapIterator() { return decorated().mapIterator(); } /** * {@inheritDoc} */ @Override protected AbstractHashedMap, V> decorated() { return (AbstractHashedMap, V>) super.decorated(); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(final 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 */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map, V>) in.readObject(); } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractHashedMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractHashedMap.jav100664 133572 12243235516 31606 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.IterableMap; import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.iterators.EmptyIterator; import org.apache.commons.collections4.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 3.0 * @version $Id: AbstractHashedMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 */ transient float loadFactor; /** The size of the map */ transient int size; /** Map entries */ transient HashEntry[] data; /** Size at which to rehash */ transient int threshold; /** Modification count for iterators */ transient int modCount; /** Entry set */ transient EntrySet entrySet; /** Key set */ transient KeySet keySet; /** Values */ 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 */ @SuppressWarnings("unchecked") protected AbstractHashedMap(final int initialCapacity, final float loadFactor, final 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 negative */ protected AbstractHashedMap(final 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 negative * @throws IllegalArgumentException if the load factor is less than or equal to zero */ @SuppressWarnings("unchecked") protected AbstractHashedMap(int initialCapacity, final float loadFactor) { super(); if (initialCapacity < 0) { throw new IllegalArgumentException("Initial capacity must be a non negative number"); } 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(final 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 */ @Override public V get(Object key) { key = convertKey(key); final 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 */ @Override public int size() { return size; } /** * Checks whether the map is currently empty. * * @return true if the map is currently size zero */ @Override 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 */ @Override public boolean containsKey(Object key) { key = convertKey(key); final 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 */ @Override public boolean containsValue(final Object value) { if (value == null) { for (final HashEntry element : data) { HashEntry entry = element; while (entry != null) { if (entry.getValue() == null) { return true; } entry = entry.next; } } } else { for (final HashEntry element : data) { HashEntry entry = element; 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 */ @Override public V put(final K key, final V value) { final Object convertedKey = convertKey(key); final int hashCode = hash(convertedKey); final int index = hashIndex(hashCode, data.length); HashEntry entry = data[index]; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(convertedKey, entry.key)) { final V oldValue = entry.getValue(); updateEntry(entry, value); return oldValue; } entry = entry.next; } addMapping(index, hashCode, key, value); return null; } /** * Puts all the values from the specified map into this map. *

* This implementation iterates around the specified map and * uses {@link #put(Object, Object)}. * * @param map the map to add * @throws NullPointerException if the map is null */ @Override public void putAll(final Map map) { _putAll(map); } /** * Puts all the values from the specified map into this map. *

* This implementation iterates around the specified map and * uses {@link #put(Object, Object)}. *

* It is private to allow the constructor to still call it * even when putAll is overriden. * * @param map the map to add * @throws NullPointerException if the map is null */ private void _putAll(final Map map) { final int mapSize = map.size(); if (mapSize == 0) { return; } final int newSize = (int) ((size + mapSize) / loadFactor + 1); ensureCapacity(calculateNewCapacity(newSize)); for (final Map.Entry entry: map.entrySet()) { 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 */ @Override public V remove(Object key) { key = convertKey(key); final int hashCode = hash(key); final int index = hashIndex(hashCode, data.length); HashEntry entry = data[index]; HashEntry previous = null; while (entry != null) { if (entry.hashCode == hashCode && isEqualKey(key, entry.key)) { final V oldValue = entry.getValue(); removeMapping(entry, index, previous); return oldValue; } previous = entry; entry = entry.next; } return null; } /** * Clears the map, resetting the size to zero and nullifying references * to avoid garbage collection issues. */ @Override public void clear() { modCount++; final 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(final 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(final 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(final Object key1, final 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(final Object value1, final 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(final int hashCode, final 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); final 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(final HashEntry entry, final V newValue) { entry.setValue(newValue); } /** * Reuses an existing key-value mapping, storing completely new data. *

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

* This implementation calls createEntry(), addEntry() * and checkCapacity(). * It also handles changes to modCount and size. * Subclasses could override to fully control adds to the map. * * @param hashIndex the index into the data array to store at * @param hashCode the hash code of the key to add * @param key the key to add * @param value the value to add */ protected void addMapping(final int hashIndex, final int hashCode, final K key, final V value) { modCount++; final 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(final HashEntry next, final int hashCode, final K key, final V value) { return new HashEntry(next, hashCode, convertKey(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(final HashEntry entry, final 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(final HashEntry entry, final int hashIndex, final 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(final HashEntry entry, final int hashIndex, final 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(final 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) { final 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) */ @SuppressWarnings("unchecked") protected void ensureCapacity(final int newCapacity) { final int oldCapacity = data.length; if (newCapacity <= oldCapacity) { return; } if (size == 0) { threshold = calculateThreshold(newCapacity, loadFactor); data = new HashEntry[newCapacity]; } else { final HashEntry oldEntries[] = data; final 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 { final HashEntry next = entry.next; final 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(final 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(final int newCapacity, final 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 3.1 */ protected HashEntry entryNext(final 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 3.1 */ protected int entryHashCode(final 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 3.1 */ protected K entryKey(final HashEntry entry) { return entry.getKey(); } /** * 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 3.1 */ protected V entryValue(final HashEntry entry) { return entry.getValue(); } //----------------------------------------------------------------------- /** * 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.emptyMapIterator(); } return new HashMapIterator(this); } /** * MapIterator implementation. */ protected static class HashMapIterator extends HashIterator implements MapIterator { protected HashMapIterator(final AbstractHashedMap parent) { super(parent); } public K next() { return super.nextEntry().getKey(); } public K getKey() { final HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } public V getValue() { final HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } public V setValue(final V value) { final 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 */ @Override 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.>emptyIterator(); } return new EntrySetIterator(this); } /** * EntrySet implementation. */ protected static class EntrySet extends AbstractSet> { /** The parent map */ private final AbstractHashedMap parent; protected EntrySet(final AbstractHashedMap parent) { super(); this.parent = parent; } @Override public int size() { return parent.size(); } @Override public void clear() { parent.clear(); } @Override public boolean contains(final Object entry) { if (entry instanceof Map.Entry) { final Map.Entry e = (Map.Entry) entry; final Entry match = parent.getEntry(e.getKey()); return match != null && match.equals(e); } return false; } @Override public boolean remove(final Object obj) { if (obj instanceof Map.Entry == false) { return false; } if (contains(obj) == false) { return false; } final Map.Entry entry = (Map.Entry) obj; parent.remove(entry.getKey()); return true; } @Override public Iterator> iterator() { return parent.createEntrySetIterator(); } } /** * EntrySet iterator. */ protected static class EntrySetIterator extends HashIterator implements Iterator> { protected EntrySetIterator(final AbstractHashedMap parent) { super(parent); } public Map.Entry 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 */ @Override 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.emptyIterator(); } return new KeySetIterator(this); } /** * KeySet implementation. */ protected static class KeySet extends AbstractSet { /** The parent map */ private final AbstractHashedMap parent; protected KeySet(final AbstractHashedMap parent) { super(); this.parent = parent; } @Override public int size() { return parent.size(); } @Override public void clear() { parent.clear(); } @Override public boolean contains(final Object key) { return parent.containsKey(key); } @Override public boolean remove(final Object key) { final boolean result = parent.containsKey(key); parent.remove(key); return result; } @Override public Iterator iterator() { return parent.createKeySetIterator(); } } /** * KeySet iterator. */ protected static class KeySetIterator extends HashIterator implements Iterator { @SuppressWarnings("unchecked") protected KeySetIterator(final AbstractHashedMap parent) { super((AbstractHashedMap) parent); } public K next() { return super.nextEntry().getKey(); } } //----------------------------------------------------------------------- /** * Gets the values view of the map. * Changes made to the view affect this map. * To simply iterate through the values, use {@link #mapIterator()}. * * @return the values view */ @Override 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.emptyIterator(); } return new ValuesIterator(this); } /** * Values implementation. */ protected static class Values extends AbstractCollection { /** The parent map */ private final AbstractHashedMap parent; protected Values(final AbstractHashedMap parent) { super(); this.parent = parent; } @Override public int size() { return parent.size(); } @Override public void clear() { parent.clear(); } @Override public boolean contains(final Object value) { return parent.containsValue(value); } @Override public Iterator iterator() { return parent.createValuesIterator(); } } /** * Values iterator. */ protected static class ValuesIterator extends HashIterator implements Iterator { @SuppressWarnings("unchecked") protected ValuesIterator(final AbstractHashedMap parent) { super((AbstractHashedMap) parent); } public V next() { return super.nextEntry().getValue(); } } //----------------------------------------------------------------------- /** * HashEntry used to store the data. *

* If you subclass AbstractHashedMap but not HashEntry * then you will not be able to access the protected fields. * The entryXxx() methods on AbstractHashedMap exist * to provide the necessary access. */ protected static class HashEntry implements Map.Entry, KeyValue { /** The next entry in the hash chain */ protected HashEntry next; /** The hash code of the key */ protected int hashCode; /** The key */ protected Object key; /** The value */ protected Object value; protected HashEntry(final HashEntry next, final int hashCode, final Object key, final V value) { super(); this.next = next; this.hashCode = hashCode; this.key = key; this.value = value; } @SuppressWarnings("unchecked") public K getKey() { if (key == NULL) { return null; } return (K) key; } @SuppressWarnings("unchecked") public V getValue() { return (V) value; } @SuppressWarnings("unchecked") public V setValue(final V value) { final Object old = this.value; this.value = value; return (V) old; } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } final 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())); } @Override public int hashCode() { return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); } @Override public String toString() { return new StringBuilder().append(getKey()).append('=').append(getValue()).toString(); } } /** * Base Iterator */ protected static abstract class HashIterator { /** The parent map */ private final AbstractHashedMap parent; /** The current index into the array of buckets */ private int hashIndex; /** The last returned entry */ private HashEntry last; /** The next entry */ private HashEntry next; /** The modification count expected */ private int expectedModCount; protected HashIterator(final AbstractHashedMap parent) { super(); this.parent = parent; final 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(); } final HashEntry newCurrent = next; if (newCurrent == null) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } final 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; } @Override public String toString() { if (last != null) { return "Iterator[" + last.getKey() + "=" + last.getValue() + "]"; } 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 * @throws IOException if an error occurs while writing tothe stream */ protected void doWriteObject(final ObjectOutputStream out) throws IOException { out.writeFloat(loadFactor); out.writeInt(data.length); out.writeInt(size); for (final 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 * @throws IOException if an error occurs while reading from the stream * @throws ClassNotFoundException if an object read from the stream can not be loaded */ @SuppressWarnings("unchecked") protected void doReadObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { loadFactor = in.readFloat(); final int capacity = in.readInt(); final int size = in.readInt(); init(); threshold = calculateThreshold(capacity, loadFactor); data = new HashEntry[capacity]; for (int i = 0; i < size; i++) { final K key = (K) in.readObject(); final V value = (V) 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 * @throws InternalError if {@link AbstractMap#clone()} failed */ @Override @SuppressWarnings("unchecked") protected AbstractHashedMap clone() { try { final 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 (final CloneNotSupportedException ex) { throw new InternalError(); } } /** * Compares this map with another. * * @param obj the object to compare to * @return true if equal */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof Map == false) { return false; } final Map map = (Map) obj; if (map.size() != size()) { return false; } final MapIterator it = mapIterator(); try { while (it.hasNext()) { final Object key = it.next(); final 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 (final ClassCastException ignored) { return false; } catch (final NullPointerException ignored) { return false; } return true; } /** * Gets the standard Map hashCode. * * @return the hash code defined in the Map interface */ @Override public int hashCode() { int total = 0; final 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 */ @Override public String toString() { if (size() == 0) { return "{}"; } final StringBuilder buf = new StringBuilder(32 * size()); buf.append('{'); final MapIterator it = mapIterator(); boolean hasNext = it.hasNext(); while (hasNext) { final K key = it.next(); final V 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(); } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/UnmodifiableOrderedMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/UnmodifiableOrderedMa100664 12234 12243235516 31641 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.collection.UnmodifiableCollection; import org.apache.commons.collections4.iterators.UnmodifiableOrderedMapIterator; /** * Decorates another OrderedMap to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableOrderedMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 the key type * @param the value type * @param map the map to decorate, must not be null * @return a new ordered map * @throws IllegalArgumentException if map is null * @since 4.0 */ public static OrderedMap unmodifiableOrderedMap(final OrderedMap map) { if (map instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final OrderedMap tmpMap = (OrderedMap) map; return tmpMap; } 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 */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableOrderedMap(final OrderedMap map) { super((OrderedMap) map); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since 3.1 */ private void writeObject(final 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 3.1 */ @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); // (1) } //----------------------------------------------------------------------- @Override public OrderedMapIterator mapIterator() { final OrderedMapIterator it = decorated().mapIterator(); return UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(it); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public V put(final K key, final V value) { throw new UnsupportedOperationException(); } @Override public void putAll(final Map mapToCopy) { throw new UnsupportedOperationException(); } @Override public V remove(final Object key) { throw new UnsupportedOperationException(); } @Override public Set> entrySet() { final Set> set = super.entrySet(); return UnmodifiableEntrySet.unmodifiableEntrySet(set); } @Override public Set keySet() { final Set set = super.keySet(); return UnmodifiableSet.unmodifiableSet(set); } @Override public Collection values() { final Collection coll = super.values(); return UnmodifiableCollection.unmodifiableCollection(coll); } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/PassiveExpiringMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/PassiveExpiringMap.ja100664 47542 12243235516 31641 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; 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 java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Decorates a Map to evict expired entries once their expiration * time has been reached. *

* When putting a key-value pair in the map this decorator uses a * {@link ExpirationPolicy} to determine how long the entry should remain alive * as defined by an expiration time value. *

*

* When accessing the mapped value for a key, its expiration time is checked, * and if it is a negative value or if it is greater than the current time, the * mapped value is returned. Otherwise, the key is removed from the decorated * map, and null is returned. *

*

* When invoking methods that involve accessing the entire map contents (i.e * {@link #containsKey(Object)}, {@link #entrySet()}, etc.) this decorator * removes all expired entries prior to actually completing the invocation. *

*

* Note that {@link PassiveExpiringMap} 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. *

* * @param the type of the keys in the map * @param the type of the values in the map * @since 4.0 * @version $Id: PassiveExpiringMap.java 1503029 2013-07-14 19:09:25Z tn $ */ public class PassiveExpiringMap extends AbstractMapDecorator implements Serializable { /** * A {@link org.apache.commons.collections4.map.PassiveExpiringMap.ExpirationPolicy ExpirationPolicy} * that returns a expiration time that is a * constant about of time in the future from the current time. * * @param the type of the keys in the map * @param the type of the values in the map * @since 4.0 * @version $Id: PassiveExpiringMap.java 1503029 2013-07-14 19:09:25Z tn $ */ public static class ConstantTimeToLiveExpirationPolicy implements ExpirationPolicy { /** Serialization version */ private static final long serialVersionUID = 1L; /** the constant time-to-live value measured in milliseconds. */ private final long timeToLiveMillis; /** * Default constructor. Constructs a policy using a negative * time-to-live value that results in entries never expiring. */ public ConstantTimeToLiveExpirationPolicy() { this(-1L); } /** * Construct a policy with the given time-to-live constant measured in * milliseconds. A negative time-to-live value indicates entries never * expire. A zero time-to-live value indicates entries expire (nearly) * immediately. * * @param timeToLiveMillis the constant amount of time (in milliseconds) * an entry is available before it expires. A negative value * results in entries that NEVER expire. A zero value results in * entries that ALWAYS expire. */ public ConstantTimeToLiveExpirationPolicy(final long timeToLiveMillis) { super(); this.timeToLiveMillis = timeToLiveMillis; } /** * Construct a policy with the given time-to-live constant measured in * the given time unit of measure. * * @param timeToLive the constant amount of time an entry is available * before it expires. A negative value results in entries that * NEVER expire. A zero value results in entries that ALWAYS * expire. * @param timeUnit the unit of time for the timeToLive * parameter, must not be null. * @throws IllegalArgumentException if the time unit is null. */ public ConstantTimeToLiveExpirationPolicy(final long timeToLive, final TimeUnit timeUnit) { this(validateAndConvertToMillis(timeToLive, timeUnit)); } /** * Determine the expiration time for the given key-value entry. * * @param key the key for the entry (ignored). * @param value the value for the entry (ignored). * @return if {@link #timeToLiveMillis} ≥ 0, an expiration time of * {@link #timeToLiveMillis} + * {@link System#currentTimeMillis()} is returned. Otherwise, -1 * is returned indicating the entry never expires. */ public long expirationTime(final K key, final V value) { if (timeToLiveMillis >= 0L) { // avoid numerical overflow final long now = System.currentTimeMillis(); if (now > Long.MAX_VALUE - timeToLiveMillis) { // expiration would be greater than Long.MAX_VALUE // never expire return -1; } // timeToLiveMillis in the future return now + timeToLiveMillis; } // never expire return -1L; } } /** * A policy to determine the expiration time for key-value entries. * * @param the key object type. * @param the value object type * @since 4.0 * @version $Id: PassiveExpiringMap.java 1503029 2013-07-14 19:09:25Z tn $ */ public static interface ExpirationPolicy extends Serializable { /** * Determine the expiration time for the given key-value entry. * * @param key the key for the entry. * @param value the value for the entry. * @return the expiration time value measured in milliseconds. A * negative return value indicates the entry never expires. */ long expirationTime(K key, V value); } /** Serialization version */ private static final long serialVersionUID = 1L; /** * First validate the input parameters. If the parameters are valid, convert * the given time measured in the given units to the same time measured in * milliseconds. If the parameters are invalid, an * {@link IllegalArgumentException} is thrown. * * @param timeToLive the constant amount of time an entry is available * before it expires. A negative value results in entries that NEVER * expire. A zero value results in entries that ALWAYS expire. * @param timeUnit the unit of time for the timeToLive * parameter, must not be null. * @throws IllegalArgumentException if the time unit is null. */ private static long validateAndConvertToMillis(final long timeToLive, final TimeUnit timeUnit) { if (timeUnit == null) { throw new IllegalArgumentException("Time unit must not be null"); } return TimeUnit.MILLISECONDS.convert(timeToLive, timeUnit); } /** map used to manage expiration times for the actual map entries. */ private final Map expirationMap = new HashMap(); /** the policy used to determine time-to-live values for map entries. */ private final ExpirationPolicy expiringPolicy; /** * Default constructor. Constructs a map decorator that results in entries * NEVER expiring. */ public PassiveExpiringMap() { this(-1L); } /** * Construct a map decorator using the given expiration policy to determine * expiration times. * * @param expiringPolicy the policy used to determine expiration times of * entries as they are added. */ public PassiveExpiringMap(final ExpirationPolicy expiringPolicy) { this(expiringPolicy, new HashMap()); } /** * Construct a map decorator that decorates the given map and uses the given * expiration policy to determine expiration times. If there are any * elements already in the map being decorated, they will NEVER expire * unless they are replaced. * * @param expiringPolicy the policy used to determine expiration times of * entries as they are added. * @param map the map to decorate, must not be null. * @throws IllegalArgumentException if the map is null. */ public PassiveExpiringMap(final ExpirationPolicy expiringPolicy, final Map map) { super(map); if (expiringPolicy == null) { throw new IllegalArgumentException("Policy must not be null."); } this.expiringPolicy = expiringPolicy; } /** * Construct a map decorator that decorates the given map using the given * time-to-live value measured in milliseconds to create and use a * {@link ConstantTimeToLiveExpirationPolicy} expiration policy. * * @param timeToLiveMillis the constant amount of time (in milliseconds) an * entry is available before it expires. A negative value results in * entries that NEVER expire. A zero value results in entries that * ALWAYS expire. */ public PassiveExpiringMap(final long timeToLiveMillis) { this(new ConstantTimeToLiveExpirationPolicy(timeToLiveMillis), new HashMap()); } /** * Construct a map decorator using the given time-to-live value measured in * milliseconds to create and use a * {@link ConstantTimeToLiveExpirationPolicy} expiration policy. If there * are any elements already in the map being decorated, they will NEVER * expire unless they are replaced. * * @param timeToLiveMillis the constant amount of time (in milliseconds) an * entry is available before it expires. A negative value results in * entries that NEVER expire. A zero value results in entries that * ALWAYS expire. * @param map the map to decorate, must not be null. * @throws IllegalArgumentException if the map is null. */ public PassiveExpiringMap(final long timeToLiveMillis, final Map map) { this(new ConstantTimeToLiveExpirationPolicy(timeToLiveMillis), map); } /** * Construct a map decorator using the given time-to-live value measured in * the given time units of measure to create and use a * {@link ConstantTimeToLiveExpirationPolicy} expiration policy. * * @param timeToLive the constant amount of time an entry is available * before it expires. A negative value results in entries that NEVER * expire. A zero value results in entries that ALWAYS expire. * @param timeUnit the unit of time for the timeToLive * parameter, must not be null. * @throws IllegalArgumentException if the time unit is null. */ public PassiveExpiringMap(final long timeToLive, final TimeUnit timeUnit) { this(validateAndConvertToMillis(timeToLive, timeUnit)); } /** * Construct a map decorator that decorates the given map using the given * time-to-live value measured in the given time units of measure to create * {@link ConstantTimeToLiveExpirationPolicy} expiration policy. This policy * is used to determine expiration times. If there are any elements already * in the map being decorated, they will NEVER expire unless they are * replaced. * * @param timeToLive the constant amount of time an entry is available * before it expires. A negative value results in entries that NEVER * expire. A zero value results in entries that ALWAYS expire. * @param timeUnit the unit of time for the timeToLive * parameter, must not be null. * @param map the map to decorate, must not be null. * @throws IllegalArgumentException if the time unit is null. * @throws IllegalArgumentException if the map is null. */ public PassiveExpiringMap(final long timeToLive, final TimeUnit timeUnit, final Map map) { this(validateAndConvertToMillis(timeToLive, timeUnit), map); } /** * Constructs a map decorator that decorates the given map and results in * entries NEVER expiring. If there are any elements already in the map * being decorated, they also will NEVER expire. * * @param map the map to decorate, must not be null. * @throws IllegalArgumentException if the map is null. */ public PassiveExpiringMap(final Map map) { this(-1L, map); } /** * Normal {@link Map#clear()} behavior with the addition of clearing all * expiration entries as well. */ @Override public void clear() { super.clear(); expirationMap.clear(); } /** * All expired entries are removed from the map prior to determining the * contains result. * {@inheritDoc} */ @Override public boolean containsKey(final Object key) { removeIfExpired(key, now()); return super.containsKey(key); } /** * All expired entries are removed from the map prior to determining the * contains result. * {@inheritDoc} */ @Override public boolean containsValue(final Object value) { removeAllExpired(now()); return super.containsValue(value); } /** * All expired entries are removed from the map prior to returning the entry set. * {@inheritDoc} */ @Override public Set> entrySet() { removeAllExpired(now()); return super.entrySet(); } /** * All expired entries are removed from the map prior to returning the entry value. * {@inheritDoc} */ @Override public V get(final Object key) { removeIfExpired(key, now()); return super.get(key); } /** * All expired entries are removed from the map prior to determining if it is empty. * {@inheritDoc} */ @Override public boolean isEmpty() { removeAllExpired(now()); return super.isEmpty(); } /** * Determines if the given expiration time is less than now. * * @param now the time in milliseconds used to compare against the * expiration time. * @param expirationTimeObject the expiration time value retrieved from * {@link #expirationMap}, can be null. * @return true if expirationTimeObject is ≥ 0 * and expirationTimeObject < now. * false otherwise. */ private boolean isExpired(final long now, final Long expirationTimeObject) { if (expirationTimeObject != null) { final long expirationTime = expirationTimeObject.longValue(); return expirationTime >= 0 && now >= expirationTime; } return false; } /** * All expired entries are removed from the map prior to returning the key set. * {@inheritDoc} */ @Override public Set keySet() { removeAllExpired(now()); return super.keySet(); } /** * The current time in milliseconds. */ private long now() { return System.currentTimeMillis(); } @Override public V put(final K key, final V value) { return put(key, value, now()); } /** * Add the given key-value pair to this map as well as recording the entry's expiration time based on * the current time in milliseconds, now and this map's {@link #expiringPolicy}. */ private V put(final K key, final V value, final long now) { // record expiration time of new entry final long expirationTime = expiringPolicy.expirationTime(key, value); expirationMap.put(key, Long.valueOf(expirationTime)); return super.put(key, value); } @Override public void putAll(final Map mapToCopy) { for (final Map.Entry entry : mapToCopy.entrySet()) { put(entry.getKey(), entry.getValue()); } } /** * Normal {@link Map#remove(Object)} behavior with the addition of removing * any expiration entry as well. * {@inheritDoc} */ @Override public V remove(final Object key) { expirationMap.remove(key); return super.remove(key); } /** * Removes all entries in the map whose expiration time is less than * now. The exceptions are entries with negative expiration * times; those entries are never removed. * * @see #isExpired(long, Long) */ private void removeAllExpired(final long now) { final Iterator> iter = expirationMap.entrySet().iterator(); while (iter.hasNext()) { final Map.Entry expirationEntry = iter.next(); if (isExpired(now, expirationEntry.getValue())) { // remove entry from collection super.remove(expirationEntry.getKey()); // remove entry from expiration map iter.remove(); } } } /** * Removes the entry with the given key if the entry's expiration time is * less than now. If the entry has a negative expiration time, * the entry is never removed. */ private void removeIfExpired(final Object key, final long now) { final Long expirationTimeObject = expirationMap.get(key); if (isExpired(now, expirationTimeObject)) { remove(key); } } /** * All expired entries are removed from the map prior to returning the size. * {@inheritDoc} */ @Override public int size() { removeAllExpired(now()); return super.size(); } /** * Read the map in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); // (1) } /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(map); } /** * All expired entries are removed from the map prior to returning the value collection. * {@inheritDoc} */ @Override public Collection values() { removeAllExpired(now()); return super.values(); } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/UnmodifiableEntrySet.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/UnmodifiableEntrySet.100664 13744 12243235516 31641 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.set.AbstractSetDecorator; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.AbstractIteratorDecorator; import org.apache.commons.collections4.keyvalue.AbstractMapEntryDecorator; /** * Decorates a map entry Set to ensure it can't be altered. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableEntrySet.java 1494280 2013-06-18 20:07:04Z tn $ */ public final class UnmodifiableEntrySet extends AbstractSetDecorator> implements Unmodifiable { /** Serialization version */ private static final long serialVersionUID = 1678353579659253473L; /** * Factory method to create an unmodifiable set of Map Entry objects. * * @param the key type * @param the value type * @param set the set to decorate, must not be null * @return a new unmodifiable entry set * @throws IllegalArgumentException if set is null * @since 4.0 */ public static Set> unmodifiableEntrySet(final 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(final Set> set) { super(set); } //----------------------------------------------------------------------- @Override public boolean add(final Map.Entry object) { throw new UnsupportedOperationException(); } @Override public boolean addAll(final Collection> coll) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- @Override public Iterator> iterator() { return new UnmodifiableEntrySetIterator(decorated().iterator()); } @Override @SuppressWarnings("unchecked") public Object[] toArray() { final Object[] array = decorated().toArray(); for (int i = 0; i < array.length; i++) { array[i] = new UnmodifiableEntry((Map.Entry) array[i]); } return array; } @Override @SuppressWarnings("unchecked") public T[] toArray(final T[] array) { Object[] result = array; if (array.length > 0) { // we must create a new array to handle multi-threaded situations // where another thread could access data before we decorate it result = (Object[]) Array.newInstance(array.getClass().getComponentType(), 0); } result = decorated().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 (T[]) result; } // copy back into input array to fulfill 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. */ private class UnmodifiableEntrySetIterator extends AbstractIteratorDecorator> { protected UnmodifiableEntrySetIterator(final Iterator> iterator) { super(iterator); } @Override public Map.Entry next() { return new UnmodifiableEntry(getIterator().next()); } @Override public void remove() { throw new UnsupportedOperationException(); } } //----------------------------------------------------------------------- /** * Implementation of a map entry that is unmodifiable. */ private class UnmodifiableEntry extends AbstractMapEntryDecorator { protected UnmodifiableEntry(final Map.Entry entry) { super(entry); } @Override public V setValue(final V obj) { throw new UnsupportedOperationException(); } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/ListOrderedMap.java100664 61752 12243235516 31267 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.OrderedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.ResettableIterator; import org.apache.commons.collections4.iterators.AbstractUntypedIteratorDecorator; import org.apache.commons.collections4.keyvalue.AbstractMapEntry; import org.apache.commons.collections4.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. *

* Note that ListOrderedMap doesn't work with * {@link java.util.IdentityHashMap IdentityHashMap}, {@link CaseInsensitiveMap}, * or similar maps that violate the general contract of {@link java.util.Map}. * The ListOrderedMap (or, more precisely, the underlying List) * is relying on {@link Object#equals(Object) equals()}. This is fine, as long as the * decorated Map is also based on {@link Object#equals(Object) equals()}, * and {@link Object#hashCode() hashCode()}, which * {@link java.util.IdentityHashMap IdentityHashMap}, and * {@link CaseInsensitiveMap} don't: The former uses ==, and * the latter uses {@link Object#equals(Object) equals()} on a lower-cased * key. *

* This class is {@link Serializable} starting with Commons Collections 3.1. * * @since 3.0 * @version $Id: ListOrderedMap.java 1496190 2013-06-24 20:04:16Z tn $ */ public class ListOrderedMap extends AbstractMapDecorator implements OrderedMap, Serializable { /** Serialization version */ private static final long serialVersionUID = 2728177751851003750L; /** Internal list to hold the sequence of objects */ private final List insertOrder = new ArrayList(); /** * Factory method to create an ordered map. *

* An ArrayList is used to retain order. * * @param the key type * @param the value type * @param map the map to decorate, must not be null * @return a new list ordered map * @throws IllegalArgumentException if map is null * @since 4.0 */ public static ListOrderedMap listOrderedMap(final Map map) { return new ListOrderedMap(map); } //----------------------------------------------------------------------- /** * Constructs a new empty ListOrderedMap that decorates * a HashMap. * * @since 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(final Map map) { super(map); insertOrder.addAll(decorated().keySet()); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since 3.1 */ private void writeObject(final 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 3.1 */ @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); // (1) } // Implement OrderedMap //----------------------------------------------------------------------- @Override public OrderedMapIterator mapIterator() { return new ListOrderedMapIterator(this); } /** * Gets the first key in this map by insert order. * * @return the first key currently in this map * @throws NoSuchElementException if this map is empty */ public K firstKey() { if (size() == 0) { throw new NoSuchElementException("Map is empty"); } return insertOrder.get(0); } /** * Gets the last key in this map by insert order. * * @return the last key currently in this map * @throws NoSuchElementException if this map is empty */ public K lastKey() { if (size() == 0) { throw new NoSuchElementException("Map is empty"); } return insertOrder.get(size() - 1); } /** * Gets the next key to the one specified using insert order. * This method performs a list search to find the key and is O(n). * * @param key the key to find previous for * @return the next key, null if no match or at start */ public K nextKey(final Object key) { final int index = insertOrder.indexOf(key); if (index >= 0 && index < size() - 1) { return insertOrder.get(index + 1); } return null; } /** * Gets the previous key to the one specified using insert order. * This method performs a list search to find the key and is O(n). * * @param key the key to find previous for * @return the previous key, null if no match or at start */ public K previousKey(final Object key) { final int index = insertOrder.indexOf(key); if (index > 0) { return insertOrder.get(index - 1); } return null; } //----------------------------------------------------------------------- @Override public V put(final K key, final V value) { if (decorated().containsKey(key)) { // re-adding doesn't change order return decorated().put(key, value); } else { // first add, so add to both map and list final V result = decorated().put(key, value); insertOrder.add(key); return result; } } @Override public void putAll(final Map map) { for (final Map.Entry entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } /** * Puts the values contained in a supplied Map into the Map starting at * the specified index. * * @param index the index in the Map to start at. * @param map the Map containing the entries to be added. * @throws IndexOutOfBoundsException if the index is out of range [0, size] */ public void putAll(int index, final Map map) { if (index < 0 || index > insertOrder.size()) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + insertOrder.size()); } for (final Map.Entry entry : map.entrySet()) { final K key = entry.getKey(); final boolean contains = containsKey(key); // The return value of put is null if the key did not exist OR the value was null // so it cannot be used to determine whether the key was added put(index, entry.getKey(), entry.getValue()); if (!contains) { // if no key was replaced, increment the index index++; } else { // otherwise put the next item after the currently inserted key index = indexOf(entry.getKey()) + 1; } } } @Override public V remove(final Object key) { V result = null; if (decorated().containsKey(key)) { result = decorated().remove(key); insertOrder.remove(key); } return result; } @Override public void clear() { decorated().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 */ @Override 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 3.2 */ public List keyList() { return UnmodifiableList.unmodifiableList(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 */ @Override 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 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 */ @Override public Set> entrySet() { return new EntrySetView(this, this.insertOrder); } //----------------------------------------------------------------------- /** * Returns the Map as a string. * * @return the Map as a String */ @Override public String toString() { if (isEmpty()) { return "{}"; } final StringBuilder buf = new StringBuilder(); buf.append('{'); boolean first = true; for (final Map.Entry entry : entrySet()) { final K key = entry.getKey(); final V value = entry.getValue(); if (first) { first = false; } else { buf.append(", "); } buf.append(key == this ? "(this Map)" : key); buf.append('='); buf.append(value == this ? "(this Map)" : value); } buf.append('}'); return buf.toString(); } //----------------------------------------------------------------------- /** * Gets the key at the specified index. * * @param index the index to retrieve * @return the key at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public K get(final int index) { return insertOrder.get(index); } /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the key at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public V getValue(final 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(final Object key) { return insertOrder.indexOf(key); } /** * Sets the value at the specified index. * * @param index the index of the value to set * @param value the new value to set * @return the previous value at that index * @throws IndexOutOfBoundsException if the index is invalid * @since 3.2 */ public V setValue(final int index, final V value) { final K 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 occurred. * * @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 [0, size] * @since 3.2 */ public V put(int index, final K key, final V value) { if (index < 0 || index > insertOrder.size()) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + insertOrder.size()); } final Map m = decorated(); if (m.containsKey(key)) { final V result = m.remove(key); final 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 V remove(final 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; @SuppressWarnings("unchecked") ValuesView(final ListOrderedMap parent) { super(); this.parent = (ListOrderedMap) parent; } @Override public int size() { return this.parent.size(); } @Override public boolean contains(final Object value) { return this.parent.containsValue(value); } @Override public void clear() { this.parent.clear(); } @Override public Iterator iterator() { return new AbstractUntypedIteratorDecorator, V>(parent.entrySet().iterator()) { public V next() { return getIterator().next().getValue(); } }; } @Override public V get(final int index) { return this.parent.getValue(index); } @Override public V set(final int index, final V value) { return this.parent.setValue(index, value); } @Override public V remove(final int index) { return this.parent.remove(index); } } //----------------------------------------------------------------------- static class KeySetView extends AbstractSet { private final ListOrderedMap parent; @SuppressWarnings("unchecked") KeySetView(final ListOrderedMap parent) { super(); this.parent = (ListOrderedMap) parent; } @Override public int size() { return this.parent.size(); } @Override public boolean contains(final Object value) { return this.parent.containsKey(value); } @Override public void clear() { this.parent.clear(); } @Override public Iterator iterator() { return new AbstractUntypedIteratorDecorator, K>(parent.entrySet().iterator()) { public K next() { return getIterator().next().getKey(); } }; } } //----------------------------------------------------------------------- static class EntrySetView extends AbstractSet> { private final ListOrderedMap parent; private final List insertOrder; private Set> entrySet; public EntrySetView(final ListOrderedMap parent, final List insertOrder) { super(); this.parent = parent; this.insertOrder = insertOrder; } private Set> getEntrySet() { if (entrySet == null) { entrySet = parent.decorated().entrySet(); } return entrySet; } @Override public int size() { return this.parent.size(); } @Override public boolean isEmpty() { return this.parent.isEmpty(); } @Override public boolean contains(final Object obj) { return getEntrySet().contains(obj); } @Override public boolean containsAll(final Collection coll) { return getEntrySet().containsAll(coll); } @Override @SuppressWarnings("unchecked") public boolean remove(final Object obj) { if (obj instanceof Map.Entry == false) { return false; } if (getEntrySet().contains(obj)) { final Object key = ((Map.Entry) obj).getKey(); parent.remove(key); return true; } return false; } @Override public void clear() { this.parent.clear(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } return getEntrySet().equals(obj); } @Override public int hashCode() { return getEntrySet().hashCode(); } @Override public String toString() { return getEntrySet().toString(); } @Override public Iterator> iterator() { return new ListOrderedIterator(parent, insertOrder); } } //----------------------------------------------------------------------- static class ListOrderedIterator extends AbstractUntypedIteratorDecorator> { private final ListOrderedMap parent; private K last = null; ListOrderedIterator(final ListOrderedMap parent, final List insertOrder) { super(insertOrder.iterator()); this.parent = parent; } public Map.Entry next() { last = getIterator().next(); return new ListOrderedMapEntry(parent, last); } @Override public void remove() { super.remove(); parent.decorated().remove(last); } } //----------------------------------------------------------------------- static class ListOrderedMapEntry extends AbstractMapEntry { private final ListOrderedMap parent; ListOrderedMapEntry(final ListOrderedMap parent, final K key) { super(key, null); this.parent = parent; } @Override public V getValue() { return parent.get(getKey()); } @Override public V setValue(final V value) { return parent.decorated().put(getKey(), value); } } //----------------------------------------------------------------------- static class ListOrderedMapIterator implements OrderedMapIterator, ResettableIterator { private final ListOrderedMap parent; private ListIterator iterator; private K last = null; private boolean readable = false; ListOrderedMapIterator(final ListOrderedMap parent) { super(); this.parent = parent; this.iterator = parent.insertOrder.listIterator(); } public boolean hasNext() { return iterator.hasNext(); } public K next() { last = iterator.next(); readable = true; return last; } public boolean hasPrevious() { return iterator.hasPrevious(); } public K previous() { last = iterator.previous(); readable = true; return last; } public void remove() { if (readable == false) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); } iterator.remove(); parent.map.remove(last); readable = false; } public K getKey() { if (readable == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return last; } public V getValue() { if (readable == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return parent.get(last); } public V setValue(final V value) { if (readable == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return parent.map.put(last, value); } public void reset() { iterator = parent.insertOrder.listIterator(); last = null; readable = false; } @Override public String toString() { if (readable == true) { return "Iterator[" + getKey() + "=" + getValue() + "]"; } return "Iterator[]"; } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/HashedMap.java100664 7627 12243235516 30224 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.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 3.0 * @version $Id: HashedMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 negative */ public HashedMap(final 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 negative * @throws IllegalArgumentException if the load factor is less than zero */ public HashedMap(final int initialCapacity, final 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(final Map map) { super(map); } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone */ @Override public HashedMap clone() { return (HashedMap) super.clone(); } /** * Write the map out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Read the map in using a custom routine. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractReferenceMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractReferenceMap.100664 103611 12243235516 31576 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.MapIterator; import org.apache.commons.collections4.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 3.1 (extracted from ReferenceMap in 3.0) * @version $Id: AbstractReferenceMap.java 1477799 2013-04-30 19:56:11Z tn $ */ public abstract class AbstractReferenceMap extends AbstractHashedMap { /** * Reference type enum. */ public static enum ReferenceStrength { HARD(0), SOFT(1), WEAK(2); /** value */ public final int value; /** * Resolve enum from int. * @param value the int value * @return ReferenceType * @throws IllegalArgumentException if the specified value is invalid. */ public static ReferenceStrength resolve(final int value) { switch (value) { case 0: return HARD; case 1: return SOFT; case 2: return WEAK; default: throw new IllegalArgumentException(); } } private ReferenceStrength(final int value) { this.value = value; } } /** * The reference type for keys. */ private ReferenceStrength keyType; /** * The reference type for values. */ private ReferenceStrength valueType; /** * Should the value be automatically purged when the associated key has been collected? */ private 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 ReferenceStrength#HARD HARD}, * {@link ReferenceStrength#SOFT SOFT}, * {@link ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link ReferenceStrength#HARD}, * {@link ReferenceStrength#SOFT SOFT}, * {@link ReferenceStrength#WEAK 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( final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity, final float loadFactor, final boolean purgeValues) { super(capacity, loadFactor); this.keyType = keyType; this.valueType = valueType; this.purgeValues = purgeValues; } /** * Initialise this subclass during construction, cloning or deserialization. */ @Override protected void init() { queue = new ReferenceQueue(); } //----------------------------------------------------------------------- /** * Gets the size of the map. * * @return the size */ @Override public int size() { purgeBeforeRead(); return super.size(); } /** * Checks whether the map is currently empty. * * @return true if the map is currently size zero */ @Override 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 */ @Override public boolean containsKey(final Object key) { purgeBeforeRead(); final 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 */ @Override public boolean containsValue(final 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 */ @Override public V get(final Object key) { purgeBeforeRead(); final 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 */ @Override public V put(final K key, final V value) { if (key == null) { throw new NullPointerException("null keys not allowed"); } if (value == null) { throw new NullPointerException("null values not allowed"); } purgeBeforeWrite(); return super.put(key, value); } /** * Removes the specified mapping from this map. * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map */ @Override public V remove(final Object key) { if (key == null) { return null; } purgeBeforeWrite(); return super.remove(key); } /** * Clears this map. */ @Override 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 */ @Override 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 */ @Override 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 */ @Override 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 */ @Override 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(final Reference ref) { // The hashCode of the reference is the hashCode of the // mapping key, even if the reference refers to the // mapping value... final int hash = ref.hashCode(); final 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 */ @Override protected HashEntry getEntry(final Object key) { if (key == null) { return null; } 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(final Object key, final 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 */ @Override @SuppressWarnings("unchecked") protected boolean isEqualKey(final Object key1, Object key2) { key2 = keyType == ReferenceStrength.HARD ? key2 : ((Reference) key2).get(); 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 */ @Override protected ReferenceEntry createEntry(final HashEntry next, final int hashCode, final K key, final V value) { return new ReferenceEntry(this, next, hashCode, key, value); } /** * Creates an entry set iterator. * * @return the entrySet iterator */ @Override protected Iterator> createEntrySetIterator() { return new ReferenceEntrySetIterator(this); } /** * Creates an key set iterator. * * @return the keySet iterator */ @Override protected Iterator createKeySetIterator() { return new ReferenceKeySetIterator(this); } /** * Creates an values iterator. * * @return the values iterator */ @Override protected Iterator createValuesIterator() { return new ReferenceValuesIterator(this); } //----------------------------------------------------------------------- /** * EntrySet implementation. */ static class ReferenceEntrySet extends EntrySet { protected ReferenceEntrySet(final AbstractHashedMap parent) { super(parent); } @Override public Object[] toArray() { return toArray(new Object[size()]); } @Override public T[] toArray(final T[] arr) { // special implementation to handle disappearing entries final ArrayList> list = new ArrayList>(size()); for (final Map.Entry entry : this) { list.add(new DefaultMapEntry(entry)); } return list.toArray(arr); } } //----------------------------------------------------------------------- /** * KeySet implementation. */ static class ReferenceKeySet extends KeySet { protected ReferenceKeySet(final AbstractHashedMap parent) { super(parent); } @Override public Object[] toArray() { return toArray(new Object[size()]); } @Override public T[] toArray(final T[] arr) { // special implementation to handle disappearing keys final List list = new ArrayList(size()); for (final K key : this) { list.add(key); } return list.toArray(arr); } } //----------------------------------------------------------------------- /** * Values implementation. */ static class ReferenceValues extends Values { protected ReferenceValues(final AbstractHashedMap parent) { super(parent); } @Override public Object[] toArray() { return toArray(new Object[size()]); } @Override public T[] toArray(final T[] arr) { // special implementation to handle disappearing values final List list = new ArrayList(size()); for (final V value : this) { list.add(value); } 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 3.1 */ protected static class ReferenceEntry extends HashEntry { /** The parent map */ private 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(final AbstractReferenceMap parent, final HashEntry next, final int hashCode, final K key, final V 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 */ @Override @SuppressWarnings("unchecked") public K getKey() { return (K) (parent.keyType == ReferenceStrength.HARD ? key : ((Reference) key).get()); } /** * 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 */ @Override @SuppressWarnings("unchecked") public V getValue() { return (V) (parent.valueType == ReferenceStrength.HARD ? value : ((Reference) value).get()); } /** * Sets the value of the entry. * * @param obj the object to store * @return the previous value */ @Override @SuppressWarnings("unchecked") public V setValue(final V obj) { final V old = getValue(); if (parent.valueType != ReferenceStrength.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 */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } final Map.Entry entry = (Map.Entry)obj; final Object entryKey = entry.getKey(); // convert to hard reference final 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 */ @Override 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 the type of the referenced object * @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 * @return the reference to the object */ protected Object toReference(final ReferenceStrength type, final T referent, final int hash) { if (type == ReferenceStrength.HARD) { return referent; } if (type == ReferenceStrength.SOFT) { return new SoftRef(hash, referent, parent.queue); } if (type == ReferenceStrength.WEAK) { return new WeakRef(hash, referent, parent.queue); } throw new Error(); } /** * Purges the specified reference * @param ref the reference to purge * @return true or false */ boolean purge(final Reference ref) { boolean r = parent.keyType != ReferenceStrength.HARD && key == ref; r = r || parent.valueType != ReferenceStrength.HARD && value == ref; if (r) { if (parent.keyType != ReferenceStrength.HARD) { ((Reference) key).clear(); } if (parent.valueType != ReferenceStrength.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; } } //----------------------------------------------------------------------- /** * Base iterator class. */ static class ReferenceBaseIterator { /** The parent map */ final AbstractReferenceMap parent; // These fields keep track of where we are in the table. int index; ReferenceEntry entry; ReferenceEntry previous; // These Object fields provide hard references to the // current and next entry; this assures that if hasNext() // returns true, next() will actually return a valid element. K currentKey, nextKey; V currentValue, nextValue; int expectedModCount; public ReferenceBaseIterator(final 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 void remove() { checkMod(); if (previous == null) { throw new IllegalStateException(); } parent.remove(currentKey); previous = null; currentKey = null; currentValue = null; expectedModCount = parent.modCount; } } /** * The EntrySet iterator. */ static class ReferenceEntrySetIterator extends ReferenceBaseIterator implements Iterator> { public ReferenceEntrySetIterator(final AbstractReferenceMap parent) { super(parent); } public Map.Entry next() { return nextEntry(); } } /** * The keySet iterator. */ static class ReferenceKeySetIterator extends ReferenceBaseIterator implements Iterator { @SuppressWarnings("unchecked") ReferenceKeySetIterator(final AbstractReferenceMap parent) { super((AbstractReferenceMap) parent); } public K next() { return nextEntry().getKey(); } } /** * The values iterator. */ static class ReferenceValuesIterator extends ReferenceBaseIterator implements Iterator { @SuppressWarnings("unchecked") ReferenceValuesIterator(final AbstractReferenceMap parent) { super((AbstractReferenceMap) parent); } public V next() { return nextEntry().getValue(); } } /** * The MapIterator implementation. */ static class ReferenceMapIterator extends ReferenceBaseIterator implements MapIterator { protected ReferenceMapIterator(final AbstractReferenceMap parent) { super(parent); } public K next() { return nextEntry().getKey(); } public K getKey() { final HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } public V getValue() { final HashEntry current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } public V setValue(final V value) { final 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 final int hash; public SoftRef(final int hash, final T r, final ReferenceQueue q) { super(r, q); this.hash = hash; } @Override 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 final int hash; public WeakRef(final int hash, final T r, final ReferenceQueue q) { super(r, q); this.hash = hash; } @Override 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 * @throws IOException if an error occurs while writing to the stream */ @Override protected void doWriteObject(final ObjectOutputStream out) throws IOException { out.writeInt(keyType.value); out.writeInt(valueType.value); out.writeBoolean(purgeValues); out.writeFloat(loadFactor); out.writeInt(data.length); for (final 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 superclass 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 * @throws IOException if an error occurs while reading from the stream * @throws ClassNotFoundException if an object read from the stream can not be loaded */ @Override @SuppressWarnings("unchecked") protected void doReadObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { this.keyType = ReferenceStrength.resolve(in.readInt()); this.valueType = ReferenceStrength.resolve(in.readInt()); this.purgeValues = in.readBoolean(); this.loadFactor = in.readFloat(); final int capacity = in.readInt(); init(); data = new HashEntry[capacity]; while (true) { final K key = (K) in.readObject(); if (key == null) { break; } final V value = (V) in.readObject(); put(key, value); } threshold = calculateThreshold(data.length, loadFactor); // do not call super.doReadObject() as code there doesn't work for reference map } /** * Provided protected read-only access to the key type. * @param type the type to check against. * @return true if keyType has the specified type */ protected boolean isKeyType(ReferenceStrength type) { return this.keyType == type; } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/TransformedSortedMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/TransformedSortedMap.100664 15171 12243235516 31644 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.Comparator; import java.util.Map; import java.util.SortedMap; import org.apache.commons.collections4.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 3.0 * @version $Id: TransformedSortedMap.java 1479407 2013-05-05 22:07:53Z tn $ */ 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. * Contrast this with {@link #transformedSortedMap(SortedMap, Transformer, Transformer)}. * * @param the key type * @param the value type * @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 * @return a new transformed sorted map * @throws IllegalArgumentException if the map is null * @since 4.0 */ public static TransformedSortedMap transformingSortedMap(final SortedMap map, final Transformer keyTransformer, final 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. * Contrast this with {@link #transformingSortedMap(SortedMap, Transformer, Transformer)}. * * @param the key type * @param the value type * @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 * @return a new transformed sorted map * @throws IllegalArgumentException if map is null * @since 4.0 */ public static TransformedSortedMap transformedSortedMap(final SortedMap map, final Transformer keyTransformer, final Transformer valueTransformer) { final TransformedSortedMap decorated = new TransformedSortedMap(map, keyTransformer, valueTransformer); if (map.size() > 0) { final Map transformed = decorated.transformMap(map); decorated.clear(); decorated.decorated().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(final SortedMap map, final Transformer keyTransformer, final Transformer valueTransformer) { super(map, keyTransformer, valueTransformer); } //----------------------------------------------------------------------- /** * Gets the map being decorated. * * @return the decorated map */ protected SortedMap getSortedMap() { return (SortedMap) map; } //----------------------------------------------------------------------- public K firstKey() { return getSortedMap().firstKey(); } public K lastKey() { return getSortedMap().lastKey(); } public Comparator comparator() { return getSortedMap().comparator(); } public SortedMap subMap(final K fromKey, final K toKey) { final SortedMap map = getSortedMap().subMap(fromKey, toKey); return new TransformedSortedMap(map, keyTransformer, valueTransformer); } public SortedMap headMap(final K toKey) { final SortedMap map = getSortedMap().headMap(toKey); return new TransformedSortedMap(map, keyTransformer, valueTransformer); } public SortedMap tailMap(final K fromKey) { final SortedMap map = getSortedMap().tailMap(fromKey); return new TransformedSortedMap(map, keyTransformer, valueTransformer); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/package-info.java100664 5646 12243235516 30715 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains implementations of the {@link java.util.Map Map}, * {@link org.apache.commons.collections4.IterableMap IterableMap}, * {@link org.apache.commons.collections4.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 *
  • Flat3Map - designed for good performance at size 3 or less *
  • LinkedMap - a hash map that maintains insertion order, supporting OrderedMapIterator *
  • LRUMap - a hash map that maintains a maximum size by removing the least recently used entries *
  • 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 *
  • Transformed - transforms each element added *
  • FixedSize - ensures that the size of the map cannot change *
  • Defaulted - provides default values for non-existing keys *
  • Lazy - creates objects in the map on demand *
  • ListOrdered - ensures that insertion order is retained *
* * @version $Id: package-info.java 1469004 2013-04-17 17:37:03Z tn $ */ package org.apache.commons.collections4.map; commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/CompositeMap.java100664 55726 12243235516 31015 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.set.CompositeSet; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.collection.CompositeCollection; /** * 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 3.0 * @version $Id: CompositeMap.java 1543276 2013-11-19 00:53:14Z ggregory $ */ public class CompositeMap extends AbstractIterableMap implements Serializable { /** Serialization version */ private static final long serialVersionUID = -6096931280583808322L; /** Array of all maps in the composite */ private Map[] composite; /** Handle mutation operations */ private MapMutator mutator; /** * Create a new, empty, CompositeMap. */ @SuppressWarnings("unchecked") 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 */ @SuppressWarnings("unchecked") public CompositeMap(final Map one, final 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 */ @SuppressWarnings("unchecked") public CompositeMap(final Map one, final Map two, final 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(final 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 */ @SuppressWarnings("unchecked") public CompositeMap(final Map[] composite, final 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(final 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. */ @SuppressWarnings("unchecked") public synchronized void addComposited(final Map map) throws IllegalArgumentException { for (int i = composite.length - 1; i >= 0; --i) { final 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"); } this.mutator.resolveCollision(this, this.composite[i], map, intersect); } } final 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 */ @SuppressWarnings("unchecked") public synchronized Map removeComposited(final Map map) { final int size = this.composite.length; for (int i = 0; i < size; ++i) { if (this.composite[i].equals(map)) { final 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(final 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(final 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() { final CompositeSet> entries = new CompositeSet>(); for (int i = composite.length - 1; i >= 0; --i) { entries.addComposited(composite[i].entrySet()); } return entries; } /** * Returns the value to which this map maps the specified key. Returns * null if the map contains no mapping for this key. A return * value of null does not necessarily indicate that the * map contains no mapping for the key; it's also possible that the map * explicitly maps the key to null. The containsKey * operation may be used to distinguish these two cases. * *

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

Returns the value to which the map previously associated the key, or * null if the map contained no mapping for this key. (A * null return can also indicate that the map previously * associated null with the specified key if the implementation * supports null values.) The map will not contain a mapping for * the specified key once the call returns. * * @param key key whose mapping is to be removed from the map. * @return previous value associated with specified key, or null * if there was no mapping for key. * * @throws ClassCastException if the key is of an inappropriate type for * the composited map (optional). * @throws NullPointerException if the key is null and the composited map * does not not permit null keys (optional). * @throws UnsupportedOperationException if the remove method is * not supported by the composited map containing the key */ public V remove(final 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() { final CompositeCollection values = new CompositeCollection(); for (int i = composite.length - 1; i >= 0; --i) { values.addComposited(composite[i].values()); } return values; } /** * 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 */ @Override public boolean equals(final Object obj) { if (obj instanceof Map) { final Map map = (Map) obj; return this.entrySet().equals(map.entrySet()); } return false; } /** * Gets a hash code for the Map as per the Map specification. * {@inheritDoc} */ @Override public int hashCode() { int code = 0; for (final Map.Entry entry : entrySet()) { code += entry.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 extends Serializable { /** * 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 */ 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. */ V put(CompositeMap map, Map[] composited, K key, V value); /** * Called when the CompositeMap.putAll() method is invoked. * * @param map the CompositeMap which is being modified * @param composited array of Maps in the CompositeMap being modified * @param mapToAdd Mappings to be stored in this CompositeMap * * @throws UnsupportedOperationException if not defined * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map. * @throws IllegalArgumentException if some aspect of this key or value * prevents it from being stored in this map. * @throws NullPointerException this map does not permit null * keys or values, and the specified key or value is * null. */ void putAll(CompositeMap map, Map[] composited, Map mapToAdd); } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractMapDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractMapDecorator.100664 7733 12243235516 31572 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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. * * @param the type of the keys in the map * @param the type of the values in the map * @since 3.0 * @version $Id: AbstractMapDecorator.java 1494296 2013-06-18 20:54:29Z tn $ */ public abstract class AbstractMapDecorator extends AbstractIterableMap { /** The map to decorate */ transient Map map; /** * Constructor only used in deserialization, do not use otherwise. * @since 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 */ protected AbstractMapDecorator(final 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 decorated() { return map; } //----------------------------------------------------------------------- public void clear() { decorated().clear(); } public boolean containsKey(final Object key) { return decorated().containsKey(key); } public boolean containsValue(final Object value) { return decorated().containsValue(value); } public Set> entrySet() { return decorated().entrySet(); } public V get(final Object key) { return decorated().get(key); } public boolean isEmpty() { return decorated().isEmpty(); } public Set keySet() { return decorated().keySet(); } public V put(final K key, final V value) { return decorated().put(key, value); } public void putAll(final Map mapToCopy) { decorated().putAll(mapToCopy); } public V remove(final Object key) { return decorated().remove(key); } public int size() { return decorated().size(); } public Collection values() { return decorated().values(); } @Override public boolean equals(final Object object) { if (object == this) { return true; } return decorated().equals(object); } @Override public int hashCode() { return decorated().hashCode(); } @Override public String toString() { return decorated().toString(); } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractSortedMapDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractSortedMapDeco100664 11660 12243235516 31637 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.Comparator; import java.util.Iterator; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import org.apache.commons.collections4.IterableSortedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.iterators.ListIteratorWrapper; /** * 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. * * @param the type of the keys in the map * @param the type of the values in the map * @since 3.0 * @version $Id: AbstractSortedMapDecorator.java 1477799 2013-04-30 19:56:11Z tn $ */ public abstract class AbstractSortedMapDecorator extends AbstractMapDecorator implements IterableSortedMap { /** * Constructor only used in deserialization, do not use otherwise. * @since 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(final SortedMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ @Override protected SortedMap decorated() { return (SortedMap) super.decorated(); } //----------------------------------------------------------------------- public Comparator comparator() { return decorated().comparator(); } public K firstKey() { return decorated().firstKey(); } public K lastKey() { return decorated().lastKey(); } public SortedMap subMap(final K fromKey, final K toKey) { return decorated().subMap(fromKey, toKey); } public SortedMap headMap(final K toKey) { return decorated().headMap(toKey); } public SortedMap tailMap(final K fromKey) { return decorated().tailMap(fromKey); } public K previousKey(final K key) { final SortedMap headMap = headMap(key); return headMap.isEmpty() ? null : headMap.lastKey(); } public K nextKey(final K key) { final Iterator it = tailMap(key).keySet().iterator(); it.next(); return it.hasNext() ? it.next() : null; } /** * {@inheritDoc} */ @Override public OrderedMapIterator mapIterator() { return new SortedMapIterator(entrySet()); } /** * OrderedMapIterator implementation. * * @param the key type * @param the value type */ protected static class SortedMapIterator extends EntrySetToMapIteratorAdapter implements OrderedMapIterator { /** * Create a new AbstractSortedMapDecorator.SortedMapIterator. * @param entrySet the entrySet to iterate */ protected SortedMapIterator(final Set> entrySet) { super(entrySet); } /** * {@inheritDoc} */ @Override public synchronized void reset() { super.reset(); iterator = new ListIteratorWrapper>(iterator); } /** * {@inheritDoc} */ public boolean hasPrevious() { return ((ListIterator>) iterator).hasPrevious(); } /** * {@inheritDoc} */ public K previous() { entry = ((ListIterator>) iterator).previous(); return getKey(); } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/StaticBucketMap.java100664 52363 12243235516 31432 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.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 3.0 (previously in main package v2.1) * @version $Id: StaticBucketMap.java 1477799 2013-04-30 19:56:11Z tn $ */ public final class StaticBucketMap extends AbstractIterableMap { /** 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 final Node[] buckets; /** The matching array of locks */ private final 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 */ @SuppressWarnings("unchecked") public StaticBucketMap(final 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 int getHash(final 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++) { synchronized(locks[i]) { cnt += locks[i].size; } } return cnt; } /** * Checks if the size is currently zero. * * @return true if empty */ public boolean isEmpty() { return (size() == 0); } /** * Gets the value associated with the key. * * @param key the key to retrieve * @return the associated value */ public V get(final Object key) { final 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) { final 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 V put(final K key, final V value) { final 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))) { final V returnVal = n.value; n.value = value; return returnVal; } } // The key was not found in the current list of nodes, add it to the end // in a new node. final Node newNode = new Node(); newNode.key = key; newNode.value = value; n.next = newNode; locks[hash].size++; } return null; } /** * Removes the specified key from the map. * * @param key the key to remove * @return the previous value at this key */ public V remove(final Object key) { final 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(final Map map) { for (final Map.Entry entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } /** * Clears the map of all entries. */ public void clear() { for (int i = 0; i < buckets.length; i++) { final 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 */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof Map == false) { return false; } final Map other = (Map) obj; return entrySet().equals(other.entrySet()); } /** * Gets the hash code, as per the Map specification. * * @return the hash code */ @Override public int hashCode() { int hashCode = 0; for (int i = 0; i < buckets.length; i++) { synchronized (locks[i]) { Node n = buckets[i]; while (n != null) { hashCode += n.hashCode(); n = n.next; } } } return hashCode; } //----------------------------------------------------------------------- /** * The Map.Entry for the StaticBucketMap. */ private static final class Node implements Map.Entry, KeyValue { protected K key; protected V value; protected Node next; public K getKey() { return key; } public V getValue() { return value; } @Override public int hashCode() { return ((key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode())); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } final Map.Entry e2 = (Map.Entry) obj; return ( (key == null ? e2.getKey() == null : key.equals(e2.getKey())) && (value == null ? e2.getValue() == null : value.equals(e2.getValue()))); } public V setValue(final V obj) { final V retVal = value; value = obj; return retVal; } } /** * The lock object, which also includes a count of the nodes in this lock. */ private final static class Lock { public int size; } //----------------------------------------------------------------------- private class BaseIterator { private final ArrayList> current = new ArrayList>(); private int bucket; private Map.Entry last; public boolean hasNext() { if (current.size() > 0) { return true; } while (bucket < buckets.length) { synchronized (locks[bucket]) { Node n = buckets[bucket]; while (n != null) { current.add(n); n = n.next; } bucket++; if (current.size() > 0) { return true; } } } return false; } protected Map.Entry nextEntry() { if (!hasNext()) { throw new NoSuchElementException(); } last = current.remove(current.size() - 1); return last; } public void remove() { if (last == null) { throw new IllegalStateException(); } StaticBucketMap.this.remove(last.getKey()); last = null; } } private class EntryIterator extends BaseIterator implements Iterator> { public Map.Entry next() { return nextEntry(); } } private class ValueIterator extends BaseIterator implements Iterator { public V next() { return nextEntry().getValue(); } } private class KeyIterator extends BaseIterator implements Iterator { public K next() { return nextEntry().getKey(); } } private class EntrySet extends AbstractSet> { @Override public int size() { return StaticBucketMap.this.size(); } @Override public void clear() { StaticBucketMap.this.clear(); } @Override public Iterator> iterator() { return new EntryIterator(); } @Override public boolean contains(final Object obj) { final Map.Entry entry = (Map.Entry) obj; final 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; } @Override public boolean remove(final Object obj) { if (obj instanceof Map.Entry == false) { return false; } final Map.Entry entry = (Map.Entry) obj; final 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 { @Override public int size() { return StaticBucketMap.this.size(); } @Override public void clear() { StaticBucketMap.this.clear(); } @Override public Iterator iterator() { return new KeyIterator(); } @Override public boolean contains(final Object obj) { return StaticBucketMap.this.containsKey(obj); } @Override public boolean remove(final Object obj) { final int hash = getHash(obj); synchronized (locks[hash]) { for (Node n = buckets[hash]; n != null; n = n.next) { final 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 { @Override public int size() { return StaticBucketMap.this.size(); } @Override public void clear() { StaticBucketMap.this.clear(); } @Override 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(final Runnable r) { if (r == null) { throw new NullPointerException(); } atomic(r, 0); } private void atomic(final Runnable r, final int bucket) { if (bucket >= buckets.length) { r.run(); return; } synchronized (locks[bucket]) { atomic(r, bucket + 1); } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/Flat3Map.java100664 115556 12243235516 30042 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.IterableMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.ResettableIterator; import org.apache.commons.collections4.iterators.EmptyIterator; import org.apache.commons.collections4.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 3.0 * @version $Id: Flat3Map.java 1477799 2013-04-30 19:56:11Z tn $ */ public class Flat3Map implements IterableMap, Serializable, Cloneable { /** Serialization version */ private static final long serialVersionUID = -6701087419741928296L; /** The size of the map, used while in flat mode */ private transient int size; /** Hash, used while in flat mode */ private transient int hash1; /** Hash, used while in flat mode */ private transient int hash2; /** Hash, used while in flat mode */ private transient int hash3; /** Key, used while in flat mode */ private transient K key1; /** Key, used while in flat mode */ private transient K key2; /** Key, used while in flat mode */ private transient K key3; /** Value, used while in flat mode */ private transient V value1; /** Value, used while in flat mode */ private transient V value2; /** Value, used while in flat mode */ private transient V value3; /** Map, used while in delegate mode */ private transient AbstractHashedMap delegateMap; /** * Constructor. */ public Flat3Map() { super(); } /** * Constructor copying elements from another map. * * @param map the map to copy * @throws NullPointerException if the map is null */ public Flat3Map(final Map map) { super(); putAll(map); } //----------------------------------------------------------------------- /** * Gets the value mapped to the key specified. * * @param key the key * @return the mapped value, null if no match */ public V get(final 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) { final 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(final 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) { final 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(final Object value) { if (delegateMap != null) { return delegateMap.containsValue(value); } if (value == null) { // drop through switch (size) { case 3: if (value3 == null) { return true; } case 2: if (value2 == null) { return true; } case 1: if (value1 == null) { return true; } } } else { switch (size) { // drop through case 3: if (value.equals(value3)) { return true; } case 2: if (value.equals(value2)) { return true; } case 1: if (value.equals(value1)) { return true; } } } return false; } //----------------------------------------------------------------------- /** * Puts a key-value mapping into this map. * * @param key the key to add * @param value the value to add * @return the value previously mapped to this key, null if none */ public V put(final K key, final V value) { if (delegateMap != null) { return delegateMap.put(key, value); } // change existing mapping if (key == null) { switch (size) { // drop through case 3: if (key3 == null) { final V old = value3; value3 = value; return old; } case 2: if (key2 == null) { final V old = value2; value2 = value; return old; } case 1: if (key1 == null) { final V old = value1; value1 = value; return old; } } } else { if (size > 0) { final int hashCode = key.hashCode(); switch (size) { // drop through case 3: if (hash3 == hashCode && key.equals(key3)) { final V old = value3; value3 = value; return old; } case 2: if (hash2 == hashCode && key.equals(key2)) { final V old = value2; value2 = value; return old; } case 1: if (hash1 == hashCode && key.equals(key1)) { final V old = value1; value1 = value; return old; } } } } // add new mapping switch (size) { default: convertToMap(); delegateMap.put(key, value); return null; case 2: hash3 = key == null ? 0 : key.hashCode(); key3 = key; value3 = value; break; case 1: hash2 = key == null ? 0 : key.hashCode(); key2 = key; value2 = value; break; case 0: hash1 = key == null ? 0 : key.hashCode(); key1 = key; value1 = value; break; } size++; return null; } /** * Puts all the values from the specified map into this map. * * @param map the map to add * @throws NullPointerException if the map is null */ public void putAll(final Map map) { final int size = map.size(); if (size == 0) { return; } if (delegateMap != null) { delegateMap.putAll(map); return; } if (size < 4) { for (final Map.Entry entry : map.entrySet()) { 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); case 0: break; default: throw new IllegalStateException("Invalid map index: " + size); } 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 3.1 */ protected AbstractHashedMap createDelegateMap() { return new HashedMap(); } /** * Removes the specified mapping from this map. * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map */ public V remove(final 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) { final V old = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (key2 == null) { final V old = value2; hash2 = hash3; key2 = key3; value2 = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (key1 == null) { final V old = value1; hash1 = hash3; key1 = key3; value1 = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } return null; case 2: if (key2 == null) { final V old = value2; hash2 = 0; key2 = null; value2 = null; size = 1; return old; } if (key1 == null) { final V old = value1; hash1 = hash2; key1 = key2; value1 = value2; hash2 = 0; key2 = null; value2 = null; size = 1; return old; } return null; case 1: if (key1 == null) { final V old = value1; hash1 = 0; key1 = null; value1 = null; size = 0; return old; } } } else { if (size > 0) { final int hashCode = key.hashCode(); switch (size) { // drop through case 3: if (hash3 == hashCode && key.equals(key3)) { final V old = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (hash2 == hashCode && key.equals(key2)) { final V old = value2; hash2 = hash3; key2 = key3; value2 = value3; hash3 = 0; key3 = null; value3 = null; size = 2; return old; } if (hash1 == hashCode && key.equals(key1)) { final V old = value1; 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)) { final V old = value2; hash2 = 0; key2 = null; value2 = null; size = 1; return old; } if (hash1 == hashCode && key.equals(key1)) { final V old = value1; 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)) { final V old = value1; hash1 = 0; key1 = null; value1 = null; size = 0; return old; } } } } return null; } /** * Clears the map, resetting the size to zero and nullifying references * to avoid garbage collection issues. */ public void clear() { if (delegateMap != null) { delegateMap.clear(); // should aid gc delegateMap = null; // switch back to flat mode } else { size = 0; hash1 = hash2 = hash3 = 0; key1 = key2 = key3 = null; value1 = value2 = value3 = null; } } //----------------------------------------------------------------------- /** * Gets an iterator over the map. * Changes made to the iterator affect this map. *

* A MapIterator returns the keys in the map. It also provides convenient * methods to get the key and value, and set the value. * It avoids the need to create an entrySet/keySet/values object. * It also avoids creating the Map Entry object. * * @return the map iterator */ public MapIterator mapIterator() { if (delegateMap != null) { return delegateMap.mapIterator(); } if (size == 0) { return EmptyMapIterator.emptyMapIterator(); } return new FlatMapIterator(this); } /** * FlatMapIterator */ static class FlatMapIterator implements MapIterator, ResettableIterator { private final Flat3Map parent; private int nextIndex = 0; private boolean canRemove = false; FlatMapIterator(final Flat3Map parent) { super(); this.parent = parent; } public boolean hasNext() { return nextIndex < parent.size; } public K next() { if (hasNext() == false) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } canRemove = true; nextIndex++; return getKey(); } public void remove() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); } parent.remove(getKey()); nextIndex--; canRemove = false; } public K getKey() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } switch (nextIndex) { case 3: return parent.key3; case 2: return parent.key2; case 1: return parent.key1; } throw new IllegalStateException("Invalid map index: " + nextIndex); } public V getValue() { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } switch (nextIndex) { case 3: return parent.value3; case 2: return parent.value2; case 1: return parent.value1; } throw new IllegalStateException("Invalid map index: " + nextIndex); } public V setValue(final V value) { if (canRemove == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } final V old = getValue(); switch (nextIndex) { case 3: parent.value3 = value; break; case 2: parent.value2 = value; break; case 1: parent.value1 = value; break; default: throw new IllegalStateException("Invalid map index: " + nextIndex); } return old; } public void reset() { nextIndex = 0; canRemove = false; } @Override public String toString() { if (canRemove) { return "Iterator[" + getKey() + "=" + getValue() + "]"; } return "Iterator[]"; } } /** * Gets the entrySet view of the map. * Changes made to the view affect this map. *

* NOTE: from 4.0, the returned Map Entry will be an independent object and will * not change anymore as the iterator progresses. To avoid this additional object * creation and 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(final Flat3Map parent) { super(); this.parent = parent; } @Override public int size() { return parent.size(); } @Override public void clear() { parent.clear(); } @Override public boolean remove(final Object obj) { if (obj instanceof Map.Entry == false) { return false; } final Map.Entry entry = (Map.Entry) obj; final Object key = entry.getKey(); final boolean result = parent.containsKey(key); parent.remove(key); return result; } @Override public Iterator> iterator() { if (parent.delegateMap != null) { return parent.delegateMap.entrySet().iterator(); } if (parent.size() == 0) { return EmptyIterator.>emptyIterator(); } return new EntrySetIterator(parent); } } static class FlatMapEntry implements Map.Entry { private final Flat3Map parent; private final int index; private volatile boolean removed; public FlatMapEntry(final Flat3Map parent, final int index) { this.parent = parent; this.index = index; this.removed = false; } /** * Used by the iterator that created this entry to indicate that * {@link java.util.Iterator#remove()} has been called. *

* As a consequence, all subsequent call to {@link #getKey()}, * {@link #setValue(Object)} and {@link #getValue()} will fail. * * @param flag */ void setRemoved(final boolean flag) { this.removed = flag; } public K getKey() { if (removed) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } switch (index) { case 3: return parent.key3; case 2: return parent.key2; case 1: return parent.key1; } throw new IllegalStateException("Invalid map index: " + index); } public V getValue() { if (removed) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } switch (index) { case 3: return parent.value3; case 2: return parent.value2; case 1: return parent.value1; } throw new IllegalStateException("Invalid map index: " + index); } public V setValue(final V value) { if (removed) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } final V old = getValue(); switch (index) { case 3: parent.value3 = value; break; case 2: parent.value2 = value; break; case 1: parent.value1 = value; break; default: throw new IllegalStateException("Invalid map index: " + index); } return old; } @Override public boolean equals(final Object obj) { if (removed) { return false; } if (obj instanceof Map.Entry == false) { return false; } final Map.Entry other = (Map.Entry) obj; final Object key = getKey(); final Object value = getValue(); return (key == null ? other.getKey() == null : key.equals(other.getKey())) && (value == null ? other.getValue() == null : value.equals(other.getValue())); } @Override public int hashCode() { if (removed) { return 0; } final Object key = getKey(); final Object value = getValue(); return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } @Override public String toString() { if (!removed) { return getKey() + "=" + getValue(); } return ""; } } static abstract class EntryIterator { private final Flat3Map parent; private int nextIndex = 0; private FlatMapEntry currentEntry = null; /** * Create a new Flat3Map.EntryIterator. */ public EntryIterator(final Flat3Map parent) { this.parent = parent; } public boolean hasNext() { return nextIndex < parent.size; } public Map.Entry nextEntry() { if (!hasNext()) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } currentEntry = new FlatMapEntry(parent, ++nextIndex); return currentEntry; } public void remove() { if (currentEntry == null) { throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); } currentEntry.setRemoved(true); parent.remove(currentEntry.getKey()); nextIndex--; currentEntry = null; } } /** * EntrySetIterator and MapEntry */ static class EntrySetIterator extends EntryIterator implements Iterator> { EntrySetIterator(final Flat3Map parent) { super(parent); } public Map.Entry next() { return 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 (delegateMap != null) { return delegateMap.keySet(); } return new KeySet(this); } /** * KeySet */ static class KeySet extends AbstractSet { private final Flat3Map parent; KeySet(final Flat3Map parent) { super(); this.parent = parent; } @Override public int size() { return parent.size(); } @Override public void clear() { parent.clear(); } @Override public boolean contains(final Object key) { return parent.containsKey(key); } @Override public boolean remove(final Object key) { final boolean result = parent.containsKey(key); parent.remove(key); return result; } @Override public Iterator iterator() { if (parent.delegateMap != null) { return parent.delegateMap.keySet().iterator(); } if (parent.size() == 0) { return EmptyIterator.emptyIterator(); } return new KeySetIterator(parent); } } /** * KeySetIterator */ static class KeySetIterator extends EntryIterator implements Iterator{ @SuppressWarnings("unchecked") KeySetIterator(final Flat3Map parent) { super((Flat3Map) parent); } public K next() { return 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 (delegateMap != null) { return delegateMap.values(); } return new Values(this); } /** * Values */ static class Values extends AbstractCollection { private final Flat3Map parent; Values(final Flat3Map parent) { super(); this.parent = parent; } @Override public int size() { return parent.size(); } @Override public void clear() { parent.clear(); } @Override public boolean contains(final Object value) { return parent.containsValue(value); } @Override public Iterator iterator() { if (parent.delegateMap != null) { return parent.delegateMap.values().iterator(); } if (parent.size() == 0) { return EmptyIterator.emptyIterator(); } return new ValuesIterator(parent); } } /** * ValuesIterator */ static class ValuesIterator extends EntryIterator implements Iterator { @SuppressWarnings("unchecked") ValuesIterator(final Flat3Map parent) { super((Flat3Map) parent); } public V next() { return nextEntry().getValue(); } } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(size()); for (final MapIterator it = mapIterator(); it.hasNext();) { out.writeObject(it.next()); // key out.writeObject(it.getValue()); // value } } /** * Read the map in using a custom routine. */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); final int count = in.readInt(); if (count > 3) { delegateMap = createDelegateMap(); } for (int i = count; i > 0; i--) { put((K) in.readObject(), (V) in.readObject()); } } //----------------------------------------------------------------------- /** * Clones the map without cloning the keys or values. * * @return a shallow clone * @since 3.1 */ @Override @SuppressWarnings("unchecked") public Flat3Map clone() { try { final Flat3Map cloned = (Flat3Map) super.clone(); if (cloned.delegateMap != null) { cloned.delegateMap = cloned.delegateMap.clone(); } return cloned; } catch (final CloneNotSupportedException ex) { throw new InternalError(); } } /** * Compares this map with another. * * @param obj the object to compare to * @return true if equal */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (delegateMap != null) { return delegateMap.equals(obj); } if (obj instanceof Map == false) { return false; } final 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 */ @Override 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()); case 0: break; default: throw new IllegalStateException("Invalid map index: " + size); } return total; } /** * Gets the map as a String. * * @return a string version of the map */ @Override public String toString() { if (delegateMap != null) { return delegateMap.toString(); } if (size == 0) { return "{}"; } final StringBuilder buf = new StringBuilder(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); break; // case 0: has already been dealt with default: throw new IllegalStateException("Invalid map index: " + size); } buf.append('}'); return buf.toString(); } } ././@LongLink100644 0 0 165 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractInputCheckedMapDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/AbstractInputCheckedM100664 16633 12243235516 31636 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.lang.reflect.Array; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.set.AbstractSetDecorator; import org.apache.commons.collections4.iterators.AbstractIteratorDecorator; import org.apache.commons.collections4.keyvalue.AbstractMapEntryDecorator; /** * 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 3.1 * @version $Id: AbstractInputCheckedMapDecorator.java 1494280 2013-06-18 20:07:04Z tn $ */ 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(final Map map) { super(map); } //----------------------------------------------------------------------- /** * Hook method called when a value is being set using setValue. *

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

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

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

* This implementation returns true. * * @return true always */ protected boolean isSetValueChecking() { return true; } //----------------------------------------------------------------------- @Override public Set> entrySet() { if (isSetValueChecking()) { return new EntrySet(map.entrySet(), this); } return map.entrySet(); } //----------------------------------------------------------------------- /** * Implementation of an entry set that checks additions via setValue. */ private class EntrySet extends AbstractSetDecorator> { /** Generated serial version ID. */ private static final long serialVersionUID = 4354731610923110264L; /** The parent map */ private final AbstractInputCheckedMapDecorator parent; protected EntrySet(final Set> set, final AbstractInputCheckedMapDecorator parent) { super(set); this.parent = parent; } @Override public Iterator> iterator() { return new EntrySetIterator(this.decorated().iterator(), parent); } @Override @SuppressWarnings("unchecked") public Object[] toArray() { final Object[] array = this.decorated().toArray(); for (int i = 0; i < array.length; i++) { array[i] = new MapEntry((Map.Entry) array[i], parent); } return array; } @Override @SuppressWarnings("unchecked") public T[] toArray(final T[] array) { Object[] result = array; if (array.length > 0) { // we must create a new array to handle multi-threaded situations // where another thread could access data before we decorate it result = (Object[]) Array.newInstance(array.getClass().getComponentType(), 0); } result = this.decorated().toArray(result); for (int i = 0; i < result.length; i++) { result[i] = new MapEntry((Map.Entry) result[i], parent); } // check to see if result should be returned straight if (result.length > array.length) { return (T[]) result; } // copy back into input array to fulfil the method contract System.arraycopy(result, 0, array, 0, result.length); if (array.length > result.length) { array[result.length] = null; } return array; } } /** * Implementation of an entry set iterator that checks additions via setValue. */ private class EntrySetIterator extends AbstractIteratorDecorator> { /** The parent map */ private final AbstractInputCheckedMapDecorator parent; protected EntrySetIterator(final Iterator> iterator, final AbstractInputCheckedMapDecorator parent) { super(iterator); this.parent = parent; } @Override public Map.Entry next() { final Map.Entry entry = getIterator().next(); return new MapEntry(entry, parent); } } /** * Implementation of a map entry that checks additions via setValue. */ private class MapEntry extends AbstractMapEntryDecorator { /** The parent map */ private final AbstractInputCheckedMapDecorator parent; protected MapEntry(final Map.Entry entry, final AbstractInputCheckedMapDecorator parent) { super(entry); this.parent = parent; } @Override public V setValue(V value) { value = parent.checkSetValue(value); return getMapEntry().setValue(value); } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/PredicatedMap.java100664 16104 12243235516 31102 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.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 3.0 * @version $Id: PredicatedMap.java 1479407 2013-05-05 22:07:53Z tn $ */ 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 the key type * @param the value type * @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 * @return a new predicated map * @throws IllegalArgumentException if the map is null * @since 4.0 */ public static PredicatedMap predicatedMap(final Map map, final Predicate keyPredicate, final 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(final Map map, final Predicate keyPredicate, final Predicate valuePredicate) { super(map); this.keyPredicate = keyPredicate; this.valuePredicate = valuePredicate; final Iterator> it = map.entrySet().iterator(); while (it.hasNext()) { final Map.Entry entry = it.next(); validate(entry.getKey(), entry.getValue()); } } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since 3.1 */ private void writeObject(final 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 3.1 */ @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); // (1) } //----------------------------------------------------------------------- /** * Validates a key value pair. * * @param key the key to validate * @param value the value to validate * @throws IllegalArgumentException if invalid */ protected void validate(final K key, final V value) { if (keyPredicate != null && keyPredicate.evaluate(key) == false) { throw new IllegalArgumentException("Cannot add key - Predicate rejected it"); } if (valuePredicate != null && valuePredicate.evaluate(value) == false) { throw new IllegalArgumentException("Cannot add value - Predicate rejected it"); } } /** * Override to validate an object set into the map via setValue. * * @param value the value to validate * @return the value itself * @throws IllegalArgumentException if invalid * @since 3.1 */ @Override protected V checkSetValue(final V value) { if (valuePredicate.evaluate(value) == false) { throw new IllegalArgumentException("Cannot set value - Predicate rejected it"); } return value; } /** * Override to only return true when there is a value transformer. * * @return true if a value predicate is in use * @since 3.1 */ @Override protected boolean isSetValueChecking() { return valuePredicate != null; } //----------------------------------------------------------------------- @Override public V put(final K key, final V value) { validate(key, value); return map.put(key, value); } @Override public void putAll(final Map mapToCopy) { for (final Map.Entry entry : mapToCopy.entrySet()) { validate(entry.getKey(), entry.getValue()); } super.putAll(mapToCopy); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/LazySortedMap.java100664 13362 12243235516 31141 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.map; import java.util.Comparator; import java.util.SortedMap; import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.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<Date> factory = new Factory<Date>() {
 *     public Date create() {
 *         return new Date();
 *     }
 * }
 * SortedMap<String, Date> lazy =
 *     LazySortedMap.lazySortedMap(new HashMap<String, Date>(), factory);
 * Date date = lazy.get("NOW");
 * 
* * After the above code is executed, date will refer to * 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 3.0 * @version $Id: LazySortedMap.java 1479407 2013-05-05 22:07:53Z tn $ */ 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 the key type * @param the value type * @param map the map to decorate, must not be null * @param factory the factory to use, must not be null * @return a new lazy sorted map * @throws IllegalArgumentException if map or factory is null * @since 4.0 */ public static LazySortedMap lazySortedMap(final SortedMap map, final Factory factory) { return new LazySortedMap(map, factory); } /** * Factory method to create a lazily instantiated sorted map. * * @param the key type * @param the value type * @param map the map to decorate, must not be null * @param factory the factory to use, must not be null * @return a new lazy sorted map * @throws IllegalArgumentException if map or factory is null * @since 4.0 */ public static LazySortedMap lazySortedMap(final SortedMap map, final 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(final SortedMap map, final 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(final SortedMap map, final Transformer factory) { super(map, factory); } //----------------------------------------------------------------------- /** * Gets the map being decorated. * * @return the decorated map */ protected SortedMap getSortedMap() { return (SortedMap) map; } //----------------------------------------------------------------------- public K firstKey() { return getSortedMap().firstKey(); } public K lastKey() { return getSortedMap().lastKey(); } public Comparator comparator() { return getSortedMap().comparator(); } public SortedMap subMap(final K fromKey, final K toKey) { final SortedMap map = getSortedMap().subMap(fromKey, toKey); return new LazySortedMap(map, factory); } public SortedMap headMap(final K toKey) { final SortedMap map = getSortedMap().headMap(toKey); return new LazySortedMap(map, factory); } public SortedMap tailMap(final K fromKey) { final SortedMap map = getSortedMap().tailMap(fromKey); return new LazySortedMap(map, factory); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/LazyMap.java100664 14535 12243235516 27763 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.Factory; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.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<Date> factory = new Factory<Date>() {
 *     public Date create() {
 *         return new Date();
 *     }
 * }
 * Map<String, Date> lazy = LazyMap.lazyMap(new HashMap<String, Date>(), factory);
 * Date date = lazy.get("NOW");
 * 
* * After the above code is executed, date will refer to * 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 3.0 * @version $Id: LazyMap.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public class LazyMap extends AbstractMapDecorator implements 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 the key type * @param the value type * @param map the map to decorate, must not be null * @param factory the factory to use, must not be null * @return a new lazy map * @throws IllegalArgumentException if map or factory is null * @since 4.0 */ public static LazyMap lazyMap(final Map map, final Factory< ? extends V> factory) { return new LazyMap(map, factory); } /** * Factory method to create a lazily instantiated map. * * @param the key type * @param the value type * @param map the map to decorate, must not be null * @param factory the factory to use, must not be null * @return a new lazy map * @throws IllegalArgumentException if map or factory is null * @since 4.0 */ public static LazyMap lazyMap(final Map map, final 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(final Map map, final Factory factory) { super(map); if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } this.factory = FactoryTransformer.factoryTransformer(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(final Map map, final 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 3.1 */ private void writeObject(final 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 3.1 */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- @Override public V get(final Object key) { // create value for key if key is not currently in the map if (map.containsKey(key) == false) { @SuppressWarnings("unchecked") final K castKey = (K) key; final V value = factory.transform(castKey); map.put(castKey, 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. } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/DefaultedMap.java100664 20113 12243235516 30726 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.Factory; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.functors.ConstantTransformer; import org.apache.commons.collections4.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 3.2 * @version $Id: DefaultedMap.java 1479407 2013-05-05 22:07:53Z tn $ * * @see LazyMap */ public class DefaultedMap extends AbstractMapDecorator implements Serializable { /** Serialization version */ private static final long serialVersionUID = 19698628745827L; /** The transformer to use if the map does not contain a key */ private final Transformer value; //----------------------------------------------------------------------- /** * Factory method to create a defaulting map. *

* The value specified is returned when a missing key is found. * * @param the key type * @param the value type * @param map the map to decorate, must not be null * @param defaultValue the default value to return when the key is not found * @return a new defaulting map * @throws IllegalArgumentException if map is null * @since 4.0 */ public static DefaultedMap defaultedMap(final Map map, final V defaultValue) { return new DefaultedMap(map, ConstantTransformer.constantTransformer(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 the key type * @param the value type * @param map the map to decorate, must not be null * @param factory the factory to use to create entries, must not be null * @return a new defaulting map * @throws IllegalArgumentException if map or factory is null * @since 4.0 */ public static DefaultedMap defaultedMap(final Map map, final Factory factory) { if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } return new DefaultedMap(map, FactoryTransformer.factoryTransformer(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 the key type * @param the value type * @param map the map to decorate, must not be null * @param transformer the transformer to use as a factory to create entries, must not be null * @return a new defaulting map * @throws IllegalArgumentException if map or factory is null * @since 4.0 */ public static Map defaultedMap(final Map map, final Transformer transformer) { if (transformer == null) { throw new IllegalArgumentException("Transformer must not be null"); } return new DefaultedMap(map, transformer); } //----------------------------------------------------------------------- /** * 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(final V defaultValue) { this(ConstantTransformer.constantTransformer(defaultValue)); } /** * Constructs a new empty DefaultedMap that decorates a HashMap. * * @param defaultValueTransformer transformer to use to generate missing values. */ public DefaultedMap(final Transformer defaultValueTransformer) { this(new HashMap(), defaultValueTransformer); } /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @param defaultValueTransformer the value transformer to use * @throws IllegalArgumentException if map or transformer is null */ protected DefaultedMap(final Map map, final Transformer defaultValueTransformer) { super(map); if (defaultValueTransformer == null) { throw new IllegalArgumentException("transformer must not be null"); } this.value = defaultValueTransformer; } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(final 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 */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- @Override @SuppressWarnings("unchecked") public V get(final Object key) { // create value for key if key is not currently in the map if (map.containsKey(key) == false) { return value.transform((K) key); } 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. } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/UnmodifiableMap.java100664 12405 12243235516 31434 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.collection.UnmodifiableCollection; import org.apache.commons.collections4.iterators.EntrySetMapIterator; import org.apache.commons.collections4.iterators.UnmodifiableMapIterator; /** * Decorates another Map to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableMap.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class UnmodifiableMap extends AbstractMapDecorator implements Unmodifiable, Serializable { /** Serialization version */ private static final long serialVersionUID = 2737023427269031941L; /** * Factory method to create an unmodifiable map. * * @param the key type * @param the value type * @param map the map to decorate, must not be null * @return a new unmodifiable map * @throws IllegalArgumentException if map is null * @since 4.0 */ public static Map unmodifiableMap(final Map map) { if (map instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final Map tmpMap = (Map) map; return tmpMap; } 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 */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableMap(final Map map) { super((Map) map); } //----------------------------------------------------------------------- /** * Write the map out using a custom routine. * * @param out the output stream * @throws IOException * @since 3.1 */ private void writeObject(final 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 3.1 */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); map = (Map) in.readObject(); } //----------------------------------------------------------------------- @Override public void clear() { throw new UnsupportedOperationException(); } @Override public V put(final K key, final V value) { throw new UnsupportedOperationException(); } @Override public void putAll(final Map mapToCopy) { throw new UnsupportedOperationException(); } @Override public V remove(final Object key) { throw new UnsupportedOperationException(); } @Override public MapIterator mapIterator() { if (map instanceof IterableMap) { final MapIterator it = ((IterableMap) map).mapIterator(); return UnmodifiableMapIterator.unmodifiableMapIterator(it); } final MapIterator it = new EntrySetMapIterator(map); return UnmodifiableMapIterator.unmodifiableMapIterator(it); } @Override public Set> entrySet() { final Set> set = super.entrySet(); return UnmodifiableEntrySet.unmodifiableEntrySet(set); } @Override public Set keySet() { final Set set = super.keySet(); return UnmodifiableSet.unmodifiableSet(set); } @Override public Collection values() { final Collection coll = super.values(); return UnmodifiableCollection.unmodifiableCollection(coll); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/map/SingletonMap.java100664 40276 12243235516 31007 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.BoundedMap; import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.ResettableIterator; import org.apache.commons.collections4.iterators.SingletonIterator; import org.apache.commons.collections4.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 3.1 * @version $Id: SingletonMap.java 1533984 2013-10-20 21:12:51Z tn $ */ public class SingletonMap implements OrderedMap, BoundedMap, KeyValue, Serializable, Cloneable { /** Serialization version */ private static final long serialVersionUID = -8931271118676803261L; /** Singleton key */ private final K key; /** Singleton value */ private V value; /** * Constructor that creates a map of null to null. */ public SingletonMap() { super(); this.key = null; } /** * Constructor specifying the key and value. * * @param key the key to use * @param value the value to use */ public SingletonMap(final K key, final V value) { super(); this.key = key; this.value = value; } /** * Constructor specifying the key and value as a KeyValue. * * @param keyValue the key value pair to use */ public SingletonMap(final 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(final 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(final Map map) { super(); if (map.size() != 1) { throw new IllegalArgumentException("The map size must be 1"); } final Map.Entry entry = map.entrySet().iterator().next(); this.key = entry.getKey(); this.value = entry.getValue(); } // KeyValue //----------------------------------------------------------------------- /** * Gets the key. * * @return the key */ public K getKey() { return key; } /** * Gets the value. * * @return the value */ public V getValue() { return value; } /** * Sets the value. * * @param value the new value to set * @return the old value */ public V setValue(final V value) { final V old = this.value; this.value = value; return old; } // BoundedMap //----------------------------------------------------------------------- /** * Is the map currently full, always true. * * @return true always */ public boolean isFull() { return true; } /** * Gets the maximum size of the map, always 1. * * @return 1 always */ public int maxSize() { return 1; } // Map //----------------------------------------------------------------------- /** * Gets the value mapped to the key specified. * * @param key the key * @return the mapped value, null if no match */ public V get(final 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(final 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(final Object value) { return isEqualValue(value); } //----------------------------------------------------------------------- /** * Puts a key-value mapping into this map where the key must match the existing key. *

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

* The map must be of size 0 or size 1. * If it is size 1, the key must match the key of this map otherwise an * IllegalArgumentException is thrown. * * @param map the map to add, must be size 0 or 1, and the key must match * @throws NullPointerException if the map is null * @throws IllegalArgumentException if the key does not match */ public void putAll(final Map map) { switch (map.size()) { case 0: return; case 1: final Map.Entry entry = map.entrySet().iterator().next(); put(entry.getKey(), entry.getValue()); return; default: throw new IllegalArgumentException("The map size must be 0 or 1"); } } /** * Unsupported operation. * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map * @throws UnsupportedOperationException always */ public V remove(final 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() { final 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); } /** * {@inheritDoc} */ public OrderedMapIterator mapIterator() { return new SingletonMapIterator(this); } /** * Gets the first (and only) key in the map. * * @return the key */ public K firstKey() { return getKey(); } /** * Gets the last (and only) key in the map. * * @return the key */ public K lastKey() { return getKey(); } /** * Gets the next key after the key specified, always null. * * @param key the next key * @return null always */ public K nextKey(final K key) { return null; } /** * Gets the previous key before the key specified, always null. * * @param key the next key * @return null always */ public K previousKey(final K key) { return null; } //----------------------------------------------------------------------- /** * Compares the specified key to the stored key. * * @param key the key to compare * @return true if equal */ protected boolean isEqualKey(final 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(final 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(final SingletonMap parent) { super(); this.parent = parent; } public boolean hasNext() { return hasNext; } public K next() { if (hasNext == false) { throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); } hasNext = false; canGetSet = true; return parent.getKey(); } public boolean hasPrevious() { return hasNext == false; } public K previous() { if (hasNext == true) { throw new NoSuchElementException(AbstractHashedMap.NO_PREVIOUS_ENTRY); } hasNext = true; return parent.getKey(); } public void remove() { throw new UnsupportedOperationException(); } public K getKey() { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return parent.getKey(); } public V getValue() { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return parent.getValue(); } public V setValue(final V value) { if (canGetSet == false) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return parent.setValue(value); } public void reset() { hasNext = true; } @Override public String toString() { if (hasNext) { return "Iterator[]"; } 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(final SingletonMap parent) { super(); this.parent = parent; } @Override public int size() { return 1; } @Override public boolean isEmpty() { return false; } @Override public boolean contains(final Object object) { return parent.containsValue(object); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Iterator iterator() { return new SingletonIterator(parent.getValue(), false); } } //----------------------------------------------------------------------- /** * Clones the map without cloning the key or value. * * @return a shallow clone */ @Override @SuppressWarnings("unchecked") public SingletonMap clone() { try { return (SingletonMap) super.clone(); } catch (final CloneNotSupportedException ex) { throw new InternalError(); } } /** * Compares this map with another. * * @param obj the object to compare to * @return true if equal */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof Map == false) { return false; } final Map other = (Map) obj; if (other.size() != 1) { return false; } final Map.Entry 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 */ @Override 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 */ @Override public String toString() { return new StringBuilder(128) .append('{') .append(getKey() == this ? "(this Map)" : getKey()) .append('=') .append(getValue() == this ? "(this Map)" : getValue()) .append('}') .toString(); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/IterableGet.java100664 3212 12243235516 27766 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * The "read" subset of the {@link java.util.Map} interface. * * @since 4.0 * @version $Id: IterableGet.java 1477779 2013-04-30 18:55:24Z tn $ * * @see Put */ public interface IterableGet extends Get { /** * 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 use Map Entry objects. *

     * IterableMap map = new HashedMap();
     * MapIterator it = map.mapIterator();
     * while (it.hasNext()) {
     *   String key = it.next();
     *   Integer value = it.getValue();
     *   it.setValue(value + 1);
     * }
     * 
* * @return a map iterator */ MapIterator mapIterator(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/TrieUtils.java100664 3213 12243235517 27525 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import org.apache.commons.collections4.trie.UnmodifiableTrie; /** * A collection of {@link Trie} utilities. * * @since 4.0 * @version $Id: TrieUtils.java 1533984 2013-10-20 21:12:51Z tn $ */ public class TrieUtils { /** * {@link TrieUtils} should not normally be instantiated. */ private TrieUtils() {} /** * Returns an unmodifiable instance of a {@link Trie} * * @param the key type * @param the value type * @param trie the trie to make unmodifiable, must not be null * @return an unmodifiable trie backed by the given trie * * @see java.util.Collections#unmodifiableMap(java.util.Map) */ public static Trie unmodifiableTrie(final Trie trie) { return UnmodifiableTrie.unmodifiableTrie(trie); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/overview.html100664 7567 12243235516 27511 0ustartntn 0 0

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

The Apache 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 occurrences. Methods are provided to get the number of occurrences, 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 bidirectional 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.

commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/MultiMap.java100664 15421 12243235516 27354 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Collection; /** * 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 MultiValueMap();
 * 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 2.0 * @version $Id: MultiMap.java 1542763 2013-11-17 17:10:33Z tn $ */ public interface MultiMap extends IterableMap { /** * 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 subsequent 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 {@code true} if the mapping was removed, {@code false} otherwise * @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 * @since 4.0 (signature in previous releases: V remove(K, V)) */ boolean removeMapping(K key, V 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 compatibility 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); // Cannot use get(K key) as that does not properly implement Map#get /** * 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 compatibility 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(K key, Object value); /** * Removes all values associated with the specified key. *

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

* Implementations typically return a collection containing the combination * of values from all keys. * This cannot be mandated due to backwards compatibility of this interface. * * @return a collection view of the values contained in this map */ Collection values(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/PredicateUtils.java100664 57624 12243235516 30560 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Collection; import org.apache.commons.collections4.functors.AllPredicate; import org.apache.commons.collections4.functors.AndPredicate; import org.apache.commons.collections4.functors.AnyPredicate; import org.apache.commons.collections4.functors.EqualPredicate; import org.apache.commons.collections4.functors.ExceptionPredicate; import org.apache.commons.collections4.functors.FalsePredicate; import org.apache.commons.collections4.functors.IdentityPredicate; import org.apache.commons.collections4.functors.InstanceofPredicate; import org.apache.commons.collections4.functors.InvokerTransformer; import org.apache.commons.collections4.functors.NonePredicate; import org.apache.commons.collections4.functors.NotNullPredicate; import org.apache.commons.collections4.functors.NotPredicate; import org.apache.commons.collections4.functors.NullIsExceptionPredicate; import org.apache.commons.collections4.functors.NullIsFalsePredicate; import org.apache.commons.collections4.functors.NullIsTruePredicate; import org.apache.commons.collections4.functors.NullPredicate; import org.apache.commons.collections4.functors.OnePredicate; import org.apache.commons.collections4.functors.OrPredicate; import org.apache.commons.collections4.functors.TransformedPredicate; import org.apache.commons.collections4.functors.TransformerPredicate; import org.apache.commons.collections4.functors.TruePredicate; import org.apache.commons.collections4.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 3.0 * @version $Id: PredicateUtils.java 1469004 2013-04-17 17:37:03Z tn $ */ public class PredicateUtils { /** * This class is not normally instantiated. */ private PredicateUtils() {} // Simple predicates //----------------------------------------------------------------------------- /** * Gets a Predicate that always throws an exception. * This could be useful during testing as a placeholder. * * @param the type that the predicate queries * @return the predicate * @see org.apache.commons.collections4.functors.ExceptionPredicate */ public static Predicate exceptionPredicate() { return ExceptionPredicate.exceptionPredicate(); } /** * Gets a Predicate that always returns true. * * @param the type that the predicate queries * @return the predicate * @see org.apache.commons.collections4.functors.TruePredicate */ public static Predicate truePredicate() { return TruePredicate.truePredicate(); } /** * Gets a Predicate that always returns false. * * @param the type that the predicate queries * @return the predicate * @see org.apache.commons.collections4.functors.FalsePredicate */ public static Predicate falsePredicate() { return FalsePredicate. falsePredicate(); } /** * Gets a Predicate that checks if the input object passed in is null. * * @param the type that the predicate queries * @return the predicate * @see org.apache.commons.collections4.functors.NullPredicate */ public static Predicate nullPredicate() { return NullPredicate.nullPredicate(); } /** * Gets a Predicate that checks if the input object passed in is not null. * * @param the type that the predicate queries * @return the predicate * @see org.apache.commons.collections4.functors.NotNullPredicate */ public static Predicate notNullPredicate() { return NotNullPredicate.notNullPredicate(); } /** * Creates a Predicate that checks if the input object is equal to the * specified object using equals(). * * @param the type that the predicate queries * @param value the value to compare against * @return the predicate * @see org.apache.commons.collections4.functors.EqualPredicate */ public static Predicate equalPredicate(final T value) { return EqualPredicate.equalPredicate(value); } /** * Creates a Predicate that checks if the input object is equal to the * specified object by identity. * * @param the type that the predicate queries * @param value the value to compare against * @return the predicate * @see org.apache.commons.collections4.functors.IdentityPredicate */ public static Predicate identityPredicate(final T value) { return IdentityPredicate.identityPredicate(value); } /** * Creates a Predicate that checks if the object passed in is of * a particular type, using instanceof. A null input * object will return false. * * @param type the type to check for, may not be null * @return the predicate * @throws IllegalArgumentException if the class is null * @see org.apache.commons.collections4.functors.InstanceofPredicate */ public static Predicate instanceofPredicate(final Class type) { return InstanceofPredicate.instanceOfPredicate(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. * * @param the type that the predicate queries * @return the predicate * @see org.apache.commons.collections4.functors.UniquePredicate */ public static Predicate uniquePredicate() { // must return new instance each time return UniquePredicate.uniquePredicate(); } /** * Creates a Predicate that invokes a method on the input object. * The method must return either a boolean or a non-null Boolean, * and have no parameters. If the input object is null, a * PredicateException is thrown. *

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

* For example, PredicateUtils.invokerPredicate("isEmpty"); * will call the isEmpty method on the input object to * determine the predicate result. * * @param the type that the predicate queries * @param methodName the method name to call on the input object, may not be null * @param paramTypes the parameter types * @param args the arguments * @return the predicate * @throws IllegalArgumentException if the method name is null * @throws IllegalArgumentException if the paramTypes and args don't match * @see org.apache.commons.collections4.functors.InvokerTransformer * @see org.apache.commons.collections4.functors.TransformerPredicate */ public static Predicate invokerPredicate(final String methodName, final Class[] paramTypes, final Object[] args) { // reuse transformer as it has caching - this is lazy really, should have inner class here return asPredicate(InvokerTransformer.invokerTransformer(methodName, paramTypes, args)); } // Boolean combinations //----------------------------------------------------------------------------- /** * Create a new Predicate that returns true only if both of the specified * predicates are true. * * @param the type that the predicate queries * @param predicate1 the first predicate, may not be null * @param predicate2 the second predicate, may not be null * @return the and predicate * @throws IllegalArgumentException if either predicate is null * @see org.apache.commons.collections4.functors.AndPredicate */ public static Predicate andPredicate(final Predicate predicate1, final Predicate predicate2) { return AndPredicate.andPredicate(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. * * @param the type that the predicate queries * @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 * @see org.apache.commons.collections4.functors.AllPredicate */ public static Predicate allPredicate(final Predicate... predicates) { return AllPredicate.allPredicate(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. * * @param the type that the predicate queries * @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 * @see org.apache.commons.collections4.functors.AllPredicate */ public static Predicate allPredicate(final Collection> predicates) { return AllPredicate.allPredicate(predicates); } /** * Create a new Predicate that returns true if either of the specified * predicates are true. * * @param the type that the predicate queries * @param predicate1 the first predicate, may not be null * @param predicate2 the second predicate, may not be null * @return the or predicate * @throws IllegalArgumentException if either predicate is null * @see org.apache.commons.collections4.functors.OrPredicate */ public static Predicate orPredicate(final Predicate predicate1, final Predicate predicate2) { return OrPredicate.orPredicate(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. * * @param the type that the predicate queries * @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 * @see org.apache.commons.collections4.functors.AnyPredicate */ public static Predicate anyPredicate(final Predicate... predicates) { return AnyPredicate.anyPredicate(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. * * @param the type that the predicate queries * @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 * @see org.apache.commons.collections4.functors.AnyPredicate */ public static Predicate anyPredicate(final Collection> predicates) { return AnyPredicate.anyPredicate(predicates); } /** * Create a new Predicate that returns true if one, but not both, of the * specified predicates are true. XOR * * @param the type that the predicate queries * @param predicate1 the first predicate, may not be null * @param predicate2 the second predicate, may not be null * @return the either predicate * @throws IllegalArgumentException if either predicate is null * @see org.apache.commons.collections4.functors.OnePredicate */ public static Predicate eitherPredicate(final Predicate predicate1, final Predicate predicate2) { @SuppressWarnings("unchecked") final Predicate onePredicate = PredicateUtils.onePredicate(predicate1, predicate2); return onePredicate; } /** * 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. * * @param the type that the predicate queries * @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 * @see org.apache.commons.collections4.functors.OnePredicate */ public static Predicate onePredicate(final Predicate... predicates) { return OnePredicate.onePredicate(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. * * @param the type that the predicate queries * @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 * @see org.apache.commons.collections4.functors.OnePredicate */ public static Predicate onePredicate(final Collection> predicates) { return OnePredicate.onePredicate(predicates); } /** * Create a new Predicate that returns true if neither of the specified * predicates are true. * * @param the type that the predicate queries * @param predicate1 the first predicate, may not be null * @param predicate2 the second predicate, may not be null * @return the neither predicate * @throws IllegalArgumentException if either predicate is null * @see org.apache.commons.collections4.functors.NonePredicate */ public static Predicate neitherPredicate(final Predicate predicate1, final Predicate predicate2) { @SuppressWarnings("unchecked") final Predicate nonePredicate = PredicateUtils.nonePredicate(predicate1, predicate2); return nonePredicate; } /** * 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. * * @param the type that the predicate queries * @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 * @see org.apache.commons.collections4.functors.NonePredicate */ public static Predicate nonePredicate(final Predicate... predicates) { return NonePredicate.nonePredicate(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. * * @param the type that the predicate queries * @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 * @see org.apache.commons.collections4.functors.NonePredicate */ public static Predicate nonePredicate(final Collection> predicates) { return NonePredicate.nonePredicate(predicates); } /** * Create a new Predicate that returns true if the specified predicate * returns false and vice versa. * * @param the type that the predicate queries * @param predicate the predicate to not * @return the not predicate * @throws IllegalArgumentException if the predicate is null * @see org.apache.commons.collections4.functors.NotPredicate */ public static Predicate notPredicate(final Predicate predicate) { return NotPredicate.notPredicate(predicate); } // Adaptors //----------------------------------------------------------------------------- /** * Create a new Predicate that wraps a Transformer. The Transformer must * return either Boolean.TRUE or Boolean.FALSE otherwise a PredicateException * will be thrown. * * @param the type that the predicate queries * @param transformer the transformer to wrap, may not be null * @return the transformer wrapping predicate * @throws IllegalArgumentException if the transformer is null * @see org.apache.commons.collections4.functors.TransformerPredicate */ public static Predicate asPredicate(final Transformer transformer) { return TransformerPredicate.transformerPredicate(transformer); } // Null handlers //----------------------------------------------------------------------------- /** * Gets a Predicate that throws an exception if the input object is null, * otherwise it calls the specified Predicate. This allows null handling * behaviour to be added to Predicates that don't support nulls. * * @param the type that the predicate queries * @param predicate the predicate to wrap, may not be null * @return the predicate * @throws IllegalArgumentException if the predicate is null. * @see org.apache.commons.collections4.functors.NullIsExceptionPredicate */ public static Predicate nullIsExceptionPredicate(final Predicate predicate){ return NullIsExceptionPredicate.nullIsExceptionPredicate(predicate); } /** * Gets a Predicate that returns false if the input object is null, otherwise * it calls the specified Predicate. This allows null handling behaviour to * be added to Predicates that don't support nulls. * * @param the type that the predicate queries * @param predicate the predicate to wrap, may not be null * @return the predicate * @throws IllegalArgumentException if the predicate is null. * @see org.apache.commons.collections4.functors.NullIsFalsePredicate */ public static Predicate nullIsFalsePredicate(final Predicate predicate){ return NullIsFalsePredicate.nullIsFalsePredicate(predicate); } /** * Gets a Predicate that returns true if the input object is null, otherwise * it calls the specified Predicate. This allows null handling behaviour to * be added to Predicates that don't support nulls. * * @param the type that the predicate queries * @param predicate the predicate to wrap, may not be null * @return the predicate * @throws IllegalArgumentException if the predicate is null. * @see org.apache.commons.collections4.functors.NullIsTruePredicate */ public static Predicate nullIsTruePredicate(final Predicate predicate){ return NullIsTruePredicate.nullIsTruePredicate(predicate); } // Transformed //----------------------------------------------------------------------- /** * Creates a predicate that transforms the input object before passing it * to the predicate. * * @param the type that the predicate queries * @param transformer the transformer to call first * @param predicate the predicate to call with the result of the transform * @return the predicate * @throws IllegalArgumentException if the transformer or the predicate is null * @see org.apache.commons.collections4.functors.TransformedPredicate * @since 3.1 */ public static Predicate transformedPredicate( final Transformer transformer, final Predicate predicate) { return TransformedPredicate.transformedPredicate(transformer, predicate); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/KeyValue.java100664 2667 12243235516 27341 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * 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. * * @param the type of the key * @param the type of the value * @since 3.0 * @version $Id: KeyValue.java 1477779 2013-04-30 18:55:24Z tn $ */ public interface KeyValue { /** * Gets the key from the pair. * * @return the key */ K getKey(); /** * Gets the value from the pair. * * @return the value */ V getValue(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/EnumerationUtils.java100664 5112 12243235516 31107 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.StringTokenizer; import org.apache.commons.collections4.iterators.EnumerationIterator; /** * Provides utility methods for {@link Enumeration} instances. * * @since 3.0 * @version $Id: EnumerationUtils.java 1533984 2013-10-20 21:12:51Z tn $ */ public class EnumerationUtils { /** * EnumerationUtils is not normally instantiated. */ private EnumerationUtils() {} /** * 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 the element type * @param enumeration the enumeration to traverse, which should not be null. * @return a list containing all elements of the given enumeration * @throws NullPointerException if the enumeration parameter is null. */ public static List toList(final Enumeration enumeration) { return IteratorUtils.toList(new EnumerationIterator(enumeration)); } /** * Override toList(Enumeration) for StringTokenizer as it implements Enumeration<Object> * for the sake of backward compatibility. * * @param stringTokenizer the tokenizer to convert to a {@link List}<{@link String}> * @return a list containing all tokens of the given StringTokenizer */ public static List toList(final StringTokenizer stringTokenizer) { final List result = new ArrayList(stringTokenizer.countTokens()); while (stringTokenizer.hasMoreTokens()) { result.add(stringTokenizer.nextToken()); } return result; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/ListUtils.java100664 66746 12243235516 27600 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.apache.commons.collections4.bag.HashBag; import org.apache.commons.collections4.functors.DefaultEquator; import org.apache.commons.collections4.list.FixedSizeList; import org.apache.commons.collections4.list.LazyList; import org.apache.commons.collections4.list.PredicatedList; import org.apache.commons.collections4.list.TransformedList; import org.apache.commons.collections4.list.UnmodifiableList; import org.apache.commons.collections4.sequence.CommandVisitor; import org.apache.commons.collections4.sequence.EditScript; import org.apache.commons.collections4.sequence.SequencesComparator; /** * Provides utility methods and decorators for {@link List} instances. * * @since 1.0 * @version $Id: ListUtils.java 1540567 2013-11-10 22:19:29Z tn $ */ public class ListUtils { /** * ListUtils should not normally be instantiated. */ private ListUtils() {} //----------------------------------------------------------------------- /** * Returns an immutable empty list if the argument is null, * or the argument itself otherwise. * * @param the element type * @param list the list, possibly null * @return an empty list if the argument is null */ public static List emptyIfNull(final List list) { return list == null ? Collections.emptyList() : list; } /** * Returns either the passed in list, or if the list is {@code null}, * the value of {@code defaultList}. * * @param the element type * @param list the list, possibly {@code null} * @param defaultList the returned values if list is {@code null} * @return an empty list if the argument is null * @since 4.0 */ public static List defaultIfNull(final List list, final List defaultList) { return list == null ? defaultList : list; } /** * Returns a new list containing all elements that are contained in * both given lists. * * @param the element type * @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 List result = new ArrayList(); List smaller = list1; List larger = list2; if (list1.size() > list2.size()) { smaller = list2; larger = list1; } final HashSet hashSet = new HashSet(smaller); for (final E e : larger) { if (hashSet.contains(e)) { result.add(e); hashSet.remove(e); } } 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 the element type * @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(); final HashBag bag = new HashBag(list2); for (final E e : list1) { if (!bag.remove(e, 1)) { result.add(e); } } return result; } /** * Returns the sum of the given lists. This is their intersection * subtracted from their union. * * @param the element type * @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 the element type * @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; } /** * Selects all elements from input collection which match the given * predicate into an output list. *

* A null predicate matches no elements. * * @param the element type * @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 list is null * * @since 4.0 * @see CollectionUtils#select(Iterable, Predicate) */ public static List select(final Collection inputCollection, final Predicate predicate) { return CollectionUtils.select(inputCollection, predicate, new ArrayList(inputCollection.size())); } /** * 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 the element type * @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 * * @since 4.0 * @see CollectionUtils#selectRejected(Iterable, Predicate) */ public static List selectRejected(final Collection inputCollection, final Predicate predicate) { return CollectionUtils.selectRejected(inputCollection, predicate, new ArrayList(inputCollection.size())); } /** * 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; } final Iterator it1 = list1.iterator(); final 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; final Iterator it = list.iterator(); while (it.hasNext()) { final Object 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);. *

* This implementation iterates over collection, checking each element in * turn to see if it's contained in retain. If it's contained, it's added * to the returned list. As a consequence, it is advised to use a collection type for * retain that provides a fast (e.g. O(1)) implementation of * {@link Collection#contains(Object)}. * * @param the element type * @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 3.2 */ public static List retainAll(final Collection collection, final Collection retain) { final List list = new ArrayList(Math.min(collection.size(), retain.size())); for (final E obj : collection) { 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 collection * 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);. *

* This implementation iterates over collection, checking each element in * turn to see if it's contained in remove. If it's not contained, it's added * to the returned list. As a consequence, it is advised to use a collection type for * remove that provides a fast (e.g. O(1)) implementation of * {@link Collection#contains(Object)}. * * @param the element type * @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 3.2 */ public static List removeAll(final Collection collection, final Collection remove) { final List list = new ArrayList(); for (final E obj : collection) { if (!remove.contains(obj)) { list.add(obj); } } return list; } //----------------------------------------------------------------------- /** * Returns a synchronized list backed by the given list. *

* You must manually synchronize on the returned list'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 is just a wrapper for {@link Collections#synchronizedList(List)}. * * @param the element type * @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(final List list) { return Collections.synchronizedList(list); } /** * Returns an unmodifiable list backed by the given list. *

* This method uses the implementation in the decorators subpackage. * * @param the element type * @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(final List list) { return UnmodifiableList.unmodifiableList(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 the element type * @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(final List list, final Predicate predicate) { return PredicatedList.predicatedList(list, predicate); } /** * Returns a transformed list backed by the given list. *

* This method returns a new list (decorating the specified list) that * will transform any new entries added to it. * Existing entries in the specified list will not be transformed. *

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

* Existing entries in the specified list will not be transformed. * If you want that behaviour, see {@link TransformedList#transformedList}. * * @param the element type * @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(final List list, final Transformer transformer) { return TransformedList.transformingList(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<Date> factory = new Factory<Date>() {
     *     public Date create() {
     *         return new Date();
     *     }
     * }
     * List<Date> lazy = ListUtils.lazyList(new ArrayList<Date>(), factory);
     * Date date = lazy.get(3);
     * 
* * After the above code is executed, date will refer to * 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 the element type * @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(final List list, final Factory factory) { return LazyList.lazyList(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 the element type * @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(final List list) { return FixedSizeList.fixedSizeList(list); } //----------------------------------------------------------------------- /** * Finds the first index in the given List which matches the given predicate. *

* If the input List or predicate is null, or no element of the List * matches the predicate, -1 is returned. * * @param the element type * @param list the List to search, may be null * @param predicate the predicate to use, may be null * @return the first index of an Object in the List which matches the predicate or -1 if none could be found */ public static int indexOf(final List list, final Predicate predicate) { if (list != null && predicate != null) { for (int i = 0; i < list.size(); i++) { final E item = list.get(i); if (predicate.evaluate(item)) { return i; } } } return -1; } //----------------------------------------------------------------------- /** * Returns the longest common subsequence (LCS) of two sequences (lists). * * @param the element type * @param a the first list * @param b the second list * @return the longest common subsequence * @throws IllegalArgumentException if either list is {@code null} * @since 4.0 */ public static List longestCommonSubsequence(final List a, final List b) { return longestCommonSubsequence( a, b, DefaultEquator.defaultEquator() ); } /** * Returns the longest common subsequence (LCS) of two sequences (lists). * * @param the element type * @param a the first list * @param b the second list * @param equator the equator used to test object equality * @return the longest common subsequence * @throws IllegalArgumentException if either list or the equator is {@code null} * @since 4.0 */ public static List longestCommonSubsequence(final List a, final List b, final Equator equator) { if (a == null || b == null) { throw new IllegalArgumentException("List must not be null"); } if (equator == null) { throw new IllegalArgumentException("Equator must not be null"); } final SequencesComparator comparator = new SequencesComparator(a, b, equator); final EditScript script = comparator.getScript(); final LcsVisitor visitor = new LcsVisitor(); script.visit(visitor); return visitor.getSubSequence(); } /** * Returns the longest common subsequence (LCS) of two {@link CharSequence} objects. *

* This is a convenience method for using {@link #longestCommonSubsequence(List, List)} * with {@link CharSequence} instances. * * @param a the first sequence * @param b the second sequence * @return the longest common subsequence as {@link String} * @throws IllegalArgumentException if either sequence is {@code null} * @since 4.0 */ public static String longestCommonSubsequence(final CharSequence a, final CharSequence b) { if (a == null || b == null) { throw new IllegalArgumentException("CharSequence must not be null"); } final List lcs = longestCommonSubsequence(new CharSequenceAsList( a ), new CharSequenceAsList( b )); final StringBuilder sb = new StringBuilder(); for ( Character ch : lcs ) { sb.append(ch); } return sb.toString(); } /** * A helper class used to construct the longest common subsequence. */ private static final class LcsVisitor implements CommandVisitor { private ArrayList sequence; public LcsVisitor() { sequence = new ArrayList(); } public void visitInsertCommand(final E object) {} public void visitDeleteCommand(final E object) {} public void visitKeepCommand(final E object) { sequence.add(object); } public List getSubSequence() { return sequence; } } /** * A simple wrapper to use a CharSequence as List. */ private static final class CharSequenceAsList extends AbstractList { private final CharSequence sequence; public CharSequenceAsList(final CharSequence sequence) { this.sequence = sequence; } @Override public Character get( int index ) { return Character.valueOf(sequence.charAt( index )); } @Override public int size() { return sequence.length(); } } //----------------------------------------------------------------------- /** * Returns consecutive {@link List#subList(int, int) sublists} of a * list, each of the same size (the final list may be smaller). For example, * partitioning a list containing {@code [a, b, c, d, e]} with a partition * size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing * two inner lists of three and two elements, all in the original order. *

* The outer list is unmodifiable, but reflects the latest state of the * source list. The inner lists are sublist views of the original list, * produced on demand using {@link List#subList(int, int)}, and are subject * to all the usual caveats about modification as explained in that API. *

* Adapted from http://code.google.com/p/guava-libraries/ * * @param the element type * @param list the list to return consecutive sublists of * @param size the desired size of each sublist (the last may be smaller) * @return a list of consecutive sublists * @throws IllegalArgumentException if list is {@code null} or size is not strictly positive * @since 4.0 */ public static List> partition(final List list, final int size) { if (list == null) { throw new IllegalArgumentException("List must not be null"); } if (size <= 0) { throw new IllegalArgumentException("Size must be greater than 0"); } return new Partition(list, size); } /** * Provides a partition view on a {@link List}. * @since 4.0 */ private static class Partition extends AbstractList> { private final List list; private final int size; private Partition(final List list, final int size) { this.list = list; this.size = size; } @Override public List get(final int index) { final int listSize = size(); if (listSize < 0) { throw new IllegalArgumentException("negative size: " + listSize); } if (index < 0) { throw new IndexOutOfBoundsException("Index " + index + " must not be negative"); } if (index >= listSize) { throw new IndexOutOfBoundsException("Index " + index + " must be less than size " + listSize); } final int start = index * size; final int end = Math.min(start + size, list.size()); return list.subList(start, end); } @Override public int size() { return (list.size() + size - 1) / size; } @Override public boolean isEmpty() { return list.isEmpty(); } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/MapIterator.java100664 10015 12243235516 30045 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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()) {
 *   String key = it.next();
 *   Integer value = it.getValue();
 *   it.setValue(value + 1);
 * }
 * 
* * @param the type of the keys in the map * @param the type of the values in the map * @since 3.0 * @version $Id: MapIterator.java 1469004 2013-04-17 17:37:03Z tn $ */ public interface MapIterator extends Iterator { /** * Checks to see if there are more entries still to be iterated. * * @return true if the iterator has more elements */ boolean hasNext(); /** * Gets the next key from the Map. * * @return the next key in the iteration * @throws java.util.NoSuchElementException if the iteration is finished */ K next(); //----------------------------------------------------------------------- /** * Gets the current key, which is the key returned by the last call * to next(). * * @return the current key * @throws IllegalStateException if next() has not yet been called */ K getKey(); /** * Gets the current value, which is the value associated with the last key * returned by next(). * * @return the current value * @throws IllegalStateException if next() has not yet been called */ V getValue(); //----------------------------------------------------------------------- /** * Removes the last returned key from the underlying Map (optional operation). *

* This method can be called once per call to next(). * * @throws UnsupportedOperationException if remove is not supported by the map * @throws IllegalStateException if next() has not yet been called * @throws IllegalStateException if remove() has already been called * since the last call to next() */ void remove(); /** * Sets the value associated with the current key (optional operation). * * @param value the new value * @return the previous value * @throws UnsupportedOperationException if setValue is not supported by the map * @throws IllegalStateException if next() has not yet been called * @throws IllegalStateException if remove() has been called since the * last call to next() */ V setValue(V value); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/OrderedMapIterator.java100664 3265 12243235516 31343 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * Defines an iterator that operates over an ordered Map. *

* This iterator allows both forward and reverse iteration through the map. * * @param the type of the keys in the map * @param the type of the values in the map * @since 3.0 * @version $Id: OrderedMapIterator.java 1469004 2013-04-17 17:37:03Z tn $ */ public interface OrderedMapIterator extends MapIterator, OrderedIterator { /** * Checks to see if there is a previous entry that can be iterated to. * * @return true if the iterator has a previous element */ boolean hasPrevious(); /** * Gets the previous key from the Map. * * @return the previous key in the iteration * @throws java.util.NoSuchElementException if the iteration is finished */ K previous(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/OrderedBidiMap.java100664 4107 12243235516 30415 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * 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. * * @param the type of the keys in the map * @param the type of the values in the map * * @since 3.0 * @version $Id: OrderedBidiMap.java 1543260 2013-11-19 00:47:22Z ggregory $ */ 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 */ OrderedBidiMap inverseBidiMap(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/CollectionUtils.java100664 223273 12243235517 30767 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; 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.ListIterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.bag.HashBag; import org.apache.commons.collections4.collection.PredicatedCollection; import org.apache.commons.collections4.collection.SynchronizedCollection; import org.apache.commons.collections4.collection.TransformedCollection; import org.apache.commons.collections4.collection.UnmodifiableBoundedCollection; import org.apache.commons.collections4.collection.UnmodifiableCollection; import org.apache.commons.collections4.functors.TruePredicate; import org.apache.commons.collections4.iterators.CollatingIterator; import org.apache.commons.collections4.iterators.PermutationIterator; /** * Provides utility methods and decorators for {@link Collection} instances. *

* NOTE: From 4.0, method parameters will take {@link Iterable} objects when possible. * * @since 1.0 * @version $Id: CollectionUtils.java 1540639 2013-11-11 08:54:12Z tn $ */ public class CollectionUtils { /** * Helper class to easily access cardinality properties of two collections. * @param the element type */ private static class CardinalityHelper { /** Contains the cardinality for each object in collection A. */ final Map cardinalityA; /** Contains the cardinality for each object in collection B. */ final Map cardinalityB; /** * Create a new CardinalityHelper for two collections. * @param a the first collection * @param b the second collection */ public CardinalityHelper(final Iterable a, final Iterable b) { cardinalityA = CollectionUtils.getCardinalityMap(a); cardinalityB = CollectionUtils.getCardinalityMap(b); } /** * Returns the maximum frequency of an object. * @param obj the object * @return the maximum frequency of the object */ public final int max(final Object obj) { return Math.max(freqA(obj), freqB(obj)); } /** * Returns the minimum frequency of an object. * @param obj the object * @return the minimum frequency of the object */ public final int min(final Object obj) { return Math.min(freqA(obj), freqB(obj)); } /** * Returns the frequency of this object in collection A. * @param obj the object * @return the frequency of the object in collection A */ public int freqA(final Object obj) { return getFreq(obj, cardinalityA); } /** * Returns the frequency of this object in collection B. * @param obj the object * @return the frequency of the object in collection B */ public int freqB(final Object obj) { return getFreq(obj, cardinalityB); } private final int getFreq(final Object obj, final Map freqMap) { final Integer count = freqMap.get(obj); if (count != null) { return count.intValue(); } return 0; } } /** * Helper class for set-related operations, e.g. union, subtract, intersection. * @param the element type */ private static class SetOperationCardinalityHelper extends CardinalityHelper implements Iterable { /** Contains the unique elements of the two collections. */ private final Set elements; /** Output collection. */ private final List newList; /** * Create a new set operation helper from the two collections. * @param a the first collection * @param b the second collection */ public SetOperationCardinalityHelper(final Iterable a, final Iterable b) { super(a, b); elements = new HashSet(); addAll(elements, a); addAll(elements, b); // the resulting list must contain at least each unique element, but may grow newList = new ArrayList(elements.size()); } public Iterator iterator() { return elements.iterator(); } /** * Add the object {@code count} times to the result collection. * @param obj the object to add * @param count the count */ public void setCardinality(final O obj, final int count) { for (int i = 0; i < count; i++) { newList.add(obj); } } /** * Returns the resulting collection. * @return the result */ public Collection list() { return newList; } } /** * 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. */ @SuppressWarnings("rawtypes") // we deliberately use the raw type here public static final Collection EMPTY_COLLECTION = UnmodifiableCollection.unmodifiableCollection(new ArrayList()); /** * CollectionUtils should not normally be instantiated. */ private CollectionUtils() {} /** * Returns the immutable EMPTY_COLLECTION with generic type safety. * * @see #EMPTY_COLLECTION * @since 4.0 * @param the element type * @return immutable empty collection */ @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type public static Collection emptyCollection() { return EMPTY_COLLECTION; } /** * Returns an immutable empty collection if the argument is null, * or the argument itself otherwise. * * @param the element type * @param collection the collection, possibly null * @return an empty collection if the argument is null */ @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type public static Collection emptyIfNull(final Collection collection) { return collection == null ? EMPTY_COLLECTION : collection; } /** * Returns a {@link Collection} containing the union of the given * {@link Iterable}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 Iterable}s. * * @param a the first collection, must not be null * @param b the second collection, must not be null * @param the generic type that is able to represent the types contained * in both input collections. * @return the union of the two collections * @see Collection#addAll */ public static Collection union(final Iterable a, final Iterable b) { final SetOperationCardinalityHelper helper = new SetOperationCardinalityHelper(a, b); for (final O obj : helper) { helper.setCardinality(obj, helper.max(obj)); } return helper.list(); } /** * Returns a {@link Collection} containing the intersection of the given * {@link Iterable}s. *

* The cardinality of each element in the returned {@link Collection} will * be equal to the minimum of the cardinality of that element in the two * given {@link Iterable}s. * * @param a the first collection, must not be null * @param b the second collection, must not be null * @param the generic type that is able to represent the types contained * in both input collections. * @return the intersection of the two collections * @see Collection#retainAll * @see #containsAny */ public static Collection intersection(final Iterable a, final Iterable b) { final SetOperationCardinalityHelper helper = new SetOperationCardinalityHelper(a, b); for (final O obj : helper) { helper.setCardinality(obj, helper.min(obj)); } return helper.list(); } /** * Returns a {@link Collection} containing the exclusive disjunction * (symmetric difference) of the given {@link Iterable}s. *

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

* This is equivalent to * {@link #subtract subtract}({@link #union union(a,b)},{@link #intersection intersection(a,b)}) * or * {@link #union union}({@link #subtract subtract(a,b)},{@link #subtract subtract(b,a)}). * @param a the first collection, must not be null * @param b the second collection, must not be null * @param the generic type that is able to represent the types contained * in both input collections. * @return the symmetric difference of the two collections */ public static Collection disjunction(final Iterable a, final Iterable b) { final SetOperationCardinalityHelper helper = new SetOperationCardinalityHelper(a, b); for (final O obj : helper) { helper.setCardinality(obj, helper.max(obj) - helper.min(obj)); } return helper.list(); } /** * Returns a new {@link Collection} containing a - b. * The cardinality of each element e in the returned {@link Collection} * will be the cardinality of e in a minus the cardinality * of e in b, or zero, whichever is greater. * * @param a the collection to subtract from, must not be null * @param b the collection to subtract, must not be null * @param the generic type that is able to represent the types contained * in both input collections. * @return a new collection with the results * @see Collection#removeAll */ public static Collection subtract(final Iterable a, final Iterable b) { final Predicate p = TruePredicate.truePredicate(); return subtract(a, b, p); } /** * Returns a new {@link Collection} containing a minus a subset of * b. Only the elements of b that satisfy the predicate * condition, p are subtracted from a. * *

The cardinality of each element e in the returned {@link Collection} * that satisfies the predicate condition will be the cardinality of e in a * minus the cardinality of e in b, or zero, whichever is greater.

*

The cardinality of each element e in the returned {@link Collection} that does not * satisfy the predicate condition will be equal to the cardinality of e in a.

* * @param a the collection to subtract from, must not be null * @param b the collection to subtract, must not be null * @param p the condition used to determine which elements of b are * subtracted. * @param the generic type that is able to represent the types contained * in both input collections. * @return a new collection with the results * @since 4.0 * @see Collection#removeAll */ public static Collection subtract(final Iterable a, final Iterable b, final Predicate p) { final ArrayList list = new ArrayList(); final HashBag bag = new HashBag(); for (final O element : b) { if (p.evaluate(element)) { bag.add(element); } } for (final O element : a) { if (!bag.remove(element, 1)) { list.add(element); } } return list; } /** * Returns true iff all elements of {@code coll2} are also contained * in {@code coll1}. The cardinality of values in {@code coll2} is not taken into account, * which is the same behavior as {@link Collection#containsAll(Collection)}. *

* In other words, this method returns true iff the * {@link #intersection} of coll1 and coll2 has the same cardinality as * the set of unique values from {@code coll2}. In case {@code coll2} is empty, {@code true} * will be returned. *

* This method is intended as a replacement for {@link Collection#containsAll(Collection)} * with a guaranteed runtime complexity of {@code O(n + m)}. Depending on the type of * {@link Collection} provided, this method will be much faster than calling * {@link Collection#containsAll(Collection)} instead, though this will come at the * cost of an additional space complexity O(n). * * @param coll1 the first collection, must not be null * @param coll2 the second collection, must not be null * @return true iff the intersection of the collections has the same cardinality * as the set of unique elements from the second collection * @since 4.0 */ public static boolean containsAll(final Collection coll1, final Collection coll2) { if (coll2.isEmpty()) { return true; } else { final Iterator it = coll1.iterator(); final Set elementsAlreadySeen = new HashSet(); for (final Object nextElement : coll2) { if (elementsAlreadySeen.contains(nextElement)) { continue; } boolean foundCurrentElement = false; while (it.hasNext()) { final Object p = it.next(); elementsAlreadySeen.add(p); if (nextElement == null ? p == null : nextElement.equals(p)) { foundCurrentElement = true; break; } } if (foundCurrentElement) { continue; } else { return false; } } return true; } } /** * 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 second 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 (final Object aColl1 : coll1) { if (coll2.contains(aColl1)) { return true; } } } else { for (final Object aColl2 : coll2) { if (coll1.contains(aColl2)) { 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 the type of object in the returned {@link Map}. This is a super type of . * @param coll the collection to get the cardinality map for, must not be null * @return the populated cardinality map */ public static Map getCardinalityMap(final Iterable coll) { final Map count = new HashMap(); for (final O obj : coll) { final Integer c = count.get(obj); if (c == null) { count.put(obj, Integer.valueOf(1)); } else { count.put(obj, Integer.valueOf(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) { final CardinalityHelper helper = new CardinalityHelper(a, b); for (final Object obj : a) { if (helper.freqA(obj) > helper.freqB(obj)) { 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; } final CardinalityHelper helper = new CardinalityHelper(a, b); if(helper.cardinalityA.size() != helper.cardinalityB.size()) { return false; } for( final Object obj : helper.cardinalityA.keySet()) { if(helper.freqA(obj) != helper.freqB(obj)) { return false; } } return true; } /** * 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 * @param equator the Equator used for testing equality * @return true iff the collections contain the same elements with the same cardinalities. * @throws IllegalArgumentException if the equator is null * @since 4.0 */ @SuppressWarnings({ "unchecked", "rawtypes" }) // we don't know the types due to wildcards in the signature public static boolean isEqualCollection(final Collection a, final Collection b, final Equator equator) { if (equator == null) { throw new IllegalArgumentException("equator may not be null"); } if(a.size() != b.size()) { return false; } final Transformer transformer = new Transformer() { public EquatorWrapper transform(final Object input) { return new EquatorWrapper(equator, input); } }; return isEqualCollection(collect(a, transformer), collect(b, transformer)); } /** * Wraps another object and uses the provided Equator to implement * {@link #equals(Object)} and {@link #hashCode()}. *

* This class can be used to store objects into a Map. * * @param the element type * @since 4.0 */ private static class EquatorWrapper { private final Equator equator; private final O object; public EquatorWrapper(final Equator equator, final O object) { this.equator = equator; this.object = object; } public O getObject() { return object; } @Override public boolean equals(final Object obj) { if (!(obj instanceof EquatorWrapper)) { return false; } @SuppressWarnings("unchecked") final EquatorWrapper otherObj = (EquatorWrapper) obj; return equator.equate(object, otherObj.getObject()); } @Override public int hashCode() { return equator.hash(object); } } /** * Returns the number of occurrences of obj in coll. * * @param obj the object to find the cardinality of * @param coll the {@link Iterable} to search * @param the type of object that the {@link Iterable} may contain. * @return the the number of occurrences of obj in coll */ public static int cardinality(final O obj, final Iterable coll) { if (coll instanceof Set) { return ((Set) coll).contains(obj) ? 1 : 0; } if (coll instanceof Bag) { return ((Bag) coll).getCount(obj); } int count = 0; if (obj == null) { for (final Object element : coll) { if (element == null) { count++; } } } else { for (final Object element : coll) { if (obj.equals(element)) { 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 the type of object the {@link Iterable} contains * @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 T find(final Iterable collection, final Predicate predicate) { if (collection != null && predicate != null) { for (final T item : collection) { 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 the type of object the {@link Iterable} contains * @param the closure type * @param collection the collection to get the input from, may be null * @param closure the closure to perform, may be null * @return closure */ public static > C forAllDo(final Iterable collection, final C closure) { if (collection != null && closure != null) { for (final T element : collection) { closure.execute(element); } } return closure; } /** * Executes the given closure on each element in the collection. *

* If the input collection or closure is null, there is no change made. * * @param the type of object the {@link Iterator} contains * @param the closure type * @param iterator the iterator to get the input from, may be null * @param closure the closure to perform, may be null * @return closure * @since 4.0 */ public static > C forAllDo(final Iterator iterator, final C closure) { if (iterator != null && closure != null) { while (iterator.hasNext()) { closure.execute(iterator.next()); } } return closure; } /** * Executes the given closure on each but the last element in the collection. *

* If the input collection or closure is null, there is no change made. * * @param the type of object the {@link Iterable} contains * @param the closure type * @param collection the collection to get the input from, may be null * @param closure the closure to perform, may be null * @return the last element in the collection, or null if either collection or closure is null * @since 4.0 */ public static > T forAllButLastDo(final Iterable collection, final C closure) { return collection != null && closure != null ? forAllButLastDo(collection.iterator(), closure) : null; } /** * Executes the given closure on each but the last element in the collection. *

* If the input collection or closure is null, there is no change made. * * @param the type of object the {@link Collection} contains * @param the closure type * @param iterator the iterator to get the input from, may be null * @param closure the closure to perform, may be null * @return the last element in the collection, or null if either iterator or closure is null * @since 4.0 */ public static > T forAllButLastDo(final Iterator iterator, final C closure) { if (iterator != null && closure != null) { while (iterator.hasNext()) { final T element = iterator.next(); if (iterator.hasNext()) { closure.execute(element); } else { return element; } } } return null; } /** * 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 the type of object the {@link Iterable} contains * @param collection the collection to get the input from, may be null * @param predicate the predicate to use as a filter, may be null * @return true if the collection is modified by this call, false otherwise. */ public static boolean filter(final Iterable collection, final Predicate predicate) { boolean result = false; if (collection != null && predicate != null) { for (final Iterator it = collection.iterator(); it.hasNext();) { if (!predicate.evaluate(it.next())) { it.remove(); result = true; } } } return result; } /** * Filter the collection by applying a Predicate to each element. If the * predicate returns true, remove the element. *

* This is equivalent to

filter(collection, PredicateUtils.notPredicate(predicate))
* if predicate is != null. *

* If the input collection or predicate is null, there is no change made. * * @param the type of object the {@link Iterable} contains * @param collection the collection to get the input from, may be null * @param predicate the predicate to use as a filter, may be null * @return true if the collection is modified by this call, false otherwise. */ public static boolean filterInverse(final Iterable collection, final Predicate predicate) { return filter(collection, predicate == null ? null : PredicateUtils.notPredicate(predicate)); } /** * 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 the type of object the {@link Collection} contains * @param collection the {@link Collection} to get the input from, may be null * @param transformer the transformer to perform, may be null */ public static void transform(final Collection collection, final Transformer transformer) { if (collection != null && transformer != null) { if (collection instanceof List) { final List list = (List) collection; for (final ListIterator it = list.listIterator(); it.hasNext();) { it.set(transformer.transform(it.next())); } } else { final 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 the type of object the {@link Iterable} contains * @param input the {@link Iterable} 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(final Iterable input, final Predicate predicate) { int count = 0; if (input != null && predicate != null) { for (final C o : input) { if (predicate.evaluate(o)) { 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 the type of object the {@link Iterable} contains * @param input the {@link Iterable} to get the input from, may be null * @param predicate the predicate to use, may be null * @return true if at least one element of the collection matches the predicate */ public static boolean exists(final Iterable input, final Predicate predicate) { if (input != null && predicate != null) { for (final C o : input) { if (predicate.evaluate(o)) { return true; } } } return false; } /** * Answers true if a predicate is true for every element of a * collection. *

* A null predicate returns false.
* A null or empty collection returns true. * * @param the type of object the {@link Iterable} contains * @param input the {@link Iterable} to get the input from, may be null * @param predicate the predicate to use, may be null * @return true if every element of the collection matches the predicate or if the * collection is empty, false otherwise * @since 4.0 */ public static boolean matchesAll(final Iterable input, final Predicate predicate) { if (predicate == null) { return false; } if (input != null) { for (final C o : input) { if (!predicate.evaluate(o)) { return false; } } } return true; } /** * Selects all elements from input collection which match the given * predicate into an output collection. *

* A null predicate matches no elements. * * @param the type of object the {@link Iterable} contains * @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(final Iterable inputCollection, final Predicate predicate) { final Collection answer = inputCollection instanceof Collection ? new ArrayList(((Collection) inputCollection).size()) : new ArrayList(); return select(inputCollection, predicate, 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 the type of object the {@link Iterable} contains * @param the type of the output {@link 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 if the inputCollection * and predicate or not null * @return the outputCollection */ public static > R select(final Iterable inputCollection, final Predicate predicate, final R outputCollection) { if (inputCollection != null && predicate != null) { for (final O item : inputCollection) { if (predicate.evaluate(item)) { outputCollection.add(item); } } } return outputCollection; } /** * Selects all elements from inputCollection which don't match the given * predicate into an output collection. *

* If the input predicate is null, the result is an empty * list. * * @param the type of object the {@link Iterable} contains * @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(final Iterable inputCollection, final Predicate predicate) { final Collection answer = inputCollection instanceof Collection ? new ArrayList(((Collection) inputCollection).size()) : new ArrayList(); return selectRejected(inputCollection, predicate, 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 the type of object the {@link Iterable} contains * @param the type of the output {@link 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 if the inputCollection * and predicate or not null * @return outputCollection */ public static > R selectRejected(final Iterable inputCollection, final Predicate predicate, final R outputCollection) { if (inputCollection != null && predicate != null) { for (final O item : inputCollection) { if (!predicate.evaluate(item)) { outputCollection.add(item); } } } return outputCollection; } /** * 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 the type of object in the input collection * @param the type of object in the output collection * @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(final Iterable inputCollection, final Transformer transformer) { final Collection answer = inputCollection instanceof Collection ? new ArrayList(((Collection) inputCollection).size()) : new ArrayList(); return collect(inputCollection, transformer, 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 * @param the type of object in the input collection * @param the type of object in the output collection * @return the transformed result (new list) */ public static Collection collect(final Iterator inputIterator, final Transformer transformer) { return collect(inputIterator, transformer, new ArrayList()); } /** * 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 the type of object in the input collection * @param the type of object in the output collection * @param the output type of the transformer - this extends O. * @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 if the inputCollection * and transformer are not null * @return the outputCollection with the transformed input added * @throws NullPointerException if the output collection is null and both, inputCollection and * transformer are not null */ public static > R collect(final Iterable inputCollection, final Transformer transformer, final R 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 if the inputCollection * and transformer are not null * @param the type of object in the input collection * @param the type of object in the output collection * @param the output type of the transformer - this extends O. * @return the outputCollection with the transformed input added * @throws NullPointerException if the output collection is null and both, inputCollection and * transformer are not null */ public static > R collect(final Iterator inputIterator, final Transformer transformer, final R outputCollection) { if (inputIterator != null && transformer != null) { while (inputIterator.hasNext()) { final I item = inputIterator.next(); final O value = transformer.transform(item); outputCollection.add(value); } } return outputCollection; } //----------------------------------------------------------------------- /** * Adds an element to the collection unless the element is null. * * @param the type of object the {@link Collection} contains * @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 3.2 */ public static boolean addIgnoreNull(final Collection collection, final T object) { if (collection == null) { throw new NullPointerException("The collection must not be null"); } return object != null && collection.add(object); } /** * Adds all elements in the {@link Iterable} to the given collection. If the * {@link Iterable} is a {@link Collection} then it is cast and will be * added using {@link Collection#addAll(Collection)} instead of iterating. * * @param the type of object the {@link Collection} contains * @param collection the collection to add to, must not be null * @param iterable the iterable of elements to add, must not be null * @return a boolean indicating whether the collection has changed or not. * @throws NullPointerException if the collection or iterator is null */ public static boolean addAll(final Collection collection, final Iterable iterable) { if (iterable instanceof Collection) { return collection.addAll((Collection) iterable); } return addAll(collection, iterable.iterator()); } /** * Adds all elements in the iteration to the given collection. * * @param the type of object the {@link Collection} contains * @param collection the collection to add to, must not be null * @param iterator the iterator of elements to add, must not be null * @return a boolean indicating whether the collection has changed or not. * @throws NullPointerException if the collection or iterator is null */ public static boolean addAll(final Collection collection, final Iterator iterator) { boolean changed = false; while (iterator.hasNext()) { changed |= collection.add(iterator.next()); } return changed; } /** * Adds all elements in the enumeration to the given collection. * * @param the type of object the {@link Collection} contains * @param collection the collection to add to, must not be null * @param enumeration the enumeration of elements to add, must not be null * @return {@code true} if the collections was changed, {@code false} otherwise * @throws NullPointerException if the collection or enumeration is null */ public static boolean addAll(final Collection collection, final Enumeration enumeration) { boolean changed = false; while (enumeration.hasMoreElements()) { changed |= collection.add(enumeration.nextElement()); } return changed; } /** * Adds all elements in the array to the given collection. * * @param the type of object the {@link Collection} contains * @param collection the collection to add to, must not be null * @param elements the array of elements to add, must not be null * @return {@code true} if the collection was changed, {@code false} otherwise * @throws NullPointerException if the collection or array is null */ public static boolean addAll(final Collection collection, final C[] elements) { boolean changed = false; for (final C element : elements) { changed |= collection.add(element); } return changed; } /** * Returns the index-th value in {@link Iterator}, throwing * IndexOutOfBoundsException if there is no such element. *

* The Iterator is advanced to index (or to the end, if * index exceeds the number of entries) as a side effect of this method. * * @param iterator the iterator to get a value from * @param index the index to get * @param the type of object in the {@link Iterator} * @return the object at the specified index * @throws IndexOutOfBoundsException if the index is invalid * @throws IllegalArgumentException if the object type is invalid */ public static T get(final Iterator iterator, final int index) { int i = index; checkIndexBounds(i); while (iterator.hasNext()) { i--; if (i == -1) { return iterator.next(); } iterator.next(); } throw new IndexOutOfBoundsException("Entry does not exist: " + i); } /** * Ensures an index is not negative. * @param index the index to check. * @throws IndexOutOfBoundsException if the index is negative. */ private static void checkIndexBounds(final int index) { if (index < 0) { throw new IndexOutOfBoundsException("Index cannot be negative: " + index); } } /** * Returns the index-th value in the iterable's {@link Iterator}, throwing * IndexOutOfBoundsException if there is no such element. *

* If the {@link Iterable} is a {@link List}, then it will use {@link List#get(int)}. * * @param iterable the {@link Iterable} to get a value from * @param index the index to get * @param the type of object in the {@link Iterable}. * @return the object at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ public static T get(final Iterable iterable, final int index) { checkIndexBounds(index); if (iterable instanceof List) { return ((List) iterable).get(index); } return get(iterable.iterator(), index); } /** * 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(final Object object, final int index) { int i = index; if (i < 0) { throw new IndexOutOfBoundsException("Index cannot be negative: " + i); } if (object instanceof Map) { final Map map = (Map) object; final Iterator iterator = map.entrySet().iterator(); return get(iterator, i); } else if (object instanceof Object[]) { return ((Object[]) object)[i]; } else if (object instanceof Iterator) { final Iterator it = (Iterator) object; while (it.hasNext()) { i--; if (i == -1) { return it.next(); } it.next(); } throw new IndexOutOfBoundsException("Entry does not exist: " + i); } else if (object instanceof Collection) { final Iterator iterator = ((Collection) object).iterator(); return get(iterator, i); } else if (object instanceof Enumeration) { final Enumeration it = (Enumeration) object; while (it.hasMoreElements()) { i--; if (i == -1) { return it.nextElement(); } else { it.nextElement(); } } throw new IndexOutOfBoundsException("Entry does not exist: " + i); } else if (object == null) { throw new IllegalArgumentException("Unsupported object type: null"); } else { try { return Array.get(object, i); } catch (final IllegalArgumentException ex) { throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName()); } } } /** * Returns the index-th Map.Entry in the map's entrySet, * throwing IndexOutOfBoundsException if there is no such element. * * @param the key type in the {@link Map} * @param the key type in the {@link Map} * @param map 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 */ public static Map.Entry get(final Map map, final int index) { checkIndexBounds(index); return get(map.entrySet(), index); } /** * 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, may be null * @return the size of the specified collection or 0 if the object was null * @throws IllegalArgumentException thrown if object is not recognised * @since 3.1 */ public static int size(final Object object) { if (object == null) { return 0; } 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) { final Iterator it = (Iterator) object; while (it.hasNext()) { total++; it.next(); } } else if (object instanceof Enumeration) { final Enumeration it = (Enumeration) object; while (it.hasMoreElements()) { total++; it.nextElement(); } } else { try { total = Array.getLength(object); } catch (final 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, may be null * @return true if empty or null * @throws IllegalArgumentException thrown if object is not recognised * @since 3.2 */ public static boolean sizeIsEmpty(final Object object) { if (object == null) { return true; } else 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 { try { return Array.getLength(object) == 0; } catch (final 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 3.2 */ public static boolean isEmpty(final 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 3.2 */ public static boolean isNotEmpty(final Collection coll) { return !isEmpty(coll); } //----------------------------------------------------------------------- /** * Reverses the order of the given array. * * @param array the array to reverse */ public static void reverseArray(final 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++; } } /** * 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(final Collection coll) { if (coll == null) { throw new NullPointerException("The collection must not be null"); } if (coll instanceof BoundedCollection) { return ((BoundedCollection) coll).isFull(); } try { final BoundedCollection bcoll = UnmodifiableBoundedCollection.unmodifiableBoundedCollection(coll); return bcoll.isFull(); } catch (final 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(final Collection coll) { if (coll == null) { throw new NullPointerException("The collection must not be null"); } if (coll instanceof BoundedCollection) { return ((BoundedCollection) coll).maxSize(); } try { final BoundedCollection bcoll = UnmodifiableBoundedCollection.unmodifiableBoundedCollection(coll); return bcoll.maxSize(); } catch (final IllegalArgumentException ex) { return -1; } } //----------------------------------------------------------------------- /** * Merges two sorted Collections, a and b, into a single, sorted List * such that the natural ordering of the elements is retained. *

* Uses the standard O(n) merge algorithm for combining two sorted lists. * * @param the element type * @param a the first collection, must not be null * @param b the second collection, must not be null * @return a new sorted List, containing the elements of Collection a and b * @throws IllegalArgumentException if either collection is null * @since 4.0 */ public static > List collate(Iterable a, Iterable b) { return collate(a, b, ComparatorUtils.naturalComparator(), true); } /** * Merges two sorted Collections, a and b, into a single, sorted List * such that the natural ordering of the elements is retained. *

* Uses the standard O(n) merge algorithm for combining two sorted lists. * * @param the element type * @param a the first collection, must not be null * @param b the second collection, must not be null * @param includeDuplicates if {@code true} duplicate elements will be retained, otherwise * they will be removed in the output collection * @return a new sorted List, containing the elements of Collection a and b * @throws IllegalArgumentException if either collection is null * @since 4.0 */ public static > List collate(final Iterable a, final Iterable b, final boolean includeDuplicates) { return collate(a, b, ComparatorUtils.naturalComparator(), includeDuplicates); } /** * Merges two sorted Collections, a and b, into a single, sorted List * such that the ordering of the elements according to Comparator c is retained. *

* Uses the standard O(n) merge algorithm for combining two sorted lists. * * @param the element type * @param a the first collection, must not be null * @param b the second collection, must not be null * @param c the comparator to use for the merge. * @return a new sorted List, containing the elements of Collection a and b * @throws IllegalArgumentException if either collection or the comparator is null * @since 4.0 */ public static List collate(final Iterable a, final Iterable b, final Comparator c) { return collate(a, b, c, true); } /** * Merges two sorted Collections, a and b, into a single, sorted List * such that the ordering of the elements according to Comparator c is retained. *

* Uses the standard O(n) merge algorithm for combining two sorted lists. * * @param the element type * @param a the first collection, must not be null * @param b the second collection, must not be null * @param c the comparator to use for the merge. * @param includeDuplicates if {@code true} duplicate elements will be retained, otherwise * they will be removed in the output collection * @return a new sorted List, containing the elements of Collection a and b * @throws IllegalArgumentException if either collection or the comparator is null * @since 4.0 */ public static List collate(final Iterable a, final Iterable b, final Comparator c, final boolean includeDuplicates) { if (a == null || b == null) { throw new IllegalArgumentException("The collections must not be null"); } if (c == null) { throw new IllegalArgumentException("The comparator must not be null"); } // if both Iterables are a Collection, we can estimate the size final int totalSize = a instanceof Collection && b instanceof Collection ? Math.max(1, ((Collection) a).size() + ((Collection) b).size()) : 10; final Iterator iterator = new CollatingIterator(c, a.iterator(), b.iterator()); if (includeDuplicates) { return IteratorUtils.toList(iterator, totalSize); } else { final ArrayList mergedList = new ArrayList(totalSize); O lastItem = null; while (iterator.hasNext()) { final O item = iterator.next(); if (lastItem == null || !lastItem.equals(item)) { mergedList.add(item); } lastItem = item; } mergedList.trimToSize(); return mergedList; } } //----------------------------------------------------------------------- /** * Returns a {@link Collection} of all the permutations of the input collection. *

* NOTE: the number of permutations of a given collection is equal to n!, where * n is the size of the collection. Thus, the resulting collection will become * very large for collections > 10 (e.g. 10! = 3628800, 15! = 1307674368000). *

* For larger collections it is advised to use a {@link PermutationIterator} to * iterate over all permutations. * * @see PermutationIterator * * @param the element type * @param collection the collection to create permutations for, may not be null * @return an unordered collection of all permutations of the input collection * @throws NullPointerException if collection is null * @since 4.0 */ public static Collection> permutations(final Collection collection) { final PermutationIterator it = new PermutationIterator(collection); final Collection> result = new LinkedList>(); while (it.hasNext()) { result.add(it.next()); } return result; } //----------------------------------------------------------------------- /** * 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 the type of object the {@link Collection} contains * @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 3.2 */ public static Collection retainAll(final Collection collection, final 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 the type of object the {@link Collection} contains * @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 4.0 (method existed in 3.2 but was completely broken) */ public static Collection removeAll(final Collection collection, final Collection remove) { return ListUtils.removeAll(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 the type of object the {@link Collection} contains * @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(final Collection collection) { return SynchronizedCollection.synchronizedCollection(collection); } /** * Returns an unmodifiable collection backed by the given collection. *

* This method uses the implementation in the decorators subpackage. * * @param the type of object the {@link Collection} contains * @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(final Collection collection) { return UnmodifiableCollection.unmodifiableCollection(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 * @param the type of objects in the Collection. * @return a predicated collection backed by the given collection * @throws IllegalArgumentException if the Collection is null */ public static Collection predicatedCollection(final Collection collection, final Predicate predicate) { return PredicatedCollection.predicatedCollection(collection, predicate); } /** * 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. *

* Existing entries in the specified collection will not be transformed. * If you want that behaviour, see {@link TransformedCollection#transformedCollection}. * * @param the type of object the {@link Collection} contains * @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 transformingCollection(final Collection collection, final Transformer transformer) { return TransformedCollection.transformingCollection(collection, transformer); } /** * Extract the lone element of the specified Collection. * @param collection type * @param collection to read * @return sole member of collection * @throws IllegalArgumentException if collection is null/empty or contains more than one element * @since 4.0 */ public static E extractSingleton(final Collection collection) { if (collection == null || collection.size() != 1) { throw new IllegalArgumentException("Can extract singleton only when collection size == 1"); } return collection.iterator().next(); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/IterableMap.java100664 3150 12243235516 27765 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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 use Map Entry objects. *

 * IterableMap map = new HashedMap();
 * MapIterator it = map.mapIterator();
 * while (it.hasNext()) {
 *   String key = it.next();
 *   Integer value = it.getValue();
 *   it.setValue(value + 1);
 * }
 * 
* * @param the type of the keys in the map * @param the type of the values in the map * * @since 3.0 * @version $Id: IterableMap.java 1469004 2013-04-17 17:37:03Z tn $ */ public interface IterableMap extends Map, Put, IterableGet { } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/ArrayStack.java100664 13055 12243235516 27671 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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. *

* Unlike Stack, ArrayStack accepts null entries. *

* Note: From version 4.0 onwards, this class does not implement the * removed {@code Buffer} interface anymore. * * @see java.util.Stack * @since 1.0 * @version $Id: ArrayStack.java 1477779 2013-04-30 18:55:24Z tn $ * @deprecated use {@link java.util.ArrayDeque} instead (available from Java 1.6) */ @Deprecated public class ArrayStack extends ArrayList { /** 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(final int initialSize) { super(initialSize); } /** * Return true if this stack is currently empty. *

* This method exists for compatibility with java.util.Stack. * New users of this class should use isEmpty instead. * * @return true if the stack is currently empty */ public boolean empty() { return isEmpty(); } /** * Returns the top item off of this stack without removing it. * * @return the top item on the stack * @throws EmptyStackException if the stack is empty */ public E peek() throws EmptyStackException { final int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return get(n - 1); } } /** * Returns the n'th item down (zero-relative) from the top of this * stack without removing it. * * @param n the number of items down to go * @return the n'th item on the stack, zero relative * @throws EmptyStackException if there are not enough items on the * stack to satisfy this request */ public E peek(final int n) throws EmptyStackException { final int m = (size() - n) - 1; if (m < 0) { throw new EmptyStackException(); } else { return get(m); } } /** * Pops the top item off of this stack and return it. * * @return the top item on the stack * @throws EmptyStackException if the stack is empty */ public E pop() throws EmptyStackException { final int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return remove(n - 1); } } /** * Pushes a new item onto the top of this stack. The pushed item is also * returned. This is equivalent to calling add. * * @param item the item to be added * @return the item just pushed */ public E push(final E item) { add(item); return item; } /** * Returns the one-based position of the distance from the top that the * specified object exists on this stack, where the top-most element is * considered to be at distance 1. If the object is not * present on the stack, return -1 instead. The * equals() method is used to compare to the items * in this stack. * * @param object the object to be searched for * @return the 1-based depth into the stack of the object, or -1 if not found */ public int search(final Object object) { int i = size() - 1; // Current index int n = 1; // Current distance while (i >= 0) { final Object current = get(i); if ((object == null && current == null) || (object != null && object.equals(current))) { return n; } i--; n++; } return -1; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/IteratorUtils.java100664 130200 12243235516 30447 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; 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.collections4.iterators.ArrayIterator; import org.apache.commons.collections4.iterators.ArrayListIterator; import org.apache.commons.collections4.iterators.CollatingIterator; import org.apache.commons.collections4.iterators.EmptyIterator; import org.apache.commons.collections4.iterators.EmptyListIterator; import org.apache.commons.collections4.iterators.EmptyMapIterator; import org.apache.commons.collections4.iterators.EmptyOrderedIterator; import org.apache.commons.collections4.iterators.EmptyOrderedMapIterator; import org.apache.commons.collections4.iterators.EnumerationIterator; import org.apache.commons.collections4.iterators.FilterIterator; import org.apache.commons.collections4.iterators.FilterListIterator; import org.apache.commons.collections4.iterators.IteratorChain; import org.apache.commons.collections4.iterators.IteratorEnumeration; import org.apache.commons.collections4.iterators.IteratorIterable; import org.apache.commons.collections4.iterators.ListIteratorWrapper; import org.apache.commons.collections4.iterators.LoopingIterator; import org.apache.commons.collections4.iterators.LoopingListIterator; import org.apache.commons.collections4.iterators.NodeListIterator; import org.apache.commons.collections4.iterators.ObjectArrayIterator; import org.apache.commons.collections4.iterators.ObjectArrayListIterator; import org.apache.commons.collections4.iterators.ObjectGraphIterator; import org.apache.commons.collections4.iterators.PeekingIterator; import org.apache.commons.collections4.iterators.PushbackIterator; import org.apache.commons.collections4.iterators.SingletonIterator; import org.apache.commons.collections4.iterators.SingletonListIterator; import org.apache.commons.collections4.iterators.TransformIterator; import org.apache.commons.collections4.iterators.UnmodifiableIterator; import org.apache.commons.collections4.iterators.UnmodifiableListIterator; import org.apache.commons.collections4.iterators.UnmodifiableMapIterator; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * 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 incompatibilities 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 2.1 * @version $Id: IteratorUtils.java 1543964 2013-11-20 21:53:39Z tn $ */ 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 compatibility with Commons Collections 2.1.1. */ @SuppressWarnings("rawtypes") 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 compatibility with Commons Collections 2.1.1. */ @SuppressWarnings("rawtypes") public static final ResettableListIterator EMPTY_LIST_ITERATOR = EmptyListIterator.RESETTABLE_INSTANCE; /** * An ordered iterator over no elements. */ @SuppressWarnings("rawtypes") public static final OrderedIterator EMPTY_ORDERED_ITERATOR = EmptyOrderedIterator.INSTANCE; /** * A map iterator over no elements. */ @SuppressWarnings("rawtypes") public static final MapIterator EMPTY_MAP_ITERATOR = EmptyMapIterator.INSTANCE; /** * An ordered map iterator over no elements. */ @SuppressWarnings("rawtypes") public static final OrderedMapIterator EMPTY_ORDERED_MAP_ITERATOR = EmptyOrderedMapIterator.INSTANCE; /** * IteratorUtils is not normally instantiated. */ private 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 compatibility with Commons Collections 2.1.1. * * @param the element type * @return an iterator over nothing */ public static ResettableIterator emptyIterator() { return EmptyIterator.resettableEmptyIterator(); } /** * 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 compatibility with Commons Collections 2.1.1. * * @param the element type * @return a list iterator over nothing */ public static ResettableListIterator emptyListIterator() { return EmptyListIterator.resettableEmptyListIterator(); } /** * Gets an empty ordered iterator. *

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

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

* This iterator is a valid map iterator object that will iterate * over nothing. * * @param the key type * @param the value type * @return a map iterator over nothing */ public static OrderedMapIterator emptyOrderedMapIterator() { return EmptyOrderedMapIterator.emptyOrderedMapIterator(); } // 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 compatibility. * * @param the element type * @param object the single object over which to iterate * @return a singleton iterator over the object */ public static ResettableIterator singletonIterator(final E object) { return new SingletonIterator(object); } /** * Gets a singleton list iterator. *

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

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

* This method will handle primitive arrays as well as object arrays. * The primitives will be wrapped in the appropriate wrapper class. * * @param the element type * @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(final 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 compatibility. * * @param the element type * @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(final E[] array, final 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 the element type * @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(final Object array, final 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 compatibility. * * @param the element type * @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(final E[] array, final int start, final 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 the element type * @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 or end is before start * @throws IndexOutOfBoundsException if array bounds are invalid * @throws NullPointerException if array is null */ public static ResettableIterator arrayIterator(final Object array, final int start, final int end) { return new ArrayIterator(array, start, end); } //----------------------------------------------------------------------- /** * Gets a list iterator over an object array. * * @param the element type * @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(final E... array) { return new ObjectArrayListIterator(array); } /** * Gets a list iterator over an object or primitive array. *

* This method will handle primitive arrays as well as object arrays. * The primitives will be wrapped in the appropriate wrapper class. * * @param the element type * @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(final Object array) { return new ArrayListIterator(array); } /** * Gets a list iterator over the end part of an object array. * * @param the element type * @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(final E[] array, final 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 the element type * @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(final Object array, final int start) { return new ArrayListIterator(array, start); } /** * Gets a list iterator over part of an object array. * * @param the element type * @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(final E[] array, final int start, final 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 the element type * @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 or end is before start * @throws IndexOutOfBoundsException if array bounds are invalid * @throws NullPointerException if array is null */ public static ResettableListIterator arrayListIterator(final Object array, final int start, final 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 the element type * @param iterator the iterator to make immutable * @return an immutable version of the iterator */ public static Iterator unmodifiableIterator(final Iterator iterator) { return UnmodifiableIterator.unmodifiableIterator(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 the element type * @param listIterator the iterator to make immutable * @return an immutable version of the iterator */ public static ListIterator unmodifiableListIterator(final ListIterator listIterator) { return UnmodifiableListIterator.umodifiableListIterator(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 the key type * @param the value type * @param mapIterator the iterator to make immutable * @return an immutable version of the iterator */ public static MapIterator unmodifiableMapIterator(final MapIterator mapIterator) { return UnmodifiableMapIterator.unmodifiableMapIterator(mapIterator); } // Chained //----------------------------------------------------------------------- /** * Gets an iterator that iterates through two {@link Iterator}s * one after another. * * @param the element type * @param iterator1 the first iterator to use, not null * @param iterator2 the second iterator to use, not null * @return a combination iterator over the iterators * @throws NullPointerException if either iterator is null */ public static Iterator chainedIterator(final Iterator iterator1, final Iterator iterator2) { // keep a version with two iterators to avoid the following warning in client code (Java 5 & 6) // "A generic array of E is created for a varargs parameter" return new IteratorChain(iterator1, iterator2); } /** * Gets an iterator that iterates through an array of {@link Iterator}s * one after another. * * @param the element type * @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(final Iterator... iterators) { return new IteratorChain(iterators); } /** * Gets an iterator that iterates through a collections of {@link Iterator}s * one after another. * * @param the element type * @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(final 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 the element type * @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(final Comparator comparator, final Iterator iterator1, final 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 the element type * @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 value */ public static Iterator collatedIterator(final Comparator comparator, final 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 the element type * @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(final Comparator comparator, final 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 the element type * @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 3.1 */ public static Iterator objectGraphIterator(final E root, final 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 the input type * @param the output type * @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(final Iterator iterator, final 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 the element type * @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(final Iterator iterator, final 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 the element type * @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(final ListIterator listIterator, final 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 the element type * @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(final 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 the element type * @param list the list to iterate over, not null * @return a new looping iterator * @throws NullPointerException if the list is null * @since 3.2 */ public static ResettableListIterator loopingListIterator(final List list) { if (list == null) { throw new NullPointerException("List must not be null"); } return new LoopingListIterator(list); } // org.w3c.dom.NodeList iterators //----------------------------------------------------------------------- /** * Gets an {@link Iterator} that wraps the specified {@link NodeList}. * The returned {@link Iterator} can be used for a single iteration. * * @param nodeList the node list to use, not null * @return a new, single use {@link Iterator} * @throws NullPointerException if nodeList is null * @since 4.0 */ public static NodeListIterator nodeListIterator(final NodeList nodeList) { if (nodeList == null) { throw new NullPointerException("NodeList must not be null"); } return new NodeListIterator(nodeList); } /** * Gets an {@link Iterator} that wraps the specified node's childNodes. * The returned {@link Iterator} can be used for a single iteration. *

* Convenience method, allows easy iteration over NodeLists: *

     *   Iterator<Node> iterator = IteratorUtils.nodeListIterator(node);
     *   for(Node childNode : IteratorUtils.asIterable(iterator)) {
     *     ...
     *   }
     * 
* * @param node the node to use, not null * @return a new, single use {@link Iterator} * @throws NullPointerException if node is null * @since 4.0 */ public static NodeListIterator nodeListIterator(final Node node) { if (node == null) { throw new NullPointerException("Node must not be null"); } return new NodeListIterator(node); } // Peeking //----------------------------------------------------------------------- /** * Gets an iterator that supports one-element lookahead. * * @param the element type * @param iterator the iterator to decorate, not null * @return a peeking iterator * @throws NullPointerException if the iterator is null * @since 4.0 */ public static Iterator peekingIterator(final Iterator iterator) { return PeekingIterator.peekingIterator(iterator); } // Pushback //----------------------------------------------------------------------- /** * Gets an iterator that supports pushback of elements. * * @param the element type * @param iterator the iterator to decorate, not null * @return a pushback iterator * @throws NullPointerException if the iterator is null * @since 4.0 */ public static Iterator pushbackIterator(final Iterator iterator) { return PushbackIterator.pushbackIterator(iterator); } // Views //----------------------------------------------------------------------- /** * Gets an iterator that provides an iterator view of the given enumeration. * * @param the element type * @param enumeration the enumeration to use * @return a new iterator */ public static Iterator asIterator(final 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 the element type * @param enumeration the enumeration to use * @param removeCollection the collection to remove elements from * @return a new iterator */ public static Iterator asIterator(final Enumeration enumeration, final 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 the element type * @param iterator the iterator to use, not null * @return a new enumeration * @throws NullPointerException if iterator is null */ public static Enumeration asEnumeration(final Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } return new IteratorEnumeration(iterator); } /** * Gets an {@link Iterable} that wraps an iterator. The returned {@link Iterable} can be * used for a single iteration. * * @param the element type * @param iterator the iterator to use, not null * @return a new, single use {@link Iterable} * @throws NullPointerException if iterator is null */ public static Iterable asIterable(final Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } return new IteratorIterable(iterator, false); } /** * Gets an iterable that wraps an iterator. The returned iterable can be * used for multiple iterations. * * @param the element type * @param iterator the iterator to use, not null * @return a new, multiple use iterable * @throws NullPointerException if iterator is null */ public static Iterable asMultipleUseIterable(final Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } return new IteratorIterable(iterator, true); } /** * 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 the element type * @param iterator the iterator to use, not null * @return a new iterator * @throws NullPointerException if iterator parameter is null */ public static ListIterator toListIterator(final 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(final Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } final 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 the element type * @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 or arrayClass is null * @throws ClassCastException if the arrayClass is invalid */ public static E[] toArray(final Iterator iterator, final 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"); } final List list = toList(iterator, 100); @SuppressWarnings("unchecked") // as per Javadoc, will throw CCE if class is wrong final E[] array = (E[]) Array.newInstance(arrayClass, list.size()); return list.toArray(array); } /** * 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 the element type * @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(final 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 the element type * @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(final Iterator iterator, final 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"); } final 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 handle 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 *
  • NodeList - iterator over the list *
  • Node - iterator over the child nodes *
* * @param obj the object to convert to an iterator * @return a suitable iterator, never null */ public static Iterator getIterator(final Object obj) { if (obj == null) { return emptyIterator(); } if (obj instanceof Iterator) { return (Iterator) obj; } if (obj instanceof Collection) { return ((Collection) obj).iterator(); } if (obj instanceof Object[]) { return new ObjectArrayIterator((Object[]) obj); } if (obj instanceof Enumeration) { return new EnumerationIterator((Enumeration) obj); } if (obj instanceof Map) { return ((Map) obj).values().iterator(); } if (obj instanceof NodeList) { return new NodeListIterator((NodeList) obj); } if (obj instanceof Node) { return new NodeListIterator((Node) obj); } if (obj instanceof Dictionary) { return new EnumerationIterator(((Dictionary) obj).elements()); } else if (obj.getClass().isArray()) { return new ArrayIterator(obj); } try { final Method method = obj.getClass().getMethod("iterator", (Class[]) null); if (Iterator.class.isAssignableFrom(method.getReturnType())) { final Iterator it = (Iterator) method.invoke(obj, (Object[]) null); if (it != null) { return it; } } } catch (final RuntimeException e) { // NOPMD // ignore } catch (final NoSuchMethodException e) { // NOPMD // ignore } catch (final IllegalAccessException e) { // NOPMD // ignore } catch (final InvocationTargetException e) { // NOPMD // ignore } return singletonIterator(obj); } } ././@LongLink100644 0 0 170 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/AbstractOrderedBidiMapDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/AbstractOrderedBi100664 5562 12243235516 31621 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import org.apache.commons.collections4.OrderedBidiMap; import org.apache.commons.collections4.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 3.0 * @version $Id: AbstractOrderedBidiMapDecorator.java 1477745 2013-04-30 18:08:32Z tn $ */ 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(final OrderedBidiMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ @Override protected OrderedBidiMap decorated() { return (OrderedBidiMap) super.decorated(); } //----------------------------------------------------------------------- @Override public OrderedMapIterator mapIterator() { return decorated().mapIterator(); } public K firstKey() { return decorated().firstKey(); } public K lastKey() { return decorated().lastKey(); } public K nextKey(final K key) { return decorated().nextKey(key); } public K previousKey(final K key) { return decorated().previousKey(key); } @Override public OrderedBidiMap inverseBidiMap() { return decorated().inverseBidiMap(); } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/DualLinkedHashBidiMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/DualLinkedHashBid100664 7466 12243235516 31542 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.collections4.BidiMap; /** * Implementation of BidiMap that uses two LinkedHashMap instances. *

* Two LinkedHashMap instances are used in this class. * This provides fast lookups at the expense of storing two sets of map entries and two linked lists. * * @version $Id: DualLinkedHashBidiMap.java 1533984 2013-10-20 21:12:51Z tn $ * @since 4.0 */ public class DualLinkedHashBidiMap extends AbstractDualBidiMap implements Serializable { /** Ensure serialization compatibility */ private static final long serialVersionUID = 721969328361810L; /** * Creates an empty HashBidiMap. */ public DualLinkedHashBidiMap() { super(new LinkedHashMap(), new LinkedHashMap()); } /** * Constructs a LinkedHashBidiMap and copies the mappings from * specified Map. * * @param map the map whose mappings are to be placed in this map */ public DualLinkedHashBidiMap(final Map map) { super(new LinkedHashMap(), new LinkedHashMap()); putAll(map); } /** * Constructs a LinkedHashBidiMap that decorates the specified maps. * * @param normalMap the normal direction map * @param reverseMap the reverse direction map * @param inverseBidiMap the inverse BidiMap */ protected DualLinkedHashBidiMap(final Map normalMap, final Map reverseMap, final 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 */ @Override protected BidiMap createBidiMap(final Map normalMap, final Map reverseMap, final BidiMap inverseBidiMap) { return new DualLinkedHashBidiMap(normalMap, reverseMap, inverseBidiMap); } // Serialization //----------------------------------------------------------------------- private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(normalMap); } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); normalMap = new LinkedHashMap(); reverseMap = new LinkedHashMap(); @SuppressWarnings("unchecked") // will fail at runtime if stream is incorrect final Map map = (Map) in.readObject(); putAll(map); } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/UnmodifiableOrderedBidiMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/UnmodifiableOrder100664 11757 12243235516 31713 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.OrderedBidiMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableOrderedMapIterator; import org.apache.commons.collections4.map.UnmodifiableEntrySet; /** * Decorates another {@link OrderedBidiMap} to ensure it can't be altered. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableOrderedBidiMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 the key type * @param the value type * @param map the map to decorate, must not be null * @return an unmodifiable OrderedBidiMap * @throws IllegalArgumentException if map is null * @since 4.0 */ public static OrderedBidiMap unmodifiableOrderedBidiMap( final OrderedBidiMap map) { if (map instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final OrderedBidiMap tmpMap = (OrderedBidiMap) map; return tmpMap; } 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 */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableOrderedBidiMap(final OrderedBidiMap map) { super((OrderedBidiMap) map); } //----------------------------------------------------------------------- @Override public void clear() { throw new UnsupportedOperationException(); } @Override public V put(final K key, final V value) { throw new UnsupportedOperationException(); } @Override public void putAll(final Map mapToCopy) { throw new UnsupportedOperationException(); } @Override public V remove(final Object key) { throw new UnsupportedOperationException(); } @Override public Set> entrySet() { final Set> set = super.entrySet(); return UnmodifiableEntrySet.unmodifiableEntrySet(set); } @Override public Set keySet() { final Set set = super.keySet(); return UnmodifiableSet.unmodifiableSet(set); } @Override public Set values() { final Set set = super.values(); return UnmodifiableSet.unmodifiableSet(set); } //----------------------------------------------------------------------- @Override public K removeValue(final Object value) { throw new UnsupportedOperationException(); } @Override public OrderedBidiMap inverseBidiMap() { return inverseOrderedBidiMap(); } //----------------------------------------------------------------------- @Override public OrderedMapIterator mapIterator() { final OrderedMapIterator it = decorated().mapIterator(); return UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(it); } /** * Gets an unmodifiable view of this map where the keys and values are reversed. * * @return an inverted unmodifiable bidirectional map */ public OrderedBidiMap inverseOrderedBidiMap() { if (inverse == null) { inverse = new UnmodifiableOrderedBidiMap(decorated().inverseBidiMap()); inverse.inverse = this; } return inverse; } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/UnmodifiableSortedBidiMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/UnmodifiableSorte100664 12725 12243235516 31730 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.Map; import java.util.Set; import java.util.SortedMap; import org.apache.commons.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.SortedBidiMap; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableOrderedMapIterator; import org.apache.commons.collections4.map.UnmodifiableEntrySet; import org.apache.commons.collections4.map.UnmodifiableSortedMap; /** * Decorates another {@link SortedBidiMap} to ensure it can't be altered. *

* Attempts to modify it will result in an {@link UnsupportedOperationException}. * * @since 3.0 * @version $Id: UnmodifiableSortedBidiMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 the key type * @param the value type * @param map the map to decorate, must not be null * @return an unmodifiable SortedBidiMap * @throws IllegalArgumentException if map is null * @since 4.0 */ public static SortedBidiMap unmodifiableSortedBidiMap(final SortedBidiMap map) { if (map instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final SortedBidiMap tmpMap = (SortedBidiMap) map; return tmpMap; } 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 */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableSortedBidiMap(final SortedBidiMap map) { super((SortedBidiMap) map); } //----------------------------------------------------------------------- @Override public void clear() { throw new UnsupportedOperationException(); } @Override public V put(final K key, final V value) { throw new UnsupportedOperationException(); } @Override public void putAll(final Map mapToCopy) { throw new UnsupportedOperationException(); } @Override public V remove(final Object key) { throw new UnsupportedOperationException(); } @Override public Set> entrySet() { final Set> set = super.entrySet(); return UnmodifiableEntrySet.unmodifiableEntrySet(set); } @Override public Set keySet() { final Set set = super.keySet(); return UnmodifiableSet.unmodifiableSet(set); } @Override public Set values() { final Set set = super.values(); return UnmodifiableSet.unmodifiableSet(set); } //----------------------------------------------------------------------- @Override public K removeValue(final Object value) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- @Override public OrderedMapIterator mapIterator() { final OrderedMapIterator it = decorated().mapIterator(); return UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(it); } //----------------------------------------------------------------------- @Override public SortedBidiMap inverseBidiMap() { if (inverse == null) { inverse = new UnmodifiableSortedBidiMap(decorated().inverseBidiMap()); inverse.inverse = this; } return inverse; } @Override public SortedMap subMap(final K fromKey, final K toKey) { final SortedMap sm = decorated().subMap(fromKey, toKey); return UnmodifiableSortedMap.unmodifiableSortedMap(sm); } @Override public SortedMap headMap(final K toKey) { final SortedMap sm = decorated().headMap(toKey); return UnmodifiableSortedMap.unmodifiableSortedMap(sm); } @Override public SortedMap tailMap(final K fromKey) { final SortedMap sm = decorated().tailMap(fromKey); return UnmodifiableSortedMap.unmodifiableSortedMap(sm); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/DualTreeBidiMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/DualTreeBidiMap.j100664 32761 12243235516 31502 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.BidiMap; import org.apache.commons.collections4.OrderedBidiMap; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.ResettableIterator; import org.apache.commons.collections4.SortedBidiMap; import org.apache.commons.collections4.map.AbstractSortedMapDecorator; /** * Implementation of {@link BidiMap} that uses two {@link 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 {@link TreeMap} * and the flawed createMap method is ignored. * * @since 3.0 * @version $Id: DualTreeBidiMap.java 1533984 2013-10-20 21:12:51Z tn $ */ public class DualTreeBidiMap extends AbstractDualBidiMap implements SortedBidiMap, Serializable { /** Ensure serialization compatibility */ private static final long serialVersionUID = 721969328361809L; /** The key comparator to use */ private final Comparator comparator; /** The value comparator to use */ private final Comparator valueComparator; /** * Creates an empty DualTreeBidiMap */ public DualTreeBidiMap() { super(new TreeMap(), new TreeMap()); this.comparator = null; this.valueComparator = 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(final Map map) { super(new TreeMap(), new TreeMap()); putAll(map); this.comparator = null; this.valueComparator = null; } /** * Constructs a {@link DualTreeBidiMap} using the specified {@link Comparator}. * * @param keyComparator the comparator * @param valueComparator the values comparator to use */ public DualTreeBidiMap(final Comparator keyComparator, final Comparator valueComparator) { super(new TreeMap(keyComparator), new TreeMap(valueComparator)); this.comparator = keyComparator; this.valueComparator = valueComparator; } /** * Constructs a {@link 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(final Map normalMap, final Map reverseMap, final BidiMap inverseBidiMap) { super(normalMap, reverseMap, inverseBidiMap); this.comparator = ((SortedMap) normalMap).comparator(); this.valueComparator = ((SortedMap) reverseMap).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 */ @Override protected DualTreeBidiMap createBidiMap(final Map normalMap, final Map reverseMap, final BidiMap inverseMap) { return new DualTreeBidiMap(normalMap, reverseMap, inverseMap); } //----------------------------------------------------------------------- public Comparator comparator() { return ((SortedMap) normalMap).comparator(); } public Comparator valueComparator() { return ((SortedMap) reverseMap).comparator(); } public K firstKey() { return ((SortedMap) normalMap).firstKey(); } public K lastKey() { return ((SortedMap) normalMap).lastKey(); } public K nextKey(final K key) { if (isEmpty()) { return null; } if (normalMap instanceof OrderedMap) { return ((OrderedMap) normalMap).nextKey(key); } final SortedMap sm = (SortedMap) normalMap; final Iterator it = sm.tailMap(key).keySet().iterator(); it.next(); if (it.hasNext()) { return it.next(); } return null; } public K previousKey(final K key) { if (isEmpty()) { return null; } if (normalMap instanceof OrderedMap) { return ((OrderedMap) normalMap).previousKey(key); } final SortedMap sm = (SortedMap) normalMap; final 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 */ @Override public OrderedMapIterator mapIterator() { return new BidiOrderedMapIterator(this); } public SortedBidiMap inverseSortedBidiMap() { return inverseBidiMap(); } public OrderedBidiMap inverseOrderedBidiMap() { return inverseBidiMap(); } //----------------------------------------------------------------------- public SortedMap headMap(final K toKey) { final SortedMap sub = ((SortedMap) normalMap).headMap(toKey); return new ViewMap(this, sub); } public SortedMap tailMap(final K fromKey) { final SortedMap sub = ((SortedMap) normalMap).tailMap(fromKey); return new ViewMap(this, sub); } public SortedMap subMap(final K fromKey, final K toKey) { final SortedMap sub = ((SortedMap) normalMap).subMap(fromKey, toKey); return new ViewMap(this, sub); } @Override public SortedBidiMap inverseBidiMap() { return (SortedBidiMap) super.inverseBidiMap(); } //----------------------------------------------------------------------- /** * Internal sorted map view. */ protected static class ViewMap extends AbstractSortedMapDecorator { /** * Constructor. * @param bidi the parent bidi map * @param sm the subMap sorted map */ protected ViewMap(final DualTreeBidiMap bidi, final SortedMap sm) { // the implementation is not great here... // use the normalMap as the filtered map, but reverseMap as the full map // this forces containsValue and clear to be overridden super(new DualTreeBidiMap(sm, bidi.reverseMap, bidi.inverseBidiMap)); } @Override public boolean containsValue(final Object value) { // override as default implementation uses reverseMap return decorated().normalMap.containsValue(value); } @Override public void clear() { // override as default implementation uses reverseMap for (final Iterator it = keySet().iterator(); it.hasNext();) { it.next(); it.remove(); } } @Override public SortedMap headMap(final K toKey) { return new ViewMap(decorated(), super.headMap(toKey)); } @Override public SortedMap tailMap(final K fromKey) { return new ViewMap(decorated(), super.tailMap(fromKey)); } @Override public SortedMap subMap(final K fromKey, final K toKey) { return new ViewMap(decorated(), super.subMap(fromKey, toKey)); } @Override protected DualTreeBidiMap decorated() { return (DualTreeBidiMap) super.decorated(); } @Override public K previousKey(final K key) { return decorated().previousKey(key); } @Override public K nextKey(final K key) { return decorated().nextKey(key); } } //----------------------------------------------------------------------- /** * Inner class MapIterator. */ protected static class BidiOrderedMapIterator implements OrderedMapIterator, ResettableIterator { /** The parent map */ private final AbstractDualBidiMap parent; /** The iterator being decorated */ private ListIterator> iterator; /** The last returned entry */ private Map.Entry last = null; /** * Constructor. * @param parent the parent map */ protected BidiOrderedMapIterator(final AbstractDualBidiMap parent) { super(); this.parent = parent; iterator = new ArrayList>(parent.entrySet()).listIterator(); } public boolean hasNext() { return iterator.hasNext(); } public K next() { last = iterator.next(); return last.getKey(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public K previous() { last = iterator.previous(); return last.getKey(); } public void remove() { iterator.remove(); parent.remove(last.getKey()); last = null; } public K getKey() { if (last == null) { throw new IllegalStateException( "Iterator getKey() can only be called after next() and before remove()"); } return last.getKey(); } public V getValue() { if (last == null) { throw new IllegalStateException( "Iterator getValue() can only be called after next() and before remove()"); } return last.getValue(); } public V setValue(final V value) { if (last == null) { throw new IllegalStateException( "Iterator setValue() can only be called after next() and before remove()"); } if (parent.reverseMap.containsKey(value) && parent.reverseMap.get(value) != last.getKey()) { throw new IllegalArgumentException( "Cannot use setValue() when the object being set is already in the map"); } final V oldValue = parent.put(last.getKey(), value); // Map.Entry specifies that the behavior is undefined when the backing map // has been modified (as we did with the put), so we also set the value // (especially needed for IBM JDK) last.setValue(value); return oldValue; } public void reset() { iterator = new ArrayList>(parent.entrySet()).listIterator(); last = null; } @Override public String toString() { if (last != null) { return "MapIterator[" + getKey() + "=" + getValue() + "]"; } return "MapIterator[]"; } } // Serialization //----------------------------------------------------------------------- private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(normalMap); } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); normalMap = new TreeMap(comparator); reverseMap = new TreeMap(valueComparator); @SuppressWarnings("unchecked") // will fail at runtime if the stream is incorrect final Map map = (Map) in.readObject(); putAll(map); } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/AbstractBidiMapDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/AbstractBidiMapDe100664 5501 12243235516 31531 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.Set; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.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 3.0 * @version $Id: AbstractBidiMapDecorator.java 1543168 2013-11-18 21:22:43Z ggregory $ */ 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(final BidiMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ @Override protected BidiMap decorated() { return (BidiMap) super.decorated(); } //----------------------------------------------------------------------- @Override public MapIterator mapIterator() { return decorated().mapIterator(); } public K getKey(final Object value) { return decorated().getKey(value); } public K removeValue(final Object value) { return decorated().removeValue(value); } public BidiMap inverseBidiMap() { return decorated().inverseBidiMap(); } @Override public Set values() { return decorated().values(); } } ././@LongLink100644 0 0 167 12243235652 10263 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/AbstractSortedBidiMapDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/AbstractSortedBid100664 5711 12243235516 31635 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.Comparator; import java.util.SortedMap; import org.apache.commons.collections4.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 3.0 * @version $Id: AbstractSortedBidiMapDecorator.java 1477745 2013-04-30 18:08:32Z tn $ */ 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(final SortedBidiMap map) { super(map); } /** * Gets the map being decorated. * * @return the decorated map */ @Override protected SortedBidiMap decorated() { return (SortedBidiMap) super.decorated(); } //----------------------------------------------------------------------- @Override public SortedBidiMap inverseBidiMap() { return decorated().inverseBidiMap(); } public Comparator comparator() { return decorated().comparator(); } public Comparator valueComparator() { return decorated().valueComparator(); } public SortedMap subMap(final K fromKey, final K toKey) { return decorated().subMap(fromKey, toKey); } public SortedMap headMap(final K toKey) { return decorated().headMap(toKey); } public SortedMap tailMap(final K fromKey) { return decorated().tailMap(fromKey); } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/package-info.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/package-info.java100664 3650 12243235516 31536 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains implementations of the * {@link org.apache.commons.collections4.BidiMap BidiMap}, * {@link org.apache.commons.collections4.OrderedBidiMap OrderedBidiMap} and * {@link org.apache.commons.collections4.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 *
  • DualLinkedHashBidiMap - uses two LinkedHashMaps 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 *
* * @version $Id: package-info.java 1477745 2013-04-30 18:08:32Z tn $ */ package org.apache.commons.collections4.bidimap; commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/TreeBidiMap.java100664 222447 12243235516 31406 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractSet; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.OrderedBidiMap; import org.apache.commons.collections4.OrderedIterator; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.iterators.EmptyOrderedMapIterator; import org.apache.commons.collections4.keyvalue.UnmodifiableMapEntry; import static org.apache.commons.collections4.bidimap.TreeBidiMap.DataElement.KEY; import static org.apache.commons.collections4.bidimap.TreeBidiMap.DataElement.VALUE; /** * 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 {@link 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 3.0 (previously DoubleOrderedMap v2.0) * @version $Id: TreeBidiMap.java 1543253 2013-11-19 00:43:25Z ggregory $ */ public class TreeBidiMap, V extends Comparable> implements OrderedBidiMap, Serializable { static enum DataElement { KEY("key"), VALUE("value"); private final String description; /** * Create a new TreeBidiMap.DataElement. * * @param description the description for the element */ private DataElement(final String description) { this.description = description; } @Override public String toString() { return description; } } private static final long serialVersionUID = 721969328361807L; private transient Node[] rootNode; private transient int nodeCount = 0; private transient int modifications = 0; private transient Set keySet; private transient Set valuesSet; private transient Set> entrySet; private transient Inverse inverse = null; //----------------------------------------------------------------------- /** * Constructs a new empty TreeBidiMap. */ @SuppressWarnings("unchecked") public TreeBidiMap() { super(); rootNode = new Node[2]; } /** * 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) { this(); 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 lookupKey(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 lookupValue(value) != null; } /** * Gets the value to which this map maps the specified key. * Returns null if the map contains no mapping for this key. *

* The key must implement Comparable. * * @param key key whose associated value is to be returned * @return the value to which this map maps the specified key, * or null if the map contains no mapping for this key * @throws ClassCastException if the key is of an inappropriate type * @throws NullPointerException if the key is null */ public V get(final Object key) { checkKey(key); final Node node = lookupKey(key); return node == null ? null : node.getValue(); } /** * Puts the key-value pair into the map, replacing any previous pair. *

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

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

* Both key and value must implement Comparable. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value for the key * @throws ClassCastException if the key is of an inappropriate type * @throws NullPointerException if the key is null */ public V put(final K key, final V value) { final V result = get(key); doPut(key, value); return result; } /** * 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(final Map map) { for (final Map.Entry e : map.entrySet()) { put(e.getKey(), e.getValue()); } } /** * Removes the mapping for this key from this map if present. *

* The key must implement Comparable. * * @param key key whose mapping is to be removed from the map. * @return previous value associated with specified key, * or null if there was no mapping for key. * @throws ClassCastException if the key is of an inappropriate type * @throws NullPointerException if the key is null */ public V remove(final Object key) { return doRemoveKey(key); } /** * Removes all mappings from this map. */ public void clear() { modify(); nodeCount = 0; rootNode[KEY.ordinal()] = null; rootNode[VALUE.ordinal()] = null; } //----------------------------------------------------------------------- /** * Returns the key to which this map maps the specified value. * Returns null if the map contains no mapping for this value. *

* The value must implement Comparable. * * @param value value whose associated key is to be returned. * @return the key to which this map maps the specified value, * or null if the map contains no mapping for this value. * @throws ClassCastException if the value is of an inappropriate type * @throws NullPointerException if the value is null */ public K getKey(final Object value) { checkValue(value); final Node node = lookupValue(value); return node == null ? null : node.getKey(); } /** * Removes the mapping for this value from this map if present. *

* The value must implement Comparable. * * @param value value whose mapping is to be removed from the map * @return previous key associated with specified value, * or null if there was no mapping for value. * @throws ClassCastException if the value is of an inappropriate type * @throws NullPointerException if the value is null */ public K removeValue(final Object value) { return doRemoveValue(value); } //----------------------------------------------------------------------- /** * Gets the first (lowest) key currently in this map. * * @return the first (lowest) key currently in this sorted map * @throws NoSuchElementException if this map is empty */ public K firstKey() { if (nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } return leastNode(rootNode[KEY.ordinal()], KEY).getKey(); } /** * Gets the last (highest) key currently in this map. * * @return the last (highest) key currently in this sorted map * @throws NoSuchElementException if this map is empty */ public K lastKey() { if (nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } return greatestNode(rootNode[KEY.ordinal()], KEY).getKey(); } /** * Gets the next key after the one specified. *

* The key must implement Comparable. * * @param key the key to search for next from * @return the next key, null if no match or at end */ public K nextKey(final K key) { checkKey(key); final Node node = nextGreater(lookupKey(key), KEY); return node == null ? null : node.getKey(); } /** * Gets the previous key before the one specified. *

* The key must implement Comparable. * * @param key the key to search for previous from * @return the previous key, null if no match or at start */ public K previousKey(final K key) { checkKey(key); final Node node = nextSmaller(lookupKey(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 KeyView(KEY); } return keySet; } //----------------------------------------------------------------------- /** * Returns a set view of the values contained in this map in key order. * The returned object can be cast to a Set. *

* The set is backed by the map, so changes to the map are reflected in * the set, and vice-versa. If the map is modified while an iteration over * the set is in progress, the results of the iteration are undefined. *

* The set supports element removal, which removes the corresponding mapping * from the map. It does not support the add or addAll operations. * * @return a set view of the values contained in this map. */ public Set values() { if (valuesSet == null) { valuesSet = new ValueView(KEY); } 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) { entrySet = new EntryView(); } return entrySet; } //----------------------------------------------------------------------- public OrderedMapIterator mapIterator() { if (isEmpty()) { return EmptyOrderedMapIterator.emptyOrderedMapIterator(); } return new ViewMapIterator(KEY); } //----------------------------------------------------------------------- /** * Gets the inverse map for comparison. * * @return the inverse map */ public OrderedBidiMap inverseBidiMap() { if (inverse == null) { inverse = new Inverse(); } return inverse; } //----------------------------------------------------------------------- /** * Compares for equals as per the API. * * @param obj the object to compare to * @return true if equal */ @Override public boolean equals(final 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 */ @Override 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 */ @Override public String toString() { return this.doToString(KEY); } //----------------------------------------------------------------------- /** * Put logic. * * @param key the key, always the main map key * @param value the value, always the main map value */ private void doPut(final K key, final V value) { checkKeyAndValue(key, value); // store previous and remove previous mappings doRemoveKey(key); doRemoveValue(value); Node node = rootNode[KEY.ordinal()]; if (node == null) { // map is empty final Node root = new Node(key, value); rootNode[KEY.ordinal()] = root; rootNode[VALUE.ordinal()] = root; grow(); } else { // add new mapping while (true) { final int cmp = compare(key, node.getKey()); if (cmp == 0) { // shouldn't happen throw new IllegalArgumentException("Cannot store a duplicate key (\"" + key + "\") in this Map"); } else if (cmp < 0) { if (node.getLeft(KEY) != null) { node = node.getLeft(KEY); } else { final 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 { final Node newNode = new Node(key, value); insertValue(newNode); node.setRight(newNode, KEY); newNode.setParent(node, KEY); doRedBlackInsert(newNode, KEY); grow(); break; } } } } } private V doRemoveKey(final Object key) { final Node node = lookupKey(key); if (node == null) { return null; } doRedBlackDelete(node); return node.getValue(); } private K doRemoveValue(final Object value) { final Node node = lookupValue(value); if (node == null) { return null; } doRedBlackDelete(node); return node.getKey(); } /** * 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 */ @SuppressWarnings("unchecked") private > Node lookup(final Object data, final DataElement dataElement) { Node rval = null; Node node = rootNode[dataElement.ordinal()]; while (node != null) { final int cmp = compare((T) data, (T) node.getData(dataElement)); if (cmp == 0) { rval = node; break; } else { node = cmp < 0 ? node.getLeft(dataElement) : node.getRight(dataElement); } } return rval; } private Node lookupKey(final Object key) { return this.lookup(key, KEY); } private Node lookupValue(final Object value) { return this.lookup(value, VALUE); } /** * 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 DataElement dataElement) { Node rval; if (node == null) { rval = null; } else if (node.getRight(dataElement) != 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(dataElement), dataElement); } 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(dataElement); Node child = node; while (parent != null && child == parent.getRight(dataElement)) { child = parent; parent = parent.getParent(dataElement); } 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 DataElement dataElement) { Node rval; if (node == null) { rval = null; } else if (node.getLeft(dataElement) != 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(dataElement), dataElement); } 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(dataElement); Node child = node; while (parent != null && child == parent.getLeft(dataElement)) { child = parent; parent = parent.getParent(dataElement); } rval = parent; } 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 T o1, final T 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 Node leastNode(final Node node, final DataElement dataElement) { Node rval = node; if (rval != null) { while (rval.getLeft(dataElement) != null) { rval = rval.getLeft(dataElement); } } 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 Node greatestNode(final Node node, final DataElement dataElement) { Node rval = node; if (rval != null) { while (rval.getRight(dataElement) != null) { rval = rval.getRight(dataElement); } } 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 void copyColor(final Node from, final Node to, final DataElement dataElement) { if (to != null) { if (from == null) { // by default, make it black to.setBlack(dataElement); } else { to.copyColor(from, dataElement); } } } /** * 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 DataElement dataElement) { return node != null && node.isRed(dataElement); } /** * 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 DataElement dataElement) { return node == null || node.isBlack(dataElement); } /** * 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 DataElement dataElement) { if (node != null) { node.setRed(dataElement); } } /** * 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 DataElement dataElement) { if (node != null) { node.setBlack(dataElement); } } /** * 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 Node getGrandParent(final Node node, final DataElement dataElement) { return getParent(getParent(node, dataElement), dataElement); } /** * 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 Node getParent(final Node node, final DataElement dataElement) { return node == null ? null : node.getParent(dataElement); } /** * 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 Node getRightChild(final Node node, final DataElement dataElement) { return node == null ? null : node.getRight(dataElement); } /** * 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 Node getLeftChild(final Node node, final DataElement dataElement) { return node == null ? null : node.getLeft(dataElement); } /** * 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 DataElement dataElement) { final Node rightChild = node.getRight(dataElement); node.setRight(rightChild.getLeft(dataElement), dataElement); if (rightChild.getLeft(dataElement) != null) { rightChild.getLeft(dataElement).setParent(node, dataElement); } rightChild.setParent(node.getParent(dataElement), dataElement); if (node.getParent(dataElement) == null) { // node was the root ... now its right child is the root rootNode[dataElement.ordinal()] = rightChild; } else if (node.getParent(dataElement).getLeft(dataElement) == node) { node.getParent(dataElement).setLeft(rightChild, dataElement); } else { node.getParent(dataElement).setRight(rightChild, dataElement); } rightChild.setLeft(node, dataElement); node.setParent(rightChild, dataElement); } /** * 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 DataElement dataElement) { final Node leftChild = node.getLeft(dataElement); node.setLeft(leftChild.getRight(dataElement), dataElement); if (leftChild.getRight(dataElement) != null) { leftChild.getRight(dataElement).setParent(node, dataElement); } leftChild.setParent(node.getParent(dataElement), dataElement); if (node.getParent(dataElement) == null) { // node was the root ... now its left child is the root rootNode[dataElement.ordinal()] = leftChild; } else if (node.getParent(dataElement).getRight(dataElement) == node) { node.getParent(dataElement).setRight(leftChild, dataElement); } else { node.getParent(dataElement).setLeft(leftChild, dataElement); } leftChild.setRight(node, dataElement); node.setParent(leftChild, dataElement); } /** * 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 dataElement the KEY or VALUE int */ private void doRedBlackInsert(final Node insertedNode, final DataElement dataElement) { Node currentNode = insertedNode; makeRed(currentNode, dataElement); while (currentNode != null && currentNode != rootNode[dataElement.ordinal()] && isRed(currentNode.getParent(dataElement), dataElement)) { if (currentNode.isLeftChild(dataElement)) { final Node y = getRightChild(getGrandParent(currentNode, dataElement), dataElement); if (isRed(y, dataElement)) { makeBlack(getParent(currentNode, dataElement), dataElement); makeBlack(y, dataElement); makeRed(getGrandParent(currentNode, dataElement), dataElement); currentNode = getGrandParent(currentNode, dataElement); } else { //dead code? if (currentNode.isRightChild(dataElement)) { currentNode = getParent(currentNode, dataElement); rotateLeft(currentNode, dataElement); } makeBlack(getParent(currentNode, dataElement), dataElement); makeRed(getGrandParent(currentNode, dataElement), dataElement); if (getGrandParent(currentNode, dataElement) != null) { rotateRight(getGrandParent(currentNode, dataElement), dataElement); } } } else { // just like clause above, except swap left for right final Node y = getLeftChild(getGrandParent(currentNode, dataElement), dataElement); if (isRed(y, dataElement)) { makeBlack(getParent(currentNode, dataElement), dataElement); makeBlack(y, dataElement); makeRed(getGrandParent(currentNode, dataElement), dataElement); currentNode = getGrandParent(currentNode, dataElement); } else { //dead code? if (currentNode.isLeftChild(dataElement)) { currentNode = getParent(currentNode, dataElement); rotateRight(currentNode, dataElement); } makeBlack(getParent(currentNode, dataElement), dataElement); makeRed(getGrandParent(currentNode, dataElement), dataElement); if (getGrandParent(currentNode, dataElement) != null) { rotateLeft(getGrandParent(currentNode, dataElement), dataElement); } } } } makeBlack(rootNode[dataElement.ordinal()], dataElement); } /** * 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 (final DataElement dataElement : DataElement.values()) { // if deleted node has both left and children, swap with // the next greater node if (deletedNode.getLeft(dataElement) != null && deletedNode.getRight(dataElement) != null) { swapPosition(nextGreater(deletedNode, dataElement), deletedNode, dataElement); } final Node replacement = deletedNode.getLeft(dataElement) != null ? deletedNode.getLeft(dataElement) : deletedNode.getRight(dataElement); if (replacement != null) { replacement.setParent(deletedNode.getParent(dataElement), dataElement); if (deletedNode.getParent(dataElement) == null) { rootNode[dataElement.ordinal()] = replacement; } else if (deletedNode == deletedNode.getParent(dataElement).getLeft(dataElement)) { deletedNode.getParent(dataElement).setLeft(replacement, dataElement); } else { deletedNode.getParent(dataElement).setRight(replacement, dataElement); } deletedNode.setLeft(null, dataElement); deletedNode.setRight(null, dataElement); deletedNode.setParent(null, dataElement); if (isBlack(deletedNode, dataElement)) { doRedBlackDeleteFixup(replacement, dataElement); } } else { // replacement is null if (deletedNode.getParent(dataElement) == null) { // empty tree rootNode[dataElement.ordinal()] = null; } else { // deleted node had no children if (isBlack(deletedNode, dataElement)) { doRedBlackDeleteFixup(deletedNode, dataElement); } if (deletedNode.getParent(dataElement) != null) { if (deletedNode == deletedNode.getParent(dataElement).getLeft(dataElement)) { deletedNode.getParent(dataElement).setLeft(null, dataElement); } else { deletedNode.getParent(dataElement).setRight(null, dataElement); } deletedNode.setParent(null, dataElement); } } } } 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 dataElement the KEY or VALUE int */ private void doRedBlackDeleteFixup(final Node replacementNode, final DataElement dataElement) { Node currentNode = replacementNode; while (currentNode != rootNode[dataElement.ordinal()] && isBlack(currentNode, dataElement)) { if (currentNode.isLeftChild(dataElement)) { Node siblingNode = getRightChild(getParent(currentNode, dataElement), dataElement); if (isRed(siblingNode, dataElement)) { makeBlack(siblingNode, dataElement); makeRed(getParent(currentNode, dataElement), dataElement); rotateLeft(getParent(currentNode, dataElement), dataElement); siblingNode = getRightChild(getParent(currentNode, dataElement), dataElement); } if (isBlack(getLeftChild(siblingNode, dataElement), dataElement) && isBlack(getRightChild(siblingNode, dataElement), dataElement)) { makeRed(siblingNode, dataElement); currentNode = getParent(currentNode, dataElement); } else { if (isBlack(getRightChild(siblingNode, dataElement), dataElement)) { makeBlack(getLeftChild(siblingNode, dataElement), dataElement); makeRed(siblingNode, dataElement); rotateRight(siblingNode, dataElement); siblingNode = getRightChild(getParent(currentNode, dataElement), dataElement); } copyColor(getParent(currentNode, dataElement), siblingNode, dataElement); makeBlack(getParent(currentNode, dataElement), dataElement); makeBlack(getRightChild(siblingNode, dataElement), dataElement); rotateLeft(getParent(currentNode, dataElement), dataElement); currentNode = rootNode[dataElement.ordinal()]; } } else { Node siblingNode = getLeftChild(getParent(currentNode, dataElement), dataElement); if (isRed(siblingNode, dataElement)) { makeBlack(siblingNode, dataElement); makeRed(getParent(currentNode, dataElement), dataElement); rotateRight(getParent(currentNode, dataElement), dataElement); siblingNode = getLeftChild(getParent(currentNode, dataElement), dataElement); } if (isBlack(getRightChild(siblingNode, dataElement), dataElement) && isBlack(getLeftChild(siblingNode, dataElement), dataElement)) { makeRed(siblingNode, dataElement); currentNode = getParent(currentNode, dataElement); } else { if (isBlack(getLeftChild(siblingNode, dataElement), dataElement)) { makeBlack(getRightChild(siblingNode, dataElement), dataElement); makeRed(siblingNode, dataElement); rotateLeft(siblingNode, dataElement); siblingNode = getLeftChild(getParent(currentNode, dataElement), dataElement); } copyColor(getParent(currentNode, dataElement), siblingNode, dataElement); makeBlack(getParent(currentNode, dataElement), dataElement); makeBlack(getLeftChild(siblingNode, dataElement), dataElement); rotateRight(getParent(currentNode, dataElement), dataElement); currentNode = rootNode[dataElement.ordinal()]; } } } makeBlack(currentNode, dataElement); } /** * 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 dataElement the KEY or VALUE int */ private void swapPosition(final Node x, final Node y, final DataElement dataElement) { // Save initial values. final Node xFormerParent = x.getParent(dataElement); final Node xFormerLeftChild = x.getLeft(dataElement); final Node xFormerRightChild = x.getRight(dataElement); final Node yFormerParent = y.getParent(dataElement); final Node yFormerLeftChild = y.getLeft(dataElement); final Node yFormerRightChild = y.getRight(dataElement); final boolean xWasLeftChild = x.getParent(dataElement) != null && x == x.getParent(dataElement).getLeft(dataElement); final boolean yWasLeftChild = y.getParent(dataElement) != null && y == y.getParent(dataElement).getLeft(dataElement); // Swap, handling special cases of one being the other's parent. if (x == yFormerParent) { // x was y's parent x.setParent(y, dataElement); if (yWasLeftChild) { y.setLeft(x, dataElement); y.setRight(xFormerRightChild, dataElement); } else { y.setRight(x, dataElement); y.setLeft(xFormerLeftChild, dataElement); } } else { x.setParent(yFormerParent, dataElement); if (yFormerParent != null) { if (yWasLeftChild) { yFormerParent.setLeft(x, dataElement); } else { yFormerParent.setRight(x, dataElement); } } y.setLeft(xFormerLeftChild, dataElement); y.setRight(xFormerRightChild, dataElement); } if (y == xFormerParent) { // y was x's parent y.setParent(x, dataElement); if (xWasLeftChild) { x.setLeft(y, dataElement); x.setRight(yFormerRightChild, dataElement); } else { x.setRight(y, dataElement); x.setLeft(yFormerLeftChild, dataElement); } } else { y.setParent(xFormerParent, dataElement); if (xFormerParent != null) { if (xWasLeftChild) { xFormerParent.setLeft(y, dataElement); } else { xFormerParent.setRight(y, dataElement); } } x.setLeft(yFormerLeftChild, dataElement); x.setRight(yFormerRightChild, dataElement); } // Fix children's parent pointers if (x.getLeft(dataElement) != null) { x.getLeft(dataElement).setParent(x, dataElement); } if (x.getRight(dataElement) != null) { x.getRight(dataElement).setParent(x, dataElement); } if (y.getLeft(dataElement) != null) { y.getLeft(dataElement).setParent(y, dataElement); } if (y.getRight(dataElement) != null) { y.getRight(dataElement).setParent(y, dataElement); } x.swapColors(y, dataElement); // Check if root changed if (rootNode[dataElement.ordinal()] == x) { rootNode[dataElement.ordinal()] = y; } else if (rootNode[dataElement.ordinal()] == y) { rootNode[dataElement.ordinal()] = 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 DataElement dataElement) { if (o == null) { throw new NullPointerException(dataElement + " cannot be null"); } if (!(o instanceof Comparable)) { throw new ClassCastException(dataElement + " 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.ordinal()]; while (true) { final int cmp = compare(newNode.getValue(), node.getValue()); 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(final Object obj, final DataElement dataElement) { if (obj == this) { return true; } if (obj instanceof Map == false) { return false; } final Map other = (Map) obj; if (other.size() != size()) { return false; } if (nodeCount > 0) { try { for (final MapIterator it = getMapIterator(dataElement); it.hasNext(); ) { final Object key = it.next(); final Object value = it.getValue(); if (value.equals(other.get(key)) == false) { return false; } } } catch (final ClassCastException ex) { return false; } catch (final 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 DataElement dataElement) { int total = 0; if (nodeCount > 0) { for (final MapIterator it = getMapIterator(dataElement); it.hasNext(); ) { final Object key = it.next(); final 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 DataElement dataElement) { if (nodeCount == 0) { return "{}"; } final StringBuilder buf = new StringBuilder(nodeCount * 32); buf.append('{'); final MapIterator it = getMapIterator(dataElement); boolean hasNext = it.hasNext(); while (hasNext) { final Object key = it.next(); final 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(); } private MapIterator getMapIterator(final DataElement dataElement) { switch (dataElement) { case KEY: return new ViewMapIterator(KEY); case VALUE: return new InverseViewMapIterator(VALUE); default: throw new IllegalArgumentException(); } } /** * Reads the content of the stream. */ @SuppressWarnings("unchecked") // This will fail at runtime if the stream is incorrect private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException{ stream.defaultReadObject(); rootNode = new Node[2]; int size = stream.readInt(); for(int i = 0; i < size; i++){ K k =(K) stream.readObject(); V v =(V) stream.readObject(); put(k, v); } } /** * Writes the content to the stream for serialization. */ private void writeObject(final ObjectOutputStream stream) throws IOException{ stream.defaultWriteObject(); stream.writeInt(this.size()); for (final Entry entry : entrySet()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } //----------------------------------------------------------------------- /** * A view of this map. */ abstract class View extends AbstractSet { /** Whether to return KEY or VALUE order. */ final DataElement orderType; /** * Constructor. * @param orderType the KEY or VALUE int for the order * @param main the main map */ View(final DataElement orderType) { super(); this.orderType = orderType; } @Override public int size() { return TreeBidiMap.this.size(); } @Override public void clear() { TreeBidiMap.this.clear(); } } class KeyView extends View { /** * Create a new TreeBidiMap.KeyView. */ public KeyView(final DataElement orderType) { super(orderType); } @Override public Iterator iterator() { return new ViewMapIterator(orderType); } @Override public boolean contains(final Object obj) { checkNonNullComparable(obj, KEY); return lookupKey(obj) != null; } @Override public boolean remove(final Object o) { return doRemoveKey(o) != null; } } class ValueView extends View { /** * Create a new TreeBidiMap.ValueView. */ public ValueView(final DataElement orderType) { super(orderType); } @Override public Iterator iterator() { return new InverseViewMapIterator(orderType); } @Override public boolean contains(final Object obj) { checkNonNullComparable(obj, VALUE); return lookupValue(obj) != null; } @Override public boolean remove(final Object o) { return doRemoveValue(o) != null; } } /** * A view of this map. */ class EntryView extends View> { EntryView() { super(KEY); } @Override public boolean contains(final Object obj) { if (obj instanceof Map.Entry == false) { return false; } final Map.Entry entry = (Map.Entry) obj; final Object value = entry.getValue(); final Node node = lookupKey(entry.getKey()); return node != null && node.getValue().equals(value); } @Override public boolean remove(final Object obj) { if (obj instanceof Map.Entry == false) { return false; } final Map.Entry entry = (Map.Entry) obj; final Object value = entry.getValue(); final Node node = lookupKey(entry.getKey()); if (node != null && node.getValue().equals(value)) { doRedBlackDelete(node); return true; } return false; } @Override public Iterator> iterator() { return new ViewMapEntryIterator(); } } /** * A view of this map. */ class InverseEntryView extends View> { InverseEntryView() { super(VALUE); } @Override public boolean contains(final Object obj) { if (obj instanceof Map.Entry == false) { return false; } final Map.Entry entry = (Map.Entry) obj; final Object value = entry.getValue(); final Node node = lookupValue(entry.getKey()); return node != null && node.getKey().equals(value); } @Override public boolean remove(final Object obj) { if (obj instanceof Map.Entry == false) { return false; } final Map.Entry entry = (Map.Entry) obj; final Object value = entry.getValue(); final Node node = lookupValue(entry.getKey()); if (node != null && node.getKey().equals(value)) { doRedBlackDelete(node); return true; } return false; } @Override public Iterator> iterator() { return new InverseViewMapEntryIterator(); } } //----------------------------------------------------------------------- /** * An iterator over the map. */ abstract class ViewIterator { /** Whether to return KEY or VALUE order. */ private final DataElement orderType; /** The last node returned by the iterator. */ Node lastReturnedNode; /** The next node to be returned by the iterator. */ private Node nextNode; /** The previous node in the sequence returned by the iterator. */ private Node previousNode; /** The modification count. */ private int expectedModifications; /** * Constructor. * @param orderType the KEY or VALUE int for the order * @param main the main map */ ViewIterator(final DataElement orderType) { super(); this.orderType = orderType; expectedModifications = modifications; nextNode = leastNode(rootNode[orderType.ordinal()], orderType); lastReturnedNode = null; previousNode = null; } public final boolean hasNext() { return nextNode != null; } protected Node navigateNext() { if (nextNode == null) { throw new NoSuchElementException(); } if (modifications != expectedModifications) { throw new ConcurrentModificationException(); } lastReturnedNode = nextNode; previousNode = nextNode; nextNode = nextGreater(nextNode, orderType); return lastReturnedNode; } public boolean hasPrevious() { return previousNode != null; } protected Node navigatePrevious() { if (previousNode == null) { throw new NoSuchElementException(); } if (modifications != expectedModifications) { throw new ConcurrentModificationException(); } nextNode = lastReturnedNode; if (nextNode == null) { nextNode = nextGreater(previousNode, orderType); } lastReturnedNode = previousNode; previousNode = nextSmaller(previousNode, orderType); return lastReturnedNode; } public final void remove() { if (lastReturnedNode == null) { throw new IllegalStateException(); } if (modifications != expectedModifications) { throw new ConcurrentModificationException(); } doRedBlackDelete(lastReturnedNode); expectedModifications++; lastReturnedNode = null; if (nextNode == null) { previousNode = greatestNode(rootNode[orderType.ordinal()], orderType); } else { previousNode = nextSmaller(nextNode, orderType); } } } //----------------------------------------------------------------------- /** * An iterator over the map. */ class ViewMapIterator extends ViewIterator implements OrderedMapIterator { /** * Constructor. */ ViewMapIterator(final DataElement orderType) { super(orderType); } public K getKey() { if (lastReturnedNode == null) { throw new IllegalStateException( "Iterator getKey() can only be called after next() and before remove()"); } return lastReturnedNode.getKey(); } public V getValue() { if (lastReturnedNode == null) { throw new IllegalStateException( "Iterator getValue() can only be called after next() and before remove()"); } return lastReturnedNode.getValue(); } public V setValue(final V obj) { throw new UnsupportedOperationException(); } public K next() { return navigateNext().getKey(); } public K previous() { return navigatePrevious().getKey(); } } /** * An iterator over the map. */ class InverseViewMapIterator extends ViewIterator implements OrderedMapIterator { /** * Create a new TreeBidiMap.InverseViewMapIterator. */ public InverseViewMapIterator(final DataElement orderType) { super(orderType); } public V getKey() { if (lastReturnedNode == null) { throw new IllegalStateException( "Iterator getKey() can only be called after next() and before remove()"); } return lastReturnedNode.getValue(); } public K getValue() { if (lastReturnedNode == null) { throw new IllegalStateException( "Iterator getValue() can only be called after next() and before remove()"); } return lastReturnedNode.getKey(); } public K setValue(final K obj) { throw new UnsupportedOperationException(); } public V next() { return navigateNext().getValue(); } public V previous() { return navigatePrevious().getValue(); } } /** * An iterator over the map entries. */ class ViewMapEntryIterator extends ViewIterator implements OrderedIterator> { /** * Constructor. */ ViewMapEntryIterator() { super(KEY); } public Map.Entry next() { return navigateNext(); } public Map.Entry previous() { return navigatePrevious(); } } /** * An iterator over the inverse map entries. */ class InverseViewMapEntryIterator extends ViewIterator implements OrderedIterator> { /** * Constructor. */ InverseViewMapEntryIterator() { super(VALUE); } public Map.Entry next() { return createEntry(navigateNext()); } public Map.Entry previous() { return createEntry(navigatePrevious()); } private Map.Entry createEntry(final Node node) { return new UnmodifiableMapEntry(node.getValue(), node.getKey()); } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- /** * A node used to store the data. */ static class Node, V extends Comparable> implements Map.Entry, KeyValue { private final K key; private final V value; private final Node[] leftNode; private final Node[] rightNode; private final Node[] parentNode; private final 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 */ @SuppressWarnings("unchecked") Node(final K key, final V value) { super(); this.key = key; this.value = value; leftNode = new Node[2]; rightNode = new Node[2]; parentNode = new Node[2]; blackColor = new boolean[] { true, true }; calculatedHashCode = false; } private Object getData(final DataElement dataElement) { switch (dataElement) { case KEY: return getKey(); case VALUE: return getValue(); default: throw new IllegalArgumentException(); } } private void setLeft(final Node node, final DataElement dataElement) { leftNode[dataElement.ordinal()] = node; } private Node getLeft(final DataElement dataElement) { return leftNode[dataElement.ordinal()]; } private void setRight(final Node node, final DataElement dataElement) { rightNode[dataElement.ordinal()] = node; } private Node getRight(final DataElement dataElement) { return rightNode[dataElement.ordinal()]; } /** * 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 DataElement dataElement) { parentNode[dataElement.ordinal()] = node; } /** * Get the parent node. * * @param index the KEY or VALUE int * @return the parent node, may be null */ private Node getParent(final DataElement dataElement) { return parentNode[dataElement.ordinal()]; } /** * 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 DataElement dataElement) { // Swap colors -- old hacker's trick blackColor[dataElement.ordinal()] ^= node.blackColor[dataElement.ordinal()]; node.blackColor[dataElement.ordinal()] ^= blackColor[dataElement.ordinal()]; blackColor[dataElement.ordinal()] ^= node.blackColor[dataElement.ordinal()]; } /** * 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 DataElement dataElement) { return blackColor[dataElement.ordinal()]; } /** * Is this node red? * * @param index the KEY or VALUE int * @return true if non-black */ private boolean isRed(final DataElement dataElement) { return !blackColor[dataElement.ordinal()]; } /** * Make this node black. * * @param index the KEY or VALUE int */ private void setBlack(final DataElement dataElement) { blackColor[dataElement.ordinal()] = true; } /** * Make this node red. * * @param index the KEY or VALUE int */ private void setRed(final DataElement dataElement) { blackColor[dataElement.ordinal()] = 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 DataElement dataElement) { blackColor[dataElement.ordinal()] = node.blackColor[dataElement.ordinal()]; } private boolean isLeftChild(final DataElement dataElement) { return parentNode[dataElement.ordinal()] != null && parentNode[dataElement.ordinal()].leftNode[dataElement.ordinal()] == this; } private boolean isRightChild(final DataElement dataElement) { return parentNode[dataElement.ordinal()] != null && parentNode[dataElement.ordinal()].rightNode[dataElement.ordinal()] == this; } //------------------------------------------------------------------- /** * Gets the key. * * @return the key corresponding to this entry. */ public K getKey() { return key; } /** * Gets the value. * * @return the value corresponding to this entry. */ public V getValue() { return value; } /** * Optional operation that is not permitted in this implementation * * @param ignored * @return does not return * @throws UnsupportedOperationException always */ public V setValue(final V ignored) throws UnsupportedOperationException { throw new UnsupportedOperationException("Map.Entry.setValue is not supported"); } /** * Compares the specified object with this entry for equality. * Returns true if the given object is also a map entry and * the two entries represent the same mapping. * * @param obj the object to be compared for equality with this entry. * @return true if the specified object is equal to this entry. */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof Map.Entry)) { return false; } final Map.Entry e = (Map.Entry) obj; return getKey().equals(e.getKey()) && getValue().equals(e.getValue()); } /** * @return the hash code value for this map entry. */ @Override public int hashCode() { if (!calculatedHashCode) { hashcodeValue = getKey().hashCode() ^ getValue().hashCode(); calculatedHashCode = true; } return hashcodeValue; } } //----------------------------------------------------------------------- /** * The inverse map implementation. */ class Inverse implements OrderedBidiMap { /** Store the keySet once created. */ private Set inverseKeySet; /** Store the valuesSet once created. */ private Set inverseValuesSet; /** Store the entrySet once created. */ private Set> inverseEntrySet; public int size() { return TreeBidiMap.this.size(); } public boolean isEmpty() { return TreeBidiMap.this.isEmpty(); } public K get(final Object key) { return TreeBidiMap.this.getKey(key); } public V getKey(final Object value) { return TreeBidiMap.this.get(value); } public boolean containsKey(final Object key) { return TreeBidiMap.this.containsValue(key); } public boolean containsValue(final Object value) { return TreeBidiMap.this.containsKey(value); } public V firstKey() { if (TreeBidiMap.this.nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } return leastNode(TreeBidiMap.this.rootNode[VALUE.ordinal()], VALUE).getValue(); } public V lastKey() { if (TreeBidiMap.this.nodeCount == 0) { throw new NoSuchElementException("Map is empty"); } return greatestNode(TreeBidiMap.this.rootNode[VALUE.ordinal()], VALUE).getValue(); } public V nextKey(final V key) { checkKey(key); final Node node = nextGreater(TreeBidiMap.this.lookup(key, VALUE), VALUE); return node == null ? null : node.getValue(); } public V previousKey(final V key) { checkKey(key); final Node node = TreeBidiMap.this.nextSmaller(TreeBidiMap.this.lookup(key, VALUE), VALUE); return node == null ? null : node.getValue(); } public K put(final V key, final K value) { final K result = get(key); TreeBidiMap.this.doPut(value, key); return result; } public void putAll(final Map map) { for (final Map.Entry e : map.entrySet()) { put(e.getKey(), e.getValue()); } } public K remove(final Object key) { return TreeBidiMap.this.removeValue(key); } public V removeValue(final Object value) { return TreeBidiMap.this.remove(value); } public void clear() { TreeBidiMap.this.clear(); } public Set keySet() { if (inverseKeySet == null) { inverseKeySet = new ValueView(VALUE); } return inverseKeySet; } public Set values() { if (inverseValuesSet == null) { inverseValuesSet = new KeyView(VALUE); } return inverseValuesSet; } public Set> entrySet() { if (inverseEntrySet == null) { inverseEntrySet = new InverseEntryView(); } return inverseEntrySet; } public OrderedMapIterator mapIterator() { if (isEmpty()) { return EmptyOrderedMapIterator.emptyOrderedMapIterator(); } return new InverseViewMapIterator(VALUE); } public OrderedBidiMap inverseBidiMap() { return TreeBidiMap.this; } @Override public boolean equals(final Object obj) { return TreeBidiMap.this.doEquals(obj, DataElement.VALUE); } @Override public int hashCode() { return TreeBidiMap.this.doHashCode(DataElement.VALUE); } @Override public String toString() { return TreeBidiMap.this.doToString(DataElement.VALUE); } } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/DualHashBidiMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/DualHashBidiMap.j100664 7711 12243235516 31443 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.BidiMap; /** * Implementation of {@link BidiMap} that uses two {@link HashMap} instances. *

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

* NOTE: From Commons Collections 3.1, all subclasses will use {@link HashMap} * and the flawed createMap method is ignored. * * @since 3.0 * @version $Id: DualHashBidiMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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(final 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(final Map normalMap, final Map reverseMap, final 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 */ @Override protected BidiMap createBidiMap(final Map normalMap, final Map reverseMap, final BidiMap inverseBidiMap) { return new DualHashBidiMap(normalMap, reverseMap, inverseBidiMap); } // Serialization //----------------------------------------------------------------------- private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(normalMap); } private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); normalMap = new HashMap(); reverseMap = new HashMap(); @SuppressWarnings("unchecked") // will fail at runtime if stream is incorrect final Map map = (Map) in.readObject(); putAll(map); } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/UnmodifiableBidiMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/UnmodifiableBidiM100664 10752 12243235516 31616 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableMapIterator; import org.apache.commons.collections4.map.UnmodifiableEntrySet; /** * Decorates another {@link BidiMap} to ensure it can't be altered. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableBidiMap.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 the key type * @param the value type * @param map the map to decorate, must not be null * @return an unmodifiable BidiMap * @throws IllegalArgumentException if map is null * @since 4.0 */ public static BidiMap unmodifiableBidiMap(final BidiMap map) { if (map instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final BidiMap tmpMap = (BidiMap) map; return tmpMap; } 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 */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableBidiMap(final BidiMap map) { super((BidiMap) map); } //----------------------------------------------------------------------- @Override public void clear() { throw new UnsupportedOperationException(); } @Override public V put(final K key, final V value) { throw new UnsupportedOperationException(); } @Override public void putAll(final Map mapToCopy) { throw new UnsupportedOperationException(); } @Override public V remove(final Object key) { throw new UnsupportedOperationException(); } @Override public Set> entrySet() { final Set> set = super.entrySet(); return UnmodifiableEntrySet.unmodifiableEntrySet(set); } @Override public Set keySet() { final Set set = super.keySet(); return UnmodifiableSet.unmodifiableSet(set); } @Override public Set values() { final Set set = super.values(); return UnmodifiableSet.unmodifiableSet(set); } //----------------------------------------------------------------------- @Override public K removeValue(final Object value) { throw new UnsupportedOperationException(); } @Override public MapIterator mapIterator() { final MapIterator it = decorated().mapIterator(); return UnmodifiableMapIterator.unmodifiableMapIterator(it); } @Override public synchronized BidiMap inverseBidiMap() { if (inverse == null) { inverse = new UnmodifiableBidiMap(decorated().inverseBidiMap()); inverse.inverse = this; } return inverse; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/AbstractDualBidiMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/bidimap/AbstractDualBidiM100664 57201 12243235516 31571 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.bidimap; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.BidiMap; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.ResettableIterator; import org.apache.commons.collections4.collection.AbstractCollectionDecorator; import org.apache.commons.collections4.iterators.AbstractIteratorDecorator; import org.apache.commons.collections4.keyvalue.AbstractMapEntryDecorator; /** * Abstract {@link BidiMap} implemented using two maps. *

* An implementation can be written simply by implementing the * {@link #createBidiMap(Map, Map, BidiMap)} method. * * @see DualHashBidiMap * @see DualTreeBidiMap * @since 3.0 * @version $Id: AbstractDualBidiMap.java 1521272 2013-09-09 20:10:39Z tn $ */ public abstract class AbstractDualBidiMap implements BidiMap { /** * Normal delegate map. */ transient Map normalMap; /** * Reverse delegate map. */ transient Map reverseMap; /** * Inverse view of this map. */ transient BidiMap inverseBidiMap = null; /** * View of the keys. */ transient Set keySet = null; /** * View of the values. */ transient Set values = null; /** * View of the entries. */ 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(); } /** * 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 3.1 */ protected AbstractDualBidiMap(final Map normalMap, final Map reverseMap) { super(); this.normalMap = normalMap; this.reverseMap = 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(final Map normalMap, final Map reverseMap, final BidiMap inverseBidiMap) { super(); this.normalMap = normalMap; this.reverseMap = reverseMap; this.inverseBidiMap = inverseBidiMap; } /** * Creates a new instance of the subclass. * * @param normalMap the normal direction map * @param reverseMap the reverse direction map * @param inverseMap this map, which is the inverse in the new map * @return the inverse map */ protected abstract BidiMap createBidiMap(Map normalMap, Map reverseMap, BidiMap inverseMap); // Map delegation //----------------------------------------------------------------------- public V get(final Object key) { return normalMap.get(key); } public int size() { return normalMap.size(); } public boolean isEmpty() { return normalMap.isEmpty(); } public boolean containsKey(final Object key) { return normalMap.containsKey(key); } @Override public boolean equals(final Object obj) { return normalMap.equals(obj); } @Override public int hashCode() { return normalMap.hashCode(); } @Override public String toString() { return normalMap.toString(); } // BidiMap changes //----------------------------------------------------------------------- public V put(final K key, final V value) { if (normalMap.containsKey(key)) { reverseMap.remove(normalMap.get(key)); } if (reverseMap.containsKey(value)) { normalMap.remove(reverseMap.get(value)); } final V obj = normalMap.put(key, value); reverseMap.put(value, key); return obj; } public void putAll(final Map map) { for (final Map.Entry entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } public V remove(final Object key) { V value = null; if (normalMap.containsKey(key)) { value = normalMap.remove(key); reverseMap.remove(value); } return value; } public void clear() { normalMap.clear(); reverseMap.clear(); } public boolean containsValue(final Object value) { return reverseMap.containsKey(value); } // BidiMap //----------------------------------------------------------------------- /** * Obtains a MapIterator over the map. * The iterator implements ResetableMapIterator. * This implementation relies on the entrySet iterator. *

* The setValue() methods only allow a new value to be set. * If the value being set is already in the map, an IllegalArgumentException * is thrown (as setValue cannot change the size of the map). * * @return a map iterator */ public MapIterator mapIterator() { return new BidiMapIterator(this); } public K getKey(final Object value) { return reverseMap.get(value); } public K removeValue(final Object value) { K key = null; if (reverseMap.containsKey(value)) { key = reverseMap.remove(value); normalMap.remove(key); } return key; } public BidiMap inverseBidiMap() { if (inverseBidiMap == null) { inverseBidiMap = createBidiMap(reverseMap, normalMap, 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(final Iterator iterator) { return new KeySetIterator(iterator, this); } /** * Gets a values view of the map. * Changes made on the view are reflected in the map. * The set supports remove and clear but not add. * * @return the values view */ public Set values() { if (values == null) { values = new Values(this); } return values; } /** * Creates a values iterator. * Subclasses can override this to return iterators with different properties. * * @param iterator the iterator to decorate * @return the values iterator */ protected Iterator createValuesIterator(final 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(final Iterator> iterator) { return new EntrySetIterator(iterator, this); } //----------------------------------------------------------------------- /** * Inner class View. */ protected static abstract class View extends AbstractCollectionDecorator { /** Generated serial version ID. */ private static final long serialVersionUID = 4621510560119690639L; /** 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(final Collection coll, final AbstractDualBidiMap parent) { super(coll); this.parent = parent; } @Override public boolean removeAll(final Collection coll) { if (parent.isEmpty() || coll.isEmpty()) { return false; } boolean modified = false; final Iterator it = coll.iterator(); while (it.hasNext()) { modified |= remove(it.next()); } return modified; } /** * {@inheritDoc} *

* This implementation iterates over the elements of this bidi map, checking each element in * turn to see if it's contained in coll. If it's not contained, it's removed * from this bidi map. As a consequence, it is advised to use a collection type for * coll that provides a fast (e.g. O(1)) implementation of * {@link Collection#contains(Object)}. */ @Override public boolean retainAll(final Collection coll) { if (parent.isEmpty()) { return false; } if (coll.isEmpty()) { parent.clear(); return true; } boolean modified = false; final Iterator it = iterator(); while (it.hasNext()) { if (coll.contains(it.next()) == false) { it.remove(); modified = true; } } return modified; } @Override public void clear() { parent.clear(); } } //----------------------------------------------------------------------- /** * Inner class KeySet. */ protected static class KeySet extends View implements Set { /** Serialization version */ private static final long serialVersionUID = -7107935777385040694L; /** * Constructs a new view of the BidiMap. * * @param parent the parent BidiMap */ @SuppressWarnings("unchecked") protected KeySet(final AbstractDualBidiMap parent) { super(parent.normalMap.keySet(), (AbstractDualBidiMap) parent); } @Override public Iterator iterator() { return parent.createKeySetIterator(super.iterator()); } @Override public boolean contains(final Object key) { return parent.normalMap.containsKey(key); } @Override public boolean remove(final Object key) { if (parent.normalMap.containsKey(key)) { final Object value = parent.normalMap.remove(key); parent.reverseMap.remove(value); return true; } return false; } } /** * Inner class KeySetIterator. */ protected static class KeySetIterator extends AbstractIteratorDecorator { /** The parent map */ protected final AbstractDualBidiMap parent; /** The last returned key */ protected K lastKey = null; /** Whether remove is allowed at present */ protected boolean canRemove = false; /** * Constructor. * @param iterator the iterator to decorate * @param parent the parent map */ protected KeySetIterator(final Iterator iterator, final AbstractDualBidiMap parent) { super(iterator); this.parent = parent; } @Override public K next() { lastKey = super.next(); canRemove = true; return lastKey; } @Override public void remove() { if (canRemove == false) { throw new IllegalStateException("Iterator remove() can only be called once after next()"); } final Object value = parent.normalMap.get(lastKey); super.remove(); parent.reverseMap.remove(value); lastKey = null; canRemove = false; } } //----------------------------------------------------------------------- /** * Inner class Values. */ protected static class Values extends View implements Set { /** Serialization version */ private static final long serialVersionUID = 4023777119829639864L; /** * Constructs a new view of the BidiMap. * * @param parent the parent BidiMap */ @SuppressWarnings("unchecked") protected Values(final AbstractDualBidiMap parent) { super(parent.normalMap.values(), (AbstractDualBidiMap) parent); } @Override public Iterator iterator() { return parent.createValuesIterator(super.iterator()); } @Override public boolean contains(final Object value) { return parent.reverseMap.containsKey(value); } @Override public boolean remove(final Object value) { if (parent.reverseMap.containsKey(value)) { final Object key = parent.reverseMap.remove(value); parent.normalMap.remove(key); return true; } return false; } } /** * Inner class ValuesIterator. */ protected static class ValuesIterator extends AbstractIteratorDecorator { /** The parent map */ protected final AbstractDualBidiMap parent; /** The last returned value */ protected V lastValue = null; /** Whether remove is allowed at present */ protected boolean canRemove = false; /** * Constructor. * @param iterator the iterator to decorate * @param parent the parent map */ @SuppressWarnings("unchecked") protected ValuesIterator(final Iterator iterator, final AbstractDualBidiMap parent) { super(iterator); this.parent = (AbstractDualBidiMap) parent; } @Override public V next() { lastValue = super.next(); canRemove = true; return lastValue; } @Override 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.reverseMap.remove(lastValue); lastValue = null; canRemove = false; } } //----------------------------------------------------------------------- /** * Inner class EntrySet. */ protected static class EntrySet extends View> implements Set> { /** Serialization version */ private static final long serialVersionUID = 4040410962603292348L; /** * Constructs a new view of the BidiMap. * * @param parent the parent BidiMap */ protected EntrySet(final AbstractDualBidiMap parent) { super(parent.normalMap.entrySet(), parent); } @Override public Iterator> iterator() { return parent.createEntrySetIterator(super.iterator()); } @Override public boolean remove(final Object obj) { if (obj instanceof Map.Entry == false) { return false; } final Map.Entry entry = (Map.Entry) obj; final Object key = entry.getKey(); if (parent.containsKey(key)) { final V value = parent.normalMap.get(key); if (value == null ? entry.getValue() == null : value.equals(entry.getValue())) { parent.normalMap.remove(key); parent.reverseMap.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(final Iterator> iterator, final AbstractDualBidiMap parent) { super(iterator); this.parent = parent; } @Override public Map.Entry next() { last = new MapEntry(super.next(), parent); canRemove = true; return last; } @Override 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) final Object value = last.getValue(); super.remove(); parent.reverseMap.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(final Map.Entry entry, final AbstractDualBidiMap parent) { super(entry); this.parent = parent; } @Override public V setValue(final V value) { final K key = MapEntry.this.getKey(); if (parent.reverseMap.containsKey(value) && parent.reverseMap.get(value) != key) { throw new IllegalArgumentException( "Cannot use setValue() when the object being set is already in the map"); } parent.put(key, value); return super.setValue(value); } } /** * 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(final AbstractDualBidiMap parent) { super(); this.parent = parent; this.iterator = parent.normalMap.entrySet().iterator(); } public boolean hasNext() { return iterator.hasNext(); } public K next() { last = iterator.next(); canRemove = true; return last.getKey(); } public void remove() { if (canRemove == false) { throw new IllegalStateException("Iterator remove() can only be called once after next()"); } // store value as remove may change the entry in the decorator (eg.TreeMap) final V value = last.getValue(); iterator.remove(); parent.reverseMap.remove(value); last = null; canRemove = false; } public K getKey() { if (last == null) { throw new IllegalStateException( "Iterator getKey() can only be called after next() and before remove()"); } return last.getKey(); } public V getValue() { if (last == null) { throw new IllegalStateException( "Iterator getValue() can only be called after next() and before remove()"); } return last.getValue(); } public V setValue(final V value) { if (last == null) { throw new IllegalStateException( "Iterator setValue() can only be called after next() and before remove()"); } if (parent.reverseMap.containsKey(value) && parent.reverseMap.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.normalMap.entrySet().iterator(); last = null; canRemove = false; } @Override public String toString() { if (last != null) { return "MapIterator[" + getKey() + "=" + getValue() + "]"; } return "MapIterator[]"; } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/MapUtils.java100664 214415 12243235516 27406 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.io.PrintStream; import java.text.NumberFormat; import java.text.ParseException; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.ResourceBundle; import java.util.SortedMap; import java.util.TreeMap; import org.apache.commons.collections4.map.AbstractMapDecorator; import org.apache.commons.collections4.map.AbstractSortedMapDecorator; import org.apache.commons.collections4.map.FixedSizeMap; import org.apache.commons.collections4.map.FixedSizeSortedMap; import org.apache.commons.collections4.map.LazyMap; import org.apache.commons.collections4.map.LazySortedMap; import org.apache.commons.collections4.map.ListOrderedMap; import org.apache.commons.collections4.map.MultiValueMap; import org.apache.commons.collections4.map.PredicatedMap; import org.apache.commons.collections4.map.PredicatedSortedMap; import org.apache.commons.collections4.map.TransformedMap; import org.apache.commons.collections4.map.TransformedSortedMap; import org.apache.commons.collections4.map.UnmodifiableMap; import org.apache.commons.collections4.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 #multiValueMap( Map )} *
  • {@link #multiValueMap( Map, Class )} *
  • {@link #multiValueMap( Map, Factory )} *
* * @since 1.0 * @version $Id: MapUtils.java 1543964 2013-11-20 21:53:39Z tn $ */ public class MapUtils { /** * An empty unmodifiable sorted map. * This is not provided in the JDK. */ @SuppressWarnings("rawtypes") public static final SortedMap EMPTY_SORTED_MAP = UnmodifiableSortedMap.unmodifiableSortedMap(new TreeMap()); /** * String used to indent the verbose and debug Map prints. */ private static final String INDENT_STRING = " "; /** * MapUtils should not normally be instantiated. */ private MapUtils() {} // Type safe getters //------------------------------------------------------------------------- /** * Gets from a Map in a null-safe manner. * * @param the key type * @param the value type * @param map the map to use * @param key the key to look up * @return the value in the Map, null if null map input */ public static V getObject(final Map map, final K key) { if (map != null) { return map.get(key); } return null; } /** * Gets a String from a Map in a null-safe manner. *

* The String is obtained via toString. * * @param the key type * @param map the map to use * @param key the key to look up * @return the value in the Map as a String, null if null map input */ public static String getString(final Map map, final K key) { if (map != null) { final 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 the key type * @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 K key) { if (map != null) { final Object answer = map.get(key); if (answer != null) { if (answer instanceof Boolean) { return (Boolean) answer; } if (answer instanceof String) { return Boolean.valueOf((String) answer); } if (answer instanceof Number) { final 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 the key type * @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 K key) { if (map != null) { final Object answer = map.get(key); if (answer != null) { if (answer instanceof Number) { return (Number) answer; } if (answer instanceof String) { try { final String text = (String) answer; return NumberFormat.getInstance().parse(text); } catch (final ParseException e) { // NOPMD // failure means null is returned } } } } 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 the key type * @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 K key) { final Number answer = getNumber(map, key); if (answer == null) { return null; } if (answer instanceof Byte) { return (Byte) answer; } return Byte.valueOf(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 the key type * @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 K key) { final Number answer = getNumber(map, key); if (answer == null) { return null; } if (answer instanceof Short) { return (Short) answer; } return Short.valueOf(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 the key type * @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 K key) { final Number answer = getNumber(map, key); if (answer == null) { return null; } if (answer instanceof Integer) { return (Integer) answer; } return Integer.valueOf(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 the key type * @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 K key) { final Number answer = getNumber(map, key); if (answer == null) { return null; } if (answer instanceof Long) { return (Long) answer; } return Long.valueOf(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 the key type * @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 K key) { final Number answer = getNumber(map, key); if (answer == null) { return null; } if (answer instanceof Float) { return (Float) answer; } return Float.valueOf(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 the key type * @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 K key) { final Number answer = getNumber(map, key); if (answer == null) { return null; } if (answer instanceof Double) { return (Double) answer; } return Double.valueOf(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 the key type * @param map the map to use * @param key the key to look up * @return the value in the Map as a Map, null if null map input */ public static Map getMap(final Map map, final K key) { if (map != null) { final 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 the key type * @param the value type * @param map the map whose value to look up * @param key the key of the value to look up in that map * @param defaultValue what to return if the value is null * @return the value in the map, or defaultValue if the original value * is null or the map is null */ public static V getObject(final Map map, final K key, final V defaultValue) { if (map != null) { final V answer = map.get(key); if (answer != null) { return answer; } } return defaultValue; } /** * Looks up the given key in the given map, converting the result into * a string, using the default value if the the conversion fails. * * @param the key type * @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(final Map map, final K key, final 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 the key type * @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(final Map map, final K key, final 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 the key type * @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(final Map map, final K key, final 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 the key type * @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(final Map map, final K key, final 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 the key type * @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(final Map map, final K key, final 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 the key type * @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(final Map map, final K key, final 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 the key type * @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(final Map map, final K key, final 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 the key type * @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(final Map map, final K key, final 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 the key type * @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(final Map map, final K key, final 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 the key type * @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(final Map map, final K key, final 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 the key type * @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 K key) { return Boolean.TRUE.equals(getBoolean(map, key)); } /** * Gets a byte from a Map in a null-safe manner. *

* The byte is obtained from the results of {@link #getNumber(Map,Object)}. * * @param the key type * @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 K key) { final 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 the key type * @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 K key) { final 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 the key type * @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 K key) { final 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 the key type * @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 K key) { final 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 the key type * @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 K key) { final 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 the key type * @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 K key) { final 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 the key type * @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 K key, final boolean defaultValue) { final 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 the key type * @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 K key, final byte defaultValue) { final 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 the key type * @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 K key, final short defaultValue) { final 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 the key type * @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 K key, final int defaultValue) { final 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 the key type * @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 K key, final long defaultValue) { final 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 the key type * @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 K key, final float defaultValue) { final 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 the key type * @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 K key, final double defaultValue) { final 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 the key type * @param the value type * @param map the map to convert to a Properties object * @return the properties object */ public static Properties toProperties(final Map map) { final Properties answer = new Properties(); if (map != null) { for (final Entry entry2 : map.entrySet()) { final Map.Entry entry = entry2; final Object key = entry.getKey(); final 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) { final Enumeration enumeration = resourceBundle.getKeys(); final Map map = new HashMap(); while (enumeration.hasMoreElements()) { final String key = enumeration.nextElement(); final 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 */ @SuppressWarnings("deprecation") 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 */ @SuppressWarnings("deprecation") public static void debugPrint(final PrintStream out, final Object label, final Map map) { verbosePrintInternal(out, label, map, new ArrayStack>(), true); } // Implementation methods //------------------------------------------------------------------------- /** * 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 */ @SuppressWarnings("deprecation") 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 (final Map.Entry entry : map.entrySet()) { final Object childKey = entry.getKey(); final 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 the key type * @param the value type * @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(final Map map) { final Map out = new HashMap(map.size()); for (final Entry entry : map.entrySet()) { 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. * Note that this method can be used to circumvent the map's * value type at runtime. * * @param the key type * @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(final Map map, final K key, final Object value) throws NullPointerException { map.put(key, value == null ? "" : 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 the key type * @param the value type * @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 3.2 */ @SuppressWarnings("unchecked") // As per Javadoc throws CCE for invalid array contents public static Map putAll(final Map map, final Object[] array) { map.size(); // force NPE if (array == null || array.length == 0) { return map; } final Object obj = array[0]; if (obj instanceof Map.Entry) { for (final Object element : array) { // cast ok here, type is checked above final Map.Entry entry = (Map.Entry) element; map.put(entry.getKey(), entry.getValue()); } } else if (obj instanceof KeyValue) { for (final Object element : array) { // cast ok here, type is checked above final KeyValue keyval = (KeyValue) element; map.put(keyval.getKey(), keyval.getValue()); } } else if (obj instanceof Object[]) { for (int i = 0; i < array.length; i++) { final Object[] sub = (Object[]) array[i]; if (sub == null || sub.length < 2) { throw new IllegalArgumentException("Invalid array element: " + i); } // these casts can fail if array has incorrect types map.put((K) sub[0], (V) sub[1]); } } else { for (int i = 0; i < array.length - 1;) { // these casts can fail if array has incorrect types map.put((K) array[i++], (V) array[i++]); } } return map; } //----------------------------------------------------------------------- /** * Returns an immutable empty map if the argument is null, * or the argument itself otherwise. * * @param the key type * @param the value type * @param map the map, possibly null * @return an empty map if the argument is null */ public static Map emptyIfNull(final Map map) { return map == null ? Collections.emptyMap() : 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 3.2 */ public static boolean isEmpty(final 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 3.2 */ public static boolean isNotEmpty(final 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 the key type * @param the value type * @param map the map to synchronize, must not be null * @return a synchronized map backed by the given map */ public static Map synchronizedMap(final 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 the key type * @param the value type * @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(final Map map) { return UnmodifiableMap.unmodifiableMap(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 the key type * @param the value type * @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 IterableMap predicatedMap(final Map map, final Predicate keyPred, final Predicate valuePred) { return PredicatedMap.predicatedMap(map, keyPred, valuePred); } /** * 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#transformedMap}. *

* 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 the key type * @param the value type * @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 IterableMap transformedMap(final Map map, final Transformer keyTransformer, final Transformer valueTransformer) { return TransformedMap.transformingMap(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 the key type * @param the value type * @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 IterableMap fixedSizeMap(final Map map) { return FixedSizeMap.fixedSizeMap(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 the key type * @param the value type * @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 IterableMap lazyMap(final Map map, final Factory factory) { return LazyMap.lazyMap(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 the key type * @param the value type * @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 IterableMap lazyMap(final Map map, final Transformer transformerFactory) { return LazyMap.lazyMap(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 the key type * @param the value type * @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 OrderedMap orderedMap(final Map map) { return ListOrderedMap.listOrderedMap(map); } /** * Creates a mult-value map backed by the given map which returns * collections of type ArrayList. * * @param the key type * @param the value type * @param map the map to decorate * @return a multi-value map backed by the given map which returns ArrayLists of values. * @see MultiValueMap * @since 3.2 */ public static MultiValueMap multiValueMap(final Map> map) { return MultiValueMap.multiValueMap(map); } /** * Creates a multi-value map backed by the given map which returns * collections of the specified type. * * @param the key type * @param the value type * @param the collection class 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 3.2 */ public static > MultiValueMap multiValueMap(final Map map, final Class collectionClass) { return MultiValueMap.multiValueMap(map, collectionClass); } /** * Creates a multi-value map backed by the given map which returns * collections created by the specified collection factory. * * @param the key type * @param the value type * @param the collection class type * @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 3.2 */ public static > MultiValueMap multiValueMap(final Map map, final Factory collectionFactory) { return MultiValueMap.multiValueMap(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 the key type * @param the value type * @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 SortedMap synchronizedSortedMap(final 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 the key type * @param the value type * @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 SortedMap unmodifiableSortedMap(final SortedMap map) { return UnmodifiableSortedMap.unmodifiableSortedMap(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 the key type * @param the value type * @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(final SortedMap map, final Predicate keyPred, final Predicate valuePred) { return PredicatedSortedMap.predicatedSortedMap(map, keyPred, valuePred); } /** * 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#transformedSortedMap}. *

* 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 the key type * @param the value type * @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(final SortedMap map, final Transformer keyTransformer, final Transformer valueTransformer) { return TransformedSortedMap.transformingSortedMap(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 the key type * @param the value type * @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(final SortedMap map) { return FixedSizeSortedMap.fixedSizeSortedMap(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 the key type * @param the value type * @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(final SortedMap map, final Factory factory) { return LazySortedMap.lazySortedMap(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 the key type * @param the value type * @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(final SortedMap map, final Transformer transformerFactory) { return LazySortedMap.lazySortedMap(map, transformerFactory); } /** * Populates a Map using the supplied Transformer to transform the elements * into keys, using the unaltered element as the value in the Map. * * @param the key type * @param the value type * @param map the Map to populate. * @param elements the Iterable containing the input values for the map. * @param keyTransformer the Transformer used to transform the element into a key value * @throws NullPointerException if the map, elements or transformer are null */ public static void populateMap(final Map map, final Iterable elements, final Transformer keyTransformer) { populateMap(map, elements, keyTransformer, TransformerUtils.nopTransformer()); } /** * Populates a Map using the supplied Transformers to transform the elements * into keys and values. * * @param the key type * @param the value type * @param the type of object contained in the {@link Iterable} * @param map the Map to populate. * @param elements the Iterable containing the input values for the map. * @param keyTransformer the Transformer used to transform the element into a key value * @param valueTransformer the Transformer used to transform the element into a value * @throws NullPointerException if the map, elements or transformers are null */ public static void populateMap(final Map map, final Iterable elements, final Transformer keyTransformer, final Transformer valueTransformer) { final Iterator iter = elements.iterator(); while (iter.hasNext()) { final E temp = iter.next(); map.put(keyTransformer.transform(temp), valueTransformer.transform(temp)); } } /** * Populates a MultiMap using the supplied Transformer to transform the elements * into keys, using the unaltered element as the value in the MultiMap. * * @param the key type * @param the value type * @param map the MultiMap to populate. * @param elements the Iterable to use as input values for the map. * @param keyTransformer the Transformer used to transform the element into a key value * @throws NullPointerException if the map, elements or transformer are null */ public static void populateMap(final MultiMap map, final Iterable elements, final Transformer keyTransformer) { populateMap(map, elements, keyTransformer, TransformerUtils.nopTransformer()); } /** * Populates a MultiMap using the supplied Transformers to transform the elements * into keys and values. * * @param the key type * @param the value type * @param the type of object contained in the {@link Iterable} * @param map the MultiMap to populate. * @param elements the Iterable containing the input values for the map. * @param keyTransformer the Transformer used to transform the element into a key value * @param valueTransformer the Transformer used to transform the element into a value * @throws NullPointerException if the map, collection or transformers are null */ public static void populateMap(final MultiMap map, final Iterable elements, final Transformer keyTransformer, final Transformer valueTransformer) { final Iterator iter = elements.iterator(); while (iter.hasNext()) { final E temp = iter.next(); map.put(keyTransformer.transform(temp), valueTransformer.transform(temp)); } } /** * Get the specified {@link Map} as an {@link IterableMap}. * * @param the key type * @param the value type * @param map to wrap if necessary. * @return IterableMap * @since 4.0 */ public static IterableMap iterableMap(final Map map) { if (map == null) { throw new IllegalArgumentException("Map must not be null"); } return map instanceof IterableMap ? (IterableMap) map : new AbstractMapDecorator(map) {}; } /** * Get the specified {@link SortedMap} as an {@link IterableSortedMap}. * * @param the key type * @param the value type * @param sortedMap to wrap if necessary * @return {@link IterableSortedMap} * @since 4.0 */ public static IterableSortedMap iterableSortedMap(final SortedMap sortedMap) { if (sortedMap == null) { throw new IllegalArgumentException("Map must not be null"); } return sortedMap instanceof IterableSortedMap ? (IterableSortedMap) sortedMap : new AbstractSortedMapDecorator(sortedMap) {}; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/SplitMapUtils.java100664 17206 12243235516 30401 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.collection.UnmodifiableCollection; import org.apache.commons.collections4.iterators.UnmodifiableMapIterator; import org.apache.commons.collections4.map.EntrySetToMapIteratorAdapter; import org.apache.commons.collections4.map.UnmodifiableEntrySet; /** * Utilities for working with "split maps:" objects that implement {@link Put} * and/or {@link Get} but not {@link Map}. * * @since 4.0 * @version $Id: SplitMapUtils.java 1543258 2013-11-19 00:46:30Z ggregory $ * * @see Get * @see Put */ public class SplitMapUtils { /** * SplitMapUtils should not normally be instantiated. */ private SplitMapUtils() {} //----------------------------------------------------------------------- private static class WrappedGet implements IterableMap, Unmodifiable { private final Get get; private WrappedGet(final Get get) { this.get = get; } public void clear() { throw new UnsupportedOperationException(); } public boolean containsKey(final Object key) { return get.containsKey(key); } public boolean containsValue(final Object value) { return get.containsValue(value); } public Set> entrySet() { return UnmodifiableEntrySet.unmodifiableEntrySet(get.entrySet()); } @Override public boolean equals(final Object arg0) { if (arg0 == this) { return true; } return arg0 instanceof WrappedGet && ((WrappedGet) arg0).get.equals(this.get); } public V get(final Object key) { return get.get(key); } @Override public int hashCode() { return ("WrappedGet".hashCode() << 4) | get.hashCode(); } public boolean isEmpty() { return get.isEmpty(); } public Set keySet() { return UnmodifiableSet.unmodifiableSet(get.keySet()); } public V put(final K key, final V value) { throw new UnsupportedOperationException(); } public void putAll(final Map t) { throw new UnsupportedOperationException(); } public V remove(final Object key) { return get.remove(key); } public int size() { return get.size(); } public Collection values() { return UnmodifiableCollection.unmodifiableCollection(get.values()); } public MapIterator mapIterator() { MapIterator it; if (get instanceof IterableGet) { it = ((IterableGet) get).mapIterator(); } else { it = new EntrySetToMapIteratorAdapter(get.entrySet()); } return UnmodifiableMapIterator.unmodifiableMapIterator(it); } } private static class WrappedPut implements Map, Put { private final Put put; private WrappedPut(final Put put) { this.put = put; } public void clear() { put.clear(); } public boolean containsKey(final Object key) { throw new UnsupportedOperationException(); } public boolean containsValue(final Object value) { throw new UnsupportedOperationException(); } public Set> entrySet() { throw new UnsupportedOperationException(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } return obj instanceof WrappedPut && ((WrappedPut) obj).put.equals(this.put); } public V get(final Object key) { throw new UnsupportedOperationException(); } @Override public int hashCode() { return ("WrappedPut".hashCode() << 4) | put.hashCode(); } public boolean isEmpty() { throw new UnsupportedOperationException(); } public Set keySet() { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") public V put(final K key, final V value) { return (V) put.put(key, value); } public void putAll(final Map t) { put.putAll(t); } public V remove(final Object key) { throw new UnsupportedOperationException(); } public int size() { throw new UnsupportedOperationException(); } public Collection values() { throw new UnsupportedOperationException(); } } //----------------------------------------------------------------------- /** * Get the specified {@link Get} as an instance of {@link IterableMap}. * If get implements {@link IterableMap} directly, no conversion will take place. * If get implements {@link Map} but not {@link IterableMap} it will be decorated. * Otherwise an {@link Unmodifiable} {@link IterableMap} will be returned. * @param the key type * @param the value type * @param get to wrap, must not be null * @return {@link IterableMap} */ @SuppressWarnings("unchecked") public static IterableMap readableMap(final Get get) { if (get == null) { throw new IllegalArgumentException("Get must not be null"); } if (get instanceof Map) { return get instanceof IterableMap ? ((IterableMap) get) : MapUtils .iterableMap((Map) get); } return new WrappedGet(get); } /** * Get the specified {@link Put} as an instanceof {@link Map}. * If put implements {@link Map} directly, no conversion will take place. * Otherwise a write-only {@link Map} will be returned. On such a {@link Map} * it is recommended that the result of #put(K, V) be discarded as it likely will not * match V at runtime. * * @param the key type * @param the element type * @param put to wrap, must not be null * @return {@link Map} */ @SuppressWarnings("unchecked") public static Map writableMap(final Put put) { if (put == null) { throw new IllegalArgumentException("Put must not be null"); } if (put instanceof Map) { return (Map) put; } return new WrappedPut(put); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/SortedBag.java100664 3226 12243235516 27456 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Comparator; /** * Defines a type of Bag that maintains a sorted order among * its unique representative members. * * @param the type to iterate over * @since 2.0 * @version $Id: SortedBag.java 1543264 2013-11-19 00:48:12Z ggregory $ */ 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 */ Comparator comparator(); /** * Returns the first (lowest) member. * * @return the first element in the sorted bag */ E first(); /** * Returns the last (highest) member. * * @return the last element in the sorted bag */ E last(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/ClosureUtils.java100664 37771 12243235516 30275 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Collection; import java.util.Map; import org.apache.commons.collections4.functors.ChainedClosure; import org.apache.commons.collections4.functors.EqualPredicate; import org.apache.commons.collections4.functors.ExceptionClosure; import org.apache.commons.collections4.functors.ForClosure; import org.apache.commons.collections4.functors.IfClosure; import org.apache.commons.collections4.functors.InvokerTransformer; import org.apache.commons.collections4.functors.NOPClosure; import org.apache.commons.collections4.functors.SwitchClosure; import org.apache.commons.collections4.functors.TransformerClosure; import org.apache.commons.collections4.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 3.0 * @version $Id: ClosureUtils.java 1479126 2013-05-04 15:16:07Z tn $ */ public class ClosureUtils { /** * This class is not normally instantiated. */ private ClosureUtils() {} /** * Gets a Closure that always throws an exception. * This could be useful during testing as a placeholder. * * @see org.apache.commons.collections4.functors.ExceptionClosure * * @param the type that the closure acts on * @return the closure */ public static Closure exceptionClosure() { return ExceptionClosure.exceptionClosure(); } /** * Gets a Closure that will do nothing. * This could be useful during testing as a placeholder. * * @see org.apache.commons.collections4.functors.NOPClosure * * @param the type that the closure acts on * @return the closure */ public static Closure nopClosure() { return NOPClosure.nopClosure(); } /** * 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.collections4.functors.TransformerClosure * * @param the type that the closure acts on * @param transformer the transformer to run each time in the closure, null means nop * @return the closure */ public static Closure asClosure(final Transformer transformer) { return TransformerClosure.transformerClosure(transformer); } /** * Creates a Closure that will call the closure count times. *

* A null closure or zero count returns the NOPClosure. * * @see org.apache.commons.collections4.functors.ForClosure * * @param the type that the closure acts on * @param count the number of times to loop * @param closure the closure to call repeatedly * @return the for closure */ public static Closure forClosure(final int count, final Closure closure) { return ForClosure.forClosure(count, closure); } /** * Creates a Closure that will call the closure repeatedly until the * predicate returns false. * * @see org.apache.commons.collections4.functors.WhileClosure * * @param the type that the closure acts on * @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(final Predicate predicate, final Closure closure) { return WhileClosure.whileClosure(predicate, closure, false); } /** * Creates a Closure that will call the closure once and then repeatedly * until the predicate returns false. * * @see org.apache.commons.collections4.functors.WhileClosure * * @param the type that the closure acts on * @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(final Closure closure, final Predicate predicate) { return WhileClosure.whileClosure(predicate, closure, true); } /** * Creates a Closure that will invoke a specific method on the closure's * input object by reflection. * * @see org.apache.commons.collections4.functors.InvokerTransformer * @see org.apache.commons.collections4.functors.TransformerClosure * * @param the type that the closure acts on * @param methodName the name of the method * @return the invoker closure * @throws IllegalArgumentException if the method name is null */ public static Closure invokerClosure(final String methodName) { // reuse transformer as it has caching - this is lazy really, should have inner class here return asClosure(InvokerTransformer.invokerTransformer(methodName)); } /** * Creates a Closure that will invoke a specific method on the closure's * input object by reflection. * * @see org.apache.commons.collections4.functors.InvokerTransformer * @see org.apache.commons.collections4.functors.TransformerClosure * * @param the type that the closure acts on * @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(final String methodName, final Class[] paramTypes, final Object[] args) { // reuse transformer as it has caching - this is lazy really, should have inner class here return asClosure(InvokerTransformer.invokerTransformer(methodName, paramTypes, args)); } /** * Create a new Closure that calls each closure in turn, passing the * result into the next closure. * * @see org.apache.commons.collections4.functors.ChainedClosure * * @param the type that the closure acts on * @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(final Closure... closures) { return ChainedClosure.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. * * @see org.apache.commons.collections4.functors.ChainedClosure * * @param the type that the closure acts on * @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(final Collection> closures) { return ChainedClosure.chainedClosure(closures); } /** * Create a new Closure that calls another closure based on the * result of the specified predicate. * * @see org.apache.commons.collections4.functors.IfClosure * * @param the type that the closure acts on * @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 3.2 */ public static Closure ifClosure(final Predicate predicate, final Closure trueClosure) { return IfClosure.ifClosure(predicate, trueClosure); } /** * Create a new Closure that calls one of two closures depending * on the specified predicate. * * @see org.apache.commons.collections4.functors.IfClosure * * @param the type that the closure acts on * @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(final Predicate predicate, final Closure trueClosure, final Closure falseClosure) { return IfClosure.ifClosure(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.collections4.functors.SwitchClosure * * @param the type that the closure acts on * @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(final Predicate[] predicates, final Closure[] closures) { return SwitchClosure.switchClosure(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.collections4.functors.SwitchClosure * * @param the type that the closure acts on * @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(final Predicate[] predicates, final Closure[] closures, final Closure defaultClosure) { return SwitchClosure.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. * * @see org.apache.commons.collections4.functors.SwitchClosure * * @param the type that the closure acts on * @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(final Map, Closure> predicatesAndClosures) { return SwitchClosure.switchClosure(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.collections4.functors.SwitchClosure * * @param the type that the closure acts on * @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 */ @SuppressWarnings("unchecked") public static Closure switchMapClosure(final Map> objectsAndClosures) { if (objectsAndClosures == null) { throw new IllegalArgumentException("The object and closure map must not be null"); } final Closure def = objectsAndClosures.remove(null); final int size = objectsAndClosures.size(); final Closure[] trs = new Closure[size]; final Predicate[] preds = new Predicate[size]; int i = 0; for (final Map.Entry> entry : objectsAndClosures.entrySet()) { preds[i] = EqualPredicate.equalPredicate(entry.getKey()); trs[i] = entry.getValue(); i++; } return ClosureUtils.switchClosure(preds, trs, def); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/Factory.java100664 3141 12243235516 27207 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * 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. * * @param the type that the factory creates * * @since 2.1 * @version $Id: Factory.java 1543256 2013-11-19 00:45:38Z ggregory $ */ public interface Factory { /** * Create a new object. * * @return a new object * @throws FunctorException (runtime) if the factory cannot create an object */ T create(); } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/NodeCachingLinkedList.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/NodeCachingLinkedLis100664 17417 12243235516 31627 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 3.0 * @version $Id: NodeCachingLinkedList.java 1533984 2013-10-20 21:12:51Z tn $ */ public class NodeCachingLinkedList extends AbstractLinkedList implements Serializable { /** Serialization version */ private static final long serialVersionUID = 6897789178562232073L; /** * The default value for {@link #maximumCacheSize}. */ private 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. */ private transient Node firstCachedNode; /** * The size of the cache. */ private transient int cacheSize; /** * The maximum size of the cache. */ private 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(final 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(final 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(final 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; } final 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(final Node node) { if (isCacheFull()) { // don't cache the node. return; } // clear the node's contents and add it to the cache. final 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 */ @Override protected Node createNode(final E value) { final Node cachedNode = getNodeFromCache(); if (cachedNode == null) { return super.createNode(value); } 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 */ @Override protected void removeNode(final Node node) { super.removeNode(node); addNodeToCache(node); } /** * Removes all the nodes from the list, storing as many as required in the * cache for reuse. * */ @Override 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}. final int numberOfNodesToCache = Math.min(size, maximumCacheSize - cacheSize); Node node = header.next; for (int currentIndex = 0; currentIndex < numberOfNodesToCache; currentIndex++) { final Node oldNode = node; node = node.next; addNodeToCache(oldNode); } super.removeAllNodes(); } //----------------------------------------------------------------------- /** * Serializes the data held in this object to the stream specified. */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Deserializes the data held in this object to the stream specified. */ private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); doReadObject(in); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/FixedSizeList.java100664 13051 12243235516 31322 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections4.BoundedCollection; import org.apache.commons.collections4.iterators.AbstractListIteratorDecorator; import org.apache.commons.collections4.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 3.0 * @version $Id: FixedSizeList.java 1479405 2013-05-05 21:58:52Z tn $ */ public class FixedSizeList extends AbstractSerializableListDecorator implements BoundedCollection { /** Serialization version */ private static final long serialVersionUID = -2218010673611160319L; /** * Factory method to create a fixed size list. * * @param the type of the elements in the list * @param list the list to decorate, must not be null * @return a new fixed size list * @throws IllegalArgumentException if list is null * @since 4.0 */ public static FixedSizeList fixedSizeList(final 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(final List list) { super(list); } //----------------------------------------------------------------------- @Override public boolean add(final E object) { throw new UnsupportedOperationException("List is fixed size"); } @Override public void add(final int index, final E object) { throw new UnsupportedOperationException("List is fixed size"); } @Override public boolean addAll(final Collection coll) { throw new UnsupportedOperationException("List is fixed size"); } @Override public boolean addAll(final int index, final Collection coll) { throw new UnsupportedOperationException("List is fixed size"); } @Override public void clear() { throw new UnsupportedOperationException("List is fixed size"); } @Override public E get(final int index) { return decorated().get(index); } @Override public int indexOf(final Object object) { return decorated().indexOf(object); } @Override public Iterator iterator() { return UnmodifiableIterator.unmodifiableIterator(decorated().iterator()); } @Override public int lastIndexOf(final Object object) { return decorated().lastIndexOf(object); } @Override public ListIterator listIterator() { return new FixedSizeListIterator(decorated().listIterator(0)); } @Override public ListIterator listIterator(final int index) { return new FixedSizeListIterator(decorated().listIterator(index)); } @Override public E remove(final int index) { throw new UnsupportedOperationException("List is fixed size"); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException("List is fixed size"); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException("List is fixed size"); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException("List is fixed size"); } @Override public E set(final int index, final E object) { return decorated().set(index, object); } @Override public List subList(final int fromIndex, final int toIndex) { final List sub = decorated().subList(fromIndex, toIndex); return new FixedSizeList(sub); } /** * List iterator that only permits changes via set() */ private class FixedSizeListIterator extends AbstractListIteratorDecorator { protected FixedSizeListIterator(final ListIterator iterator) { super(iterator); } @Override public void remove() { throw new UnsupportedOperationException("List is fixed size"); } @Override public void add(final Object object) { throw new UnsupportedOperationException("List is fixed size"); } } public boolean isFull() { return true; } public int maxSize() { return size(); } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/AbstractListDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/AbstractListDecorato100664 6373 12243235516 31725 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.Collection; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections4.collection.AbstractCollectionDecorator; /** * Decorates another {@link List} to provide additional behaviour. *

* Methods are forwarded directly to the decorated list. * * @param the type of the elements in the list * @since 3.0 * @version $Id: AbstractListDecorator.java 1477772 2013-04-30 18:44:21Z tn $ */ public abstract class AbstractListDecorator extends AbstractCollectionDecorator implements List { /** Serialization version--necessary in an abstract class? */ private static final long serialVersionUID = 4500739654952315623L; /** * Constructor only used in deserialization, do not use otherwise. * @since 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(final List list) { super(list); } /** * Gets the list being decorated. * * @return the decorated list */ @Override protected List decorated() { return (List) super.decorated(); } //----------------------------------------------------------------------- public void add(final int index, final E object) { decorated().add(index, object); } public boolean addAll(final int index, final Collection coll) { return decorated().addAll(index, coll); } public E get(final int index) { return decorated().get(index); } public int indexOf(final Object object) { return decorated().indexOf(object); } public int lastIndexOf(final Object object) { return decorated().lastIndexOf(object); } public ListIterator listIterator() { return decorated().listIterator(); } public ListIterator listIterator(final int index) { return decorated().listIterator(index); } public E remove(final int index) { return decorated().remove(index); } public E set(final int index, final E object) { return decorated().set(index, object); } public List subList(final int fromIndex, final int toIndex) { return decorated().subList(fromIndex, toIndex); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/TreeList.java100664 115352 12243235516 30356 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.ArrayStack; import org.apache.commons.collections4.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 slightly more memory. * * @since 3.1 * @version $Id: TreeList.java 1533984 2013-10-20 21:12:51Z tn $ */ @SuppressWarnings("deprecation") // replace ArrayStack by ArrayDeque when moving to Java 1.6 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 collection. * * @param coll the collection to copy * @throws NullPointerException if the collection is null */ public TreeList(final Collection coll) { super(); if (!coll.isEmpty()) { root = new AVLNode(coll); size = coll.size(); } } //----------------------------------------------------------------------- /** * Gets the element at the specified index. * * @param index the index to retrieve * @return the element at the specified index */ @Override public E get(final int index) { checkInterval(index, 0, size() - 1); return root.get(index).getValue(); } /** * Gets the current size of the list. * * @return the current size */ @Override public int size() { return size; } /** * Gets an iterator over the list. * * @return an iterator over the list */ @Override public Iterator iterator() { // override to go 75% faster return listIterator(0); } /** * Gets a ListIterator over the list. * * @return the new iterator */ @Override 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 */ @Override public ListIterator listIterator(final 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. * * @param object the object to search * @return the index of the object, -1 if not found */ @Override public int indexOf(final 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. * * @param object the object to check * @return true if the object is found */ @Override public boolean contains(final Object object) { return indexOf(object) >= 0; } /** * Converts the list into an array. * * @return the list as an array */ @Override public Object[] toArray() { // override to go 20% faster final 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 */ @Override public void add(final int index, final E obj) { modCount++; checkInterval(index, 0, size()); if (root == null) { root = new AVLNode(index, obj, null, null); } else { root = root.insert(index, obj); } size++; } /** * 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 collection's Iterator. *

* This method runs in O(n + log m) time, where m is * the size of this list and n is the size of {@code c}. * * @param c the collection to be added to this list * @return {@code true} if this list changed as a result of the call * @throws NullPointerException {@inheritDoc} */ @Override public boolean addAll(final Collection c) { if (c.isEmpty()) { return false; } modCount += c.size(); final AVLNode cTree = new AVLNode(c); root = root == null ? cTree : root.addAll(cTree, size); size += c.size(); return true; } /** * 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 */ @Override public E set(final int index, final E obj) { checkInterval(index, 0, size() - 1); final AVLNode node = root.get(index); final E result = node.value; node.setValue(obj); return result; } /** * Removes the element at the specified index. * * @param index the index to remove * @return the previous object at that index */ @Override public E remove(final int index) { modCount++; checkInterval(index, 0, size() - 1); final E result = get(index); root = root.remove(index); size--; return result; } /** * Clears the list, removing all entries. */ @Override 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(final int index, final int startIndex, final 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 E value; /** * Constructs a new node with a relative position. * * @param relativePosition the relative position of the node * @param obj the value for the node * @param rightFollower the node with the value following this one * @param leftFollower the node with the value leading this one */ private AVLNode(final int relativePosition, final E obj, final AVLNode rightFollower, final AVLNode leftFollower) { this.relativePosition = relativePosition; value = obj; rightIsNext = true; leftIsPrevious = true; right = rightFollower; left = leftFollower; } /** * Constructs a new AVL tree from a collection. *

* The collection must be nonempty. * * @param coll a nonempty collection */ private AVLNode(final Collection coll) { this(coll.iterator(), 0, coll.size() - 1, 0, null, null); } /** * Constructs a new AVL tree from a collection. *

* This is a recursive helper for {@link #AVLNode(Collection)}. A call * to this method will construct the subtree for elements {@code start} * through {@code end} of the collection, assuming the iterator * {@code e} already points at element {@code start}. * * @param iterator an iterator over the collection, which should already point * to the element at index {@code start} within the collection * @param start the index of the first element in the collection that * should be in this subtree * @param end the index of the last element in the collection that * should be in this subtree * @param absolutePositionOfParent absolute position of this node's * parent, or 0 if this node is the root * @param prev the {@code AVLNode} corresponding to element (start - 1) * of the collection, or null if start is 0 * @param next the {@code AVLNode} corresponding to element (end + 1) * of the collection, or null if end is the last element of the collection */ private AVLNode(final Iterator iterator, final int start, final int end, final int absolutePositionOfParent, final AVLNode prev, final AVLNode next) { final int mid = start + (end - start) / 2; if (start < mid) { left = new AVLNode(iterator, start, mid - 1, mid, prev, this); } else { leftIsPrevious = true; left = prev; } value = iterator.next(); relativePosition = mid - absolutePositionOfParent; if (mid < end) { right = new AVLNode(iterator, mid + 1, end, mid, this, next); } else { rightIsNext = true; right = next; } recalcHeight(); } /** * Gets the value. * * @return the value of this node */ E getValue() { return value; } /** * Sets the value. * * @param obj the value to store */ void setValue(final E obj) { this.value = obj; } /** * Locate the element with the given index relative to the * offset of the parent of this node. */ AVLNode get(final int index) { final int indexRelativeToMe = index - relativePosition; if (indexRelativeToMe == 0) { return this; } final 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(final Object object, final int index) { if (getLeftSubTree() != null) { final 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(final Object[] array, final 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(final int index, final E obj) { final int indexRelativeToMe = index - relativePosition; if (indexRelativeToMe <= 0) { return insertOnLeft(indexRelativeToMe, obj); } return insertOnRight(indexRelativeToMe, obj); } private AVLNode insertOnLeft(final int indexRelativeToMe, final E obj) { if (getLeftSubTree() == null) { setLeft(new AVLNode(-1, obj, this, left), null); } else { setLeft(left.insert(indexRelativeToMe, obj), null); } if (relativePosition >= 0) { relativePosition++; } final AVLNode ret = balance(); recalcHeight(); return ret; } private AVLNode insertOnRight(final int indexRelativeToMe, final E obj) { if (getRightSubTree() == null) { setRight(new AVLNode(+1, obj, right, this), null); } else { setRight(right.insert(indexRelativeToMe, obj), null); } if (relativePosition < 0) { relativePosition--; } final AVLNode 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(final int index) { final 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 final 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 final AVLNode leftMax = left.max(); value = leftMax.value; if (rightIsNext) { right = leftMax.right; } final 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(final AVLNode node) { if (node == null) { return 0; } return node.relativePosition; } /** * Sets the relative position. */ private int setOffset(final AVLNode node, final int newOffest) { if (node == null) { return 0; } final 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(final 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() { final AVLNode newTop = right; // can't be faedelung! final AVLNode movedNode = getRightSubTree().getLeftSubTree(); final int newTopPosition = relativePosition + getOffset(newTop); final int myNewPosition = -newTop.relativePosition; final 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() { final AVLNode newTop = left; // can't be faedelung final AVLNode movedNode = getLeftSubTree().getRightSubTree(); final int newTopPosition = relativePosition + getOffset(newTop); final int myNewPosition = -newTop.relativePosition; final 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(final AVLNode node, final 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(final AVLNode node, final AVLNode next) { rightIsNext = node == null; right = rightIsNext ? next : node; recalcHeight(); } /** * Appends the elements of another tree list to this tree list by efficiently * merging the two AVL trees. This operation is destructive to both trees and * runs in O(log(m + n)) time. * * @param otherTree * the root of the AVL tree to merge with this one * @param currentSize * the number of elements in this AVL tree * @return the root of the new, merged AVL tree */ private AVLNode addAll(AVLNode otherTree, final int currentSize) { final AVLNode maxNode = max(); final AVLNode otherTreeMin = otherTree.min(); // We need to efficiently merge the two AVL trees while keeping them // balanced (or nearly balanced). To do this, we take the shorter // tree and combine it with a similar-height subtree of the taller // tree. There are two symmetric cases: // * this tree is taller, or // * otherTree is taller. if (otherTree.height > height) { // CASE 1: The other tree is taller than this one. We will thus // merge this tree into otherTree. // STEP 1: Remove the maximum element from this tree. final AVLNode leftSubTree = removeMax(); // STEP 2: Navigate left from the root of otherTree until we // find a subtree, s, that is no taller than me. (While we are // navigating left, we store the nodes we encounter in a stack // so that we can re-balance them in step 4.) final ArrayStack> sAncestors = new ArrayStack>(); AVLNode s = otherTree; int sAbsolutePosition = s.relativePosition + currentSize; int sParentAbsolutePosition = 0; while (s != null && s.height > getHeight(leftSubTree)) { sParentAbsolutePosition = sAbsolutePosition; sAncestors.push(s); s = s.left; if (s != null) { sAbsolutePosition += s.relativePosition; } } // STEP 3: Replace s with a newly constructed subtree whose root // is maxNode, whose left subtree is leftSubTree, and whose right // subtree is s. maxNode.setLeft(leftSubTree, null); maxNode.setRight(s, otherTreeMin); if (leftSubTree != null) { leftSubTree.max().setRight(null, maxNode); leftSubTree.relativePosition -= currentSize - 1; } if (s != null) { s.min().setLeft(null, maxNode); s.relativePosition = sAbsolutePosition - currentSize + 1; } maxNode.relativePosition = currentSize - 1 - sParentAbsolutePosition; otherTree.relativePosition += currentSize; // STEP 4: Re-balance the tree and recalculate the heights of s's ancestors. s = maxNode; while (!sAncestors.isEmpty()) { final AVLNode sAncestor = sAncestors.pop(); sAncestor.setLeft(s, null); s = sAncestor.balance(); } return s; } else { // CASE 2: This tree is taller. This is symmetric to case 1. // We merge otherTree into this tree by finding a subtree s of this // tree that is of similar height to otherTree and replacing it // with a new subtree whose root is otherTreeMin and whose // children are otherTree and s. otherTree = otherTree.removeMin(); final ArrayStack> sAncestors = new ArrayStack>(); AVLNode s = this; int sAbsolutePosition = s.relativePosition; int sParentAbsolutePosition = 0; while (s != null && s.height > getHeight(otherTree)) { sParentAbsolutePosition = sAbsolutePosition; sAncestors.push(s); s = s.right; if (s != null) { sAbsolutePosition += s.relativePosition; } } otherTreeMin.setRight(otherTree, null); otherTreeMin.setLeft(s, maxNode); if (otherTree != null) { otherTree.min().setLeft(null, otherTreeMin); otherTree.relativePosition++; } if (s != null) { s.max().setRight(null, otherTreeMin); s.relativePosition = sAbsolutePosition - currentSize; } otherTreeMin.relativePosition = currentSize - sParentAbsolutePosition; s = otherTreeMin; while (!sAncestors.isEmpty()) { final AVLNode sAncestor = sAncestors.pop(); sAncestor.setRight(s, null); s = sAncestor.balance(); } return s; } } // 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. */ @Override public String toString() { return new StringBuilder() .append("AVLNode(") .append(relativePosition) .append(',') .append(left != null) .append(',') .append(value) .append(',') .append(getRightSubTree() != null) .append(", faedelung ") .append(rightIsNext) .append(" )") .toString(); } } /** * A list iterator over the linked list. */ static class TreeListIterator implements ListIterator, OrderedIterator { /** The parent list */ private final TreeList parent; /** * Cache of the next node that will be returned by {@link #next()}. */ private AVLNode next; /** * The index of the next node to be returned. */ private int nextIndex; /** * Cache of the last node that was returned by {@link #next()} * or {@link #previous()}. */ private AVLNode current; /** * The index of the last node that was returned. */ private 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. */ private int expectedModCount; /** * Create a ListIterator for a list. * * @param parent the parent list * @param fromIndex the index to start at */ protected TreeListIterator(final TreeList parent, final 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 E next() { checkModCount(); if (!hasNext()) { throw new NoSuchElementException("No element at index " + nextIndex + "."); } if (next == null) { next = parent.root.get(nextIndex); } final E value = next.getValue(); current = next; currentIndex = nextIndex++; next = next.next(); return value; } public boolean hasPrevious() { return nextIndex > 0; } public E previous() { checkModCount(); if (!hasPrevious()) { throw new NoSuchElementException("Already at start of list."); } if (next == null) { next = parent.root.get(nextIndex - 1); } else { next = next.previous(); } final E value = next.getValue(); current = next; currentIndex = --nextIndex; return value; } public int nextIndex() { return nextIndex; } public int previousIndex() { return nextIndex() - 1; } public void remove() { checkModCount(); if (currentIndex == -1) { throw new IllegalStateException(); } parent.remove(currentIndex); if (nextIndex != currentIndex) { // remove() following next() nextIndex--; } // the AVL node referenced by next may have become stale after a remove // reset it now: will be retrieved by next call to next()/previous() via nextIndex next = null; current = null; currentIndex = -1; expectedModCount++; } public void set(final E obj) { checkModCount(); if (current == null) { throw new IllegalStateException(); } current.setValue(obj); } public void add(final E obj) { checkModCount(); parent.add(nextIndex, obj); current = null; currentIndex = -1; nextIndex++; expectedModCount++; } } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/TransformedList.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/TransformedList.java100664 15405 12243235516 31721 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.Collection; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.collection.TransformedCollection; import org.apache.commons.collections4.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 3.0 * @version $Id: TransformedList.java 1494280 2013-06-18 20:07:04Z tn $ */ 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. * Contrast this with {@link #transformedList(List, Transformer)}. * * @param the type of the elements in the list * @param list the list to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed list * @throws IllegalArgumentException if list or transformer is null * @since 4.0 */ public static TransformedList transformingList(final List list, final Transformer transformer) { return new TransformedList(list, transformer); } /** * Factory method to create a transforming list that will transform * existing contents of the specified list. *

* If there are any elements already in the list being decorated, they * will be transformed by this method. * Contrast this with {@link #transformingList(List, Transformer)}. * * @param the type of the elements in the list * @param list the list to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed List * @throws IllegalArgumentException if list or transformer is null * @since 4.0 */ public static TransformedList transformedList(final List list, final Transformer transformer) { final TransformedList decorated = new TransformedList(list, transformer); if (transformer != null && list != null && list.size() > 0) { @SuppressWarnings("unchecked") // list is of type E final E[] values = (E[]) list.toArray(); // NOPMD - false positive for generics list.clear(); for (final E value : values) { decorated.decorated().add(transformer.transform(value)); } } return decorated; } //----------------------------------------------------------------------- /** * 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(final List list, final Transformer transformer) { super(list, transformer); } /** * Gets the decorated list. * * @return the decorated list */ protected List getList() { return (List) decorated(); } //----------------------------------------------------------------------- public E get(final int index) { return getList().get(index); } public int indexOf(final Object object) { return getList().indexOf(object); } public int lastIndexOf(final Object object) { return getList().lastIndexOf(object); } public E remove(final int index) { return getList().remove(index); } //----------------------------------------------------------------------- public void add(final int index, E object) { object = transform(object); getList().add(index, object); } public boolean addAll(final int index, Collection coll) { coll = transform(coll); return getList().addAll(index, coll); } public ListIterator listIterator() { return listIterator(0); } public ListIterator listIterator(final int i) { return new TransformedListIterator(getList().listIterator(i)); } public E set(final int index, E object) { object = transform(object); return getList().set(index, object); } public List subList(final int fromIndex, final int toIndex) { final List sub = getList().subList(fromIndex, toIndex); return new TransformedList(sub, transformer); } /** * Inner class Iterator for the TransformedList */ protected class TransformedListIterator extends AbstractListIteratorDecorator { /** * Create a new transformed list iterator. * * @param iterator the list iterator to decorate */ protected TransformedListIterator(final ListIterator iterator) { super(iterator); } @Override public void add(E object) { object = transform(object); getListIterator().add(object); } @Override public void set(E object) { object = transform(object); getListIterator().set(object); } } } ././@LongLink100644 0 0 167 12243235652 10263 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/AbstractSerializableListDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/AbstractSerializable100664 4606 12243235516 31734 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.List; /** * Serializable subclass of AbstractListDecorator. * * @since 3.1 * @version $Id: AbstractSerializableListDecorator.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public abstract class AbstractSerializableListDecorator extends AbstractListDecorator { /** Serialization version */ private static final long serialVersionUID = 2684959196747496299L; /** * Constructor that wraps (not copies). * * @param list the list to decorate, must not be null * @throws IllegalArgumentException if list is null */ protected AbstractSerializableListDecorator(final List list) { super(list); } //----------------------------------------------------------------------- /** * Write the list out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(decorated()); } /** * Read the list in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); setCollection((Collection) in.readObject()); } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/UnmodifiableList.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/UnmodifiableList.jav100664 11342 12243235516 31666 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableIterator; import org.apache.commons.collections4.iterators.UnmodifiableListIterator; /** * Decorates another List to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableList.java 1533984 2013-10-20 21:12:51Z tn $ */ public final class UnmodifiableList extends AbstractSerializableListDecorator implements Unmodifiable { /** Serialization version */ private static final long serialVersionUID = 6595182819922443652L; /** * Factory method to create an unmodifiable list. * * @param the type of the elements in the list * @param list the list to decorate, must not be null * @return a new unmodifiable list * @throws IllegalArgumentException if list is null * @since 4.0 */ public static List unmodifiableList(final List list) { if (list instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final List tmpList = (List) list; return tmpList; } 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 */ @SuppressWarnings("unchecked") // safe to upcast public UnmodifiableList(final List list) { super((List) list); } //----------------------------------------------------------------------- @Override public Iterator iterator() { return UnmodifiableIterator.unmodifiableIterator(decorated().iterator()); } @Override public boolean add(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean addAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- @Override public ListIterator listIterator() { return UnmodifiableListIterator.umodifiableListIterator(decorated().listIterator()); } @Override public ListIterator listIterator(final int index) { return UnmodifiableListIterator.umodifiableListIterator(decorated().listIterator(index)); } @Override public void add(final int index, final E object) { throw new UnsupportedOperationException(); } @Override public boolean addAll(final int index, final Collection coll) { throw new UnsupportedOperationException(); } @Override public E remove(final int index) { throw new UnsupportedOperationException(); } @Override public E set(final int index, final E object) { throw new UnsupportedOperationException(); } @Override public List subList(final int fromIndex, final int toIndex) { final List sub = decorated().subList(fromIndex, toIndex); return new UnmodifiableList(sub); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/PredicatedList.java100664 13150 12243235516 31474 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.collection.PredicatedCollection; import org.apache.commons.collections4.iterators.AbstractListIteratorDecorator; import java.util.Collection; import java.util.List; import java.util.ListIterator; /** * Decorates another List to validate that all additions * match a specified predicate. *

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

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

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

* This class is Serializable from Commons Collections 3.1. * * @since 3.0 * @version $Id: PredicatedList.java 1479405 2013-05-05 21:58:52Z tn $ */ 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 the type of the elements in the list * @param list the list to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @return a new predicated list * @throws IllegalArgumentException if list or predicate is null * @throws IllegalArgumentException if the list contains invalid elements * @since 4.0 */ public static PredicatedList predicatedList(final List list, final 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(final List list, final Predicate predicate) { super(list, predicate); } /** * Gets the list being decorated. * * @return the decorated list */ @Override protected List decorated() { return (List) super.decorated(); } //----------------------------------------------------------------------- public E get(final int index) { return decorated().get(index); } public int indexOf(final Object object) { return decorated().indexOf(object); } public int lastIndexOf(final Object object) { return decorated().lastIndexOf(object); } public E remove(final int index) { return decorated().remove(index); } //----------------------------------------------------------------------- public void add(final int index, final E object) { validate(object); decorated().add(index, object); } public boolean addAll(final int index, final Collection coll) { for (final E aColl : coll) { validate(aColl); } return decorated().addAll(index, coll); } public ListIterator listIterator() { return listIterator(0); } public ListIterator listIterator(final int i) { return new PredicatedListIterator(decorated().listIterator(i)); } public E set(final int index, final E object) { validate(object); return decorated().set(index, object); } public List subList(final int fromIndex, final int toIndex) { final List sub = decorated().subList(fromIndex, toIndex); return new PredicatedList(sub, predicate); } /** * Inner class Iterator for the PredicatedList */ protected class PredicatedListIterator extends AbstractListIteratorDecorator { /** * Create a new predicated list iterator. * * @param iterator the list iterator to decorate */ protected PredicatedListIterator(final ListIterator iterator) { super(iterator); } @Override public void add(final E object) { validate(object); getListIterator().add(object); } @Override public void set(final E object) { validate(object); getListIterator().set(object); } } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/CursorableLinkedList.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/CursorableLinkedList100664 54430 12243235516 31746 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 1.0 * @version $Id: CursorableLinkedList.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 */ private transient List>> cursors; //----------------------------------------------------------------------- /** * 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(final Collection coll) { super(coll); } /** * The equivalent of a default constructor called * by any constructor and by readObject. */ @Override 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 */ @Override 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 */ @Override 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 */ @Override public ListIterator listIterator(final 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(final int fromIndex) { final 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 */ @Override protected void updateNode(final Node node, final E value) { super.updateNode(node, value); broadcastNodeChanged(node); } /** * Inserts a new node into the list. * * @param nodeToInsert new node to insert * @param insertBeforeNode node to insert before * @throws NullPointerException if either node is null */ @Override protected void addNode(final Node nodeToInsert, final 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 */ @Override protected void removeNode(final Node node) { super.removeNode(node); broadcastNodeRemoved(node); } /** * Removes all nodes by iteration. */ @Override protected void removeAllNodes() { if (size() > 0) { // superclass implementation would break all the iterators final 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(final Cursor cursor) { // We take this opportunity to clean the cursors list // of WeakReference objects to garbage-collected cursors. for (final Iterator>> it = cursors.iterator(); it.hasNext();) { final WeakReference> ref = it.next(); if (ref.get() == null) { it.remove(); } } cursors.add(new WeakReference>(cursor)); } /** * Deregisters a cursor from the list to be notified of changes. * * @param cursor the cursor to deregister */ protected void unregisterCursor(final Cursor cursor) { for (final Iterator>> it = cursors.iterator(); it.hasNext();) { final WeakReference> ref = it.next(); final Cursor cur = 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(final Node node) { final Iterator>> it = cursors.iterator(); while (it.hasNext()) { final WeakReference> ref = it.next(); final 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(final Node node) { final Iterator>> it = cursors.iterator(); while (it.hasNext()) { final WeakReference> ref = it.next(); final 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(final Node node) { final Iterator>> it = cursors.iterator(); while (it.hasNext()) { final WeakReference> ref = it.next(); final 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(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); doWriteObject(out); } /** * Deserializes the data held in this object to the stream specified. */ private void readObject(final 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 * @return the list iterator for the sublist */ @Override protected ListIterator createSubListListIterator(final LinkedSubList subList, final int fromIndex) { final 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 parent the parent list * @param index the index to start from */ protected Cursor(final CursorableLinkedList parent, final 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 */ @Override public void remove() { // overridden, as the nodeRemoved() method updates the iterator // state in the parent.removeNode() call below if (current == null && currentRemovedByAnother) { // NOPMD // 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 */ @Override public void add(final E 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 */ @Override 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(final 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(final 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(final 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. */ @Override 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 3.2 */ protected static class SubCursor extends Cursor { /** The parent list */ protected final LinkedSubList sub; /** * Constructs a new cursor. * * @param sub the sub list * @param index the index to start from */ protected SubCursor(final LinkedSubList sub, final int index) { super((CursorableLinkedList) sub.parent, index + sub.offset); this.sub = sub; } @Override public boolean hasNext() { return nextIndex() < sub.size; } @Override public boolean hasPrevious() { return previousIndex() >= 0; } @Override public int nextIndex() { return super.nextIndex() - sub.offset; } @Override public void add(final E obj) { super.add(obj); sub.expectedModCount = parent.modCount; sub.size++; } @Override public void remove() { super.remove(); sub.expectedModCount = parent.modCount; sub.size--; } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/GrowthList.java100664 17013 12243235516 30704 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 3.2 * @version $Id: GrowthList.java 1479405 2013-05-05 21:58:52Z tn $ */ public class GrowthList extends AbstractSerializableListDecorator { /** Serialization version */ private static final long serialVersionUID = -3620001881672L; /** * Factory method to create a growth list. * * @param the type of the elements in the list * @param list the list to decorate, must not be null * @return a new growth list * @throws IllegalArgumentException if list is null * @since 4.0 */ public static GrowthList growthList(final 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(final 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(final 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 */ @Override public void add(final int index, final E element) { final int size = decorated().size(); if (index > size) { decorated().addAll(Collections.nCopies(index - size, null)); } decorated().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 */ @Override public boolean addAll(final int index, final Collection coll) { final int size = decorated().size(); boolean result = false; if (index > size) { decorated().addAll(Collections.nCopies(index - size, null)); result = true; } return decorated().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 */ @Override public E set(final int index, final E element) { final int size = decorated().size(); if (index >= size) { decorated().addAll(Collections.nCopies(index - size + 1, null)); } return decorated().set(index, element); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/package-info.java100664 4004 12243235516 31076 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This 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: *

    *
  • Unmodifiable - ensures the collection cannot be altered
  • *
  • Predicated - ensures that only elements that are valid according to a predicate 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
  • *
* * @version $Id: package-info.java 1469004 2013-04-17 17:37:03Z tn $ */ package org.apache.commons.collections4.list; commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/LazyList.java100664 12377 12243235516 30361 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.list; import java.util.List; import org.apache.commons.collections4.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<Date> factory = new Factory<Date>() {
 *     public Date create() {
 *         return new Date();
 *     }
 * }
 * List<Date> lazy = LazyList.decorate(new ArrayList<Date>(), factory);
 * Date date = lazy.get(3);
 * 
* * After the above code is executed, date 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 3.0 * @version $Id: LazyList.java 1479405 2013-05-05 21:58:52Z tn $ */ public class LazyList extends AbstractSerializableListDecorator { /** Serialization version */ private static final long serialVersionUID = -1708388017160694542L; /** The factory to use to lazily instantiate the objects */ private final Factory factory; /** * Factory method to create a lazily instantiating list. * * @param the type of the elements in the list * @param list the list to decorate, must not be null * @param factory the factory to use for creation, must not be null * @return a new lazy list * @throws IllegalArgumentException if list or factory is null * @since 4.0 */ public static LazyList lazyList(final List list, final 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(final List list, final 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 * @return the element at the given index */ @Override public E get(final int index) { final int size = decorated().size(); if (index < size) { // within bounds, get the object E object = decorated().get(index); if (object == null) { // item is a place holder, create new one, set and return object = factory.create(); decorated().set(index, object); return object; } // good and ready to go return object; } // we have to grow the list for (int i = size; i < index; i++) { decorated().add(null); } // create our last object, set and return final E object = factory.create(); decorated().add(object); return object; } @Override public List subList(final int fromIndex, final int toIndex) { final List sub = decorated().subList(fromIndex, toIndex); return new LazyList(sub, factory); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/SetUniqueList.java100664 32577 12243235516 31370 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.ListUtils; import org.apache.commons.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.iterators.AbstractIteratorDecorator; import org.apache.commons.collections4.iterators.AbstractListIteratorDecorator; /** * 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.collections4.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 3.0 * @version $Id: SetUniqueList.java 1479405 2013-05-05 21:58:52Z tn $ */ public class SetUniqueList extends AbstractSerializableListDecorator { /** Serialization version. */ private static final long serialVersionUID = 7196982186153478694L; /** Internal Set to maintain uniqueness. */ private 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 the element type * @param list the list to decorate, must not be null * @return a new {@link SetUniqueList} * @throws IllegalArgumentException if list is null * @since 4.0 */ public static SetUniqueList setUniqueList(final List list) { if (list == null) { throw new IllegalArgumentException("List must not be null"); } if (list.isEmpty()) { return new SetUniqueList(list, new HashSet()); } final List temp = new ArrayList(list); list.clear(); final 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(final List list, final 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.unmodifiableSet(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 */ @Override public boolean add(final E object) { // gets initial size final int sizeBefore = size(); // adds element if unique add(size(), object); // compares sizes to detect if collection changed return sizeBefore != size(); } /** * Adds an element to a specific index in the list if it is not already * present. *

* (Violation) The List interface makes the assumption * that the element is always inserted. This may not happen with this * implementation. * * @param index the index to insert at * @param object the object to add */ @Override public void add(final int index, final E object) { // adds element if it is not contained already if (set.contains(object) == false) { super.add(index, object); set.add(object); } } /** * 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 coll the collection to add in iterator order * @return true if this collection changed */ @Override public boolean addAll(final Collection coll) { return addAll(size(), coll); } /** * Adds a collection of objects a specific index in 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 */ @Override public boolean addAll(final int index, final Collection coll) { final List temp = new ArrayList(); for (final E e : coll) { if (set.add(e)) { temp.add(e); } } return super.addAll(index, temp); } // ----------------------------------------------------------------------- /** * 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 */ @Override public E set(final int index, final E object) { final int pos = indexOf(object); final E removed = super.set(index, object); if (pos != -1 && pos != index) { // the object is already in the unique 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 set.add(object); // add the new item to the unique set return removed; // return the item deleted by the set } @Override public boolean remove(final Object object) { final boolean result = set.remove(object); if (result) { super.remove(object); } return result; } @Override public E remove(final int index) { final E result = super.remove(index); set.remove(result); return result; } @Override public boolean removeAll(final Collection coll) { boolean result = false; for (final Object name : coll) { result |= remove(name); } return result; } @Override public boolean retainAll(final Collection coll) { final Set setRetainAll = new HashSet(); for (final Object next : coll) { if (set.contains(next)) { setRetainAll.add(next); } } if (setRetainAll.size() == set.size()) { return false; } if (setRetainAll.size() == 0) { clear(); } else { for (final Iterator it = iterator(); it.hasNext();) { if (!setRetainAll.contains(it.next())) { it.remove(); } } } return true; } @Override public void clear() { super.clear(); set.clear(); } @Override public boolean contains(final Object object) { return set.contains(object); } @Override public boolean containsAll(final Collection coll) { return set.containsAll(coll); } @Override public Iterator iterator() { return new SetListIterator(super.iterator(), set); } @Override public ListIterator listIterator() { return new SetListListIterator(super.listIterator(), set); } @Override public ListIterator listIterator(final int index) { return new SetListListIterator(super.listIterator(index), set); } /** * {@inheritDoc} *

* NOTE: from 4.0, an unmodifiable list will be returned, as changes to the * subList can invalidate the parent list. */ @Override public List subList(final int fromIndex, final int toIndex) { final List superSubList = super.subList(fromIndex, toIndex); final Set subSet = createSetBasedOnList(set, superSubList); return ListUtils.unmodifiableList(new SetUniqueList(superSubList, subSet)); } /** * Create a new {@link Set} with the same type as the provided {@code set} * and populate it with all elements of {@code list}. * * @param set the {@link Set} to be used as return type, must not be null * @param list the {@link List} to populate the {@link Set} * @return a new {@link Set} populated with all elements of the provided * {@link List} */ @SuppressWarnings("unchecked") protected Set createSetBasedOnList(final Set set, final List list) { Set subSet; if (set.getClass().equals(HashSet.class)) { subSet = new HashSet(list.size()); } else { try { subSet = set.getClass().newInstance(); } catch (final InstantiationException ie) { subSet = new HashSet(); } catch (final IllegalAccessException iae) { subSet = new HashSet(); } } subSet.addAll(list); return subSet; } // ----------------------------------------------------------------------- /** * Inner class iterator. */ static class SetListIterator extends AbstractIteratorDecorator { private final Set set; private E last = null; protected SetListIterator(final Iterator it, final Set set) { super(it); this.set = set; } @Override public E next() { last = super.next(); return last; } @Override public void remove() { super.remove(); set.remove(last); last = null; } } /** * Inner class iterator. */ static class SetListListIterator extends AbstractListIteratorDecorator { private final Set set; private E last = null; protected SetListListIterator(final ListIterator it, final Set set) { super(it); this.set = set; } @Override public E next() { last = super.next(); return last; } @Override public E previous() { last = super.previous(); return last; } @Override public void remove() { super.remove(); set.remove(last); last = null; } @Override public void add(final E object) { if (set.contains(object) == false) { super.add(object); set.add(object); } } @Override public void set(final E object) { throw new UnsupportedOperationException("ListIterator does not support set"); } } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/AbstractLinkedList.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/list/AbstractLinkedList.j100664 101316 12243235516 31654 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.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 3.0 * @version $Id: AbstractLinkedList.java 1494296 2013-06-18 20:54:29Z tn $ */ 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. */ transient Node header; /** The size of the list */ transient int size; /** Modification count for iterators */ 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(final Collection coll) { super(); init(); addAll(coll); } /** * The equivalent of a default constructor, broken out so it can be called * by any constructor and by readObject. * Subclasses which override this method should make sure they call super, * so the list is initialised properly. */ protected void init() { header = createHeaderNode(); } //----------------------------------------------------------------------- public int size() { return size; } public boolean isEmpty() { return size() == 0; } public E get(final int index) { final Node node = getNode(index, false); return node.getValue(); } //----------------------------------------------------------------------- public Iterator iterator() { return listIterator(); } public ListIterator listIterator() { return new LinkedListIterator(this, 0); } public ListIterator listIterator(final int fromIndex) { return new LinkedListIterator(this, fromIndex); } //----------------------------------------------------------------------- public int indexOf(final 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(final 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(final Object value) { return indexOf(value) != -1; } public boolean containsAll(final Collection coll) { for (final Object o : coll) { if (!contains(o)) { return false; } } return true; } //----------------------------------------------------------------------- public Object[] toArray() { return toArray(new Object[size]); } @SuppressWarnings("unchecked") public T[] toArray(T[] array) { // Extend the array if needed if (array.length < size) { final Class componentType = array.getClass().getComponentType(); array = (T[]) Array.newInstance(componentType, size); } // Copy the values into the array int i = 0; for (Node node = header.next; node != header; node = node.next, i++) { array[i] = (T) 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(final int fromIndexInclusive, final int toIndexExclusive) { return new LinkedSubList(this, fromIndexInclusive, toIndexExclusive); } //----------------------------------------------------------------------- public boolean add(final E value) { addLast(value); return true; } public void add(final int index, final E value) { final Node node = getNode(index, true); addNodeBefore(node, value); } public boolean addAll(final Collection coll) { return addAll(size, coll); } public boolean addAll(final int index, final Collection coll) { final Node node = getNode(index, true); for (final E e : coll) { addNodeBefore(node, e); } return true; } //----------------------------------------------------------------------- public E remove(final int index) { final Node node = getNode(index, false); final E oldValue = node.getValue(); removeNode(node); return oldValue; } public boolean remove(final Object value) { for (Node node = header.next; node != header; node = node.next) { if (isEqualValue(node.getValue(), value)) { removeNode(node); return true; } } return false; } /** * {@inheritDoc} *

* This implementation iterates over the elements of this list, checking each element in * turn to see if it's contained in coll. If it's contained, it's removed * from this list. As a consequence, it is advised to use a collection type for * coll that provides a fast (e.g. O(1)) implementation of * {@link Collection#contains(Object)}. */ public boolean removeAll(final Collection coll) { boolean modified = false; final Iterator it = iterator(); while (it.hasNext()) { if (coll.contains(it.next())) { it.remove(); modified = true; } } return modified; } //----------------------------------------------------------------------- /** * {@inheritDoc} *

* This implementation iterates over the elements of this list, checking each element in * turn to see if it's contained in coll. If it's not contained, it's removed * from this list. As a consequence, it is advised to use a collection type for * coll that provides a fast (e.g. O(1)) implementation of * {@link Collection#contains(Object)}. */ public boolean retainAll(final Collection coll) { boolean modified = false; final Iterator it = iterator(); while (it.hasNext()) { if (coll.contains(it.next()) == false) { it.remove(); modified = true; } } return modified; } public E set(final int index, final E value) { final Node node = getNode(index, false); final E oldValue = node.getValue(); updateNode(node, value); return oldValue; } public void clear() { removeAllNodes(); } //----------------------------------------------------------------------- public E getFirst() { final Node node = header.next; if (node == header) { throw new NoSuchElementException(); } return node.getValue(); } public E getLast() { final Node node = header.previous; if (node == header) { throw new NoSuchElementException(); } return node.getValue(); } public boolean addFirst(final E o) { addNodeAfter(header, o); return true; } public boolean addLast(final E o) { addNodeBefore(header, o); return true; } public E removeFirst() { final Node node = header.next; if (node == header) { throw new NoSuchElementException(); } final E oldValue = node.getValue(); removeNode(node); return oldValue; } public E removeLast() { final Node node = header.previous; if (node == header) { throw new NoSuchElementException(); } final E oldValue = node.getValue(); removeNode(node); return oldValue; } //----------------------------------------------------------------------- @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof List == false) { return false; } final List other = (List) obj; if (other.size() != size()) { return false; } final ListIterator it1 = listIterator(); final ListIterator it2 = other.listIterator(); while (it1.hasNext() && it2.hasNext()) { final Object o1 = it1.next(); final Object o2 = it2.next(); if (!(o1 == null ? o2 == null : o1.equals(o2))) { return false; } } return !(it1.hasNext() || it2.hasNext()); } @Override public int hashCode() { int hashCode = 1; for (final E e : this) { hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode()); } return hashCode; } @Override public String toString() { if (size() == 0) { return "[]"; } final StringBuilder buf = new StringBuilder(16 * size()); buf.append('['); final Iterator it = iterator(); boolean hasNext = it.hasNext(); while (hasNext) { final 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(final Object value1, final 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(final Node node, final E value) { node.setValue(value); } /** * Creates a new node with previous, next and element all set to null. * This implementation creates a new empty Node. * Subclasses can override this to create a different class. * * @return newly created node */ protected Node createHeaderNode() { return new Node(); } /** * Creates a new node with the specified properties. * This implementation creates a new Node with data. * Subclasses can override this to create a different class. * * @param value value of the new node * @return a new node containing the value */ protected Node createNode(final E value) { return new Node(value); } /** * Creates a new node with the specified object as its * value and inserts it before node. *

* This implementation uses {@link #createNode(Object)} and * {@link #addNode(AbstractLinkedList.Node,AbstractLinkedList.Node)}. * * @param node node to insert before * @param value value of the newly added node * @throws NullPointerException if node is null */ protected void addNodeBefore(final Node node, final E value) { final 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(final Node node, final E value) { final 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(final Node nodeToInsert, final 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(final 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 * @return the node at the given index * @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(final int index, final 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 * @return a new iterator on the given sublist */ protected Iterator createSubListIterator(final 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 * @return a new list iterator on the given sublist */ protected ListIterator createSubListListIterator(final LinkedSubList subList, final 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. * * @param outputStream the stream to write the object to * @throws IOException if anything goes wrong */ protected void doWriteObject(final ObjectOutputStream outputStream) throws IOException { // Write the size so we know how many nodes to read back outputStream.writeInt(size()); for (final E e : this) { outputStream.writeObject(e); } } /** * Deserializes the data held in this object to the stream specified. *

* The first serializable subclass must call this method from * readObject. * * @param inputStream the stream to read the object from * @throws IOException if any error occurs while reading from the stream * @throws ClassNotFoundException if a class read from the stream can not be loaded */ @SuppressWarnings("unchecked") protected void doReadObject(final ObjectInputStream inputStream) throws IOException, ClassNotFoundException { init(); final int size = inputStream.readInt(); for (int i = 0; i < size; i++) { add((E) inputStream.readObject()); } } //----------------------------------------------------------------------- /** * A node within the linked list. *

* From Commons Collections 3.1, all access to the value property * is via the methods on this class. */ protected static class Node { /** A pointer to the node before this node */ protected Node previous; /** A pointer to the node after this node */ protected Node next; /** The object contained within this node */ protected E 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(final E 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(final Node previous, final Node next, final E value) { super(); this.previous = previous; this.next = next; this.value = value; } /** * Gets the value of the node. * * @return the value * @since 3.1 */ protected E getValue() { return value; } /** * Sets the value of the node. * * @param value the value * @since 3.1 */ protected void setValue(final E value) { this.value = value; } /** * Gets the previous node. * * @return the previous node * @since 3.1 */ protected Node getPreviousNode() { return previous; } /** * Sets the previous node. * * @param previous the previous node * @since 3.1 */ protected void setPreviousNode(final Node previous) { this.previous = previous; } /** * Gets the next node. * * @return the next node * @since 3.1 */ protected Node getNextNode() { return next; } /** * Sets the next node. * * @param next the next node * @since 3.1 */ protected void setNextNode(final 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 * @throws IndexOutOfBoundsException if fromIndex is less than 0 or greater than the size of the list */ protected LinkedListIterator(final AbstractLinkedList parent, final 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. * * @return the last node returned * @throws IllegalStateException If {@link #next()} or {@link #previous()} haven't been called, * or if the node has been removed with {@link #remove()} or a new node added with {@link #add(Object)}. */ protected Node getLastNodeReturned() throws IllegalStateException { if (current == null) { throw new IllegalStateException(); } return current; } public boolean hasNext() { return next != parent.header; } public E next() { checkModCount(); if (!hasNext()) { throw new NoSuchElementException("No element at index " + nextIndex + "."); } final E value = next.getValue(); current = next; next = next.next; nextIndex++; return value; } public boolean hasPrevious() { return next.previous != parent.header; } public E previous() { checkModCount(); if (!hasPrevious()) { throw new NoSuchElementException("Already at start of list."); } next = next.previous; final E value = next.getValue(); current = next; nextIndex--; return value; } public int nextIndex() { return nextIndex; } public int previousIndex() { // not normally overridden, as relative to nextIndex() return nextIndex() - 1; } public void remove() { checkModCount(); 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(final E obj) { checkModCount(); getLastNodeReturned().setValue(obj); } public void add(final E obj) { checkModCount(); parent.addNodeBefore(next, obj); current = null; nextIndex++; expectedModCount++; } } //----------------------------------------------------------------------- /** * A list iterator over the linked sub list. */ protected static class LinkedSubListIterator extends LinkedListIterator { /** The parent list */ protected final LinkedSubList sub; protected LinkedSubListIterator(final LinkedSubList sub, final int startIndex) { super(sub.parent, startIndex + sub.offset); this.sub = sub; } @Override public boolean hasNext() { return nextIndex() < sub.size; } @Override public boolean hasPrevious() { return previousIndex() >= 0; } @Override public int nextIndex() { return super.nextIndex() - sub.offset; } @Override public void add(final E obj) { super.add(obj); sub.expectedModCount = parent.modCount; sub.size++; } @Override 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(final AbstractLinkedList parent, final int fromIndex, final 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; } @Override public int size() { checkModCount(); return size; } @Override public E get(final int index) { rangeCheck(index, size); checkModCount(); return parent.get(index + offset); } @Override public void add(final int index, final E obj) { rangeCheck(index, size + 1); checkModCount(); parent.add(index + offset, obj); expectedModCount = parent.modCount; size++; LinkedSubList.this.modCount++; } @Override public E remove(final int index) { rangeCheck(index, size); checkModCount(); final E result = parent.remove(index + offset); expectedModCount = parent.modCount; size--; LinkedSubList.this.modCount++; return result; } @Override public boolean addAll(final Collection coll) { return addAll(size, coll); } @Override public boolean addAll(final int index, final Collection coll) { rangeCheck(index, size + 1); final 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; } @Override public E set(final int index, final E obj) { rangeCheck(index, size); checkModCount(); return parent.set(index + offset, obj); } @Override public void clear() { checkModCount(); final Iterator it = iterator(); while (it.hasNext()) { it.next(); it.remove(); } } @Override public Iterator iterator() { checkModCount(); return parent.createSubListIterator(this); } @Override public ListIterator listIterator(final int index) { rangeCheck(index, size + 1); checkModCount(); return parent.createSubListListIterator(this, index); } @Override public List subList(final int fromIndexInclusive, final int toIndexExclusive) { return new LinkedSubList(parent, fromIndexInclusive + offset, toIndexExclusive + offset); } protected void rangeCheck(final int index, final 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(); } } } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/BooleanComparator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/BooleanCompar100664 15631 12243235516 31762 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 #booleanComparator(boolean) * * @since 3.0 * @version $Id: BooleanComparator.java 1479403 2013-05-05 21:54:13Z tn $ */ 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 * @since 4.0 */ public static BooleanComparator booleanComparator(final 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(final boolean trueFirst) { this.trueFirst = trueFirst; } //----------------------------------------------------------------------- /** * 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(final Boolean b1, final Boolean b2) { final boolean v1 = b1.booleanValue(); final 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. */ @Override public int hashCode() { final 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 */ @Override public boolean equals(final 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; } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/package-info.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/package-info.100664 2356 12243235516 31623 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains implementations of the * {@link java.util.Comparator Comparator} interface. *

* You may also consider using * {@link org.apache.commons.collections4.ComparatorUtils ComparatorUtils}, * which is a single class that uses static methods to construct instances * of the classes in this package. * * @version $Id: package-info.java 1477747 2013-04-30 18:16:48Z tn $ */ package org.apache.commons.collections4.comparators; ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/ReverseComparator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/ReverseCompar100664 10533 12243235516 32012 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.comparators; import java.io.Serializable; import java.util.Comparator; import org.apache.commons.collections4.ComparatorUtils; /** * Reverses the order of another comparator by reversing the arguments * to its {@link #compare(Object, Object) compare} method. * * @since 2.0 * @version $Id: ReverseComparator.java 1533984 2013-10-20 21:12:51Z tn $ * * @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 final 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 */ @SuppressWarnings("unchecked") public ReverseComparator(final Comparator comparator) { this.comparator = comparator == null ? ComparatorUtils.NATURAL_COMPARATOR : comparator; } //----------------------------------------------------------------------- /** * Compares two objects in reverse order. * * @param obj1 the first object to compare * @param obj2 the second object to compare * @return negative if obj1 is less, positive if greater, zero if equal */ public int compare(final E obj1, final E 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 3.0 */ @Override 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 3.0 */ @Override public boolean equals(final Object object) { if (this == object) { return true; } if (null == object) { return false; } if (object.getClass().equals(this.getClass())) { final ReverseComparator thatrc = (ReverseComparator) object; return comparator.equals(thatrc.comparator); } return false; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/ComparatorChain.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/ComparatorCha100664 30264 12243235516 31763 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 2.0 * @version $Id: ComparatorChain.java 1533984 2013-10-20 21:12:51Z tn $ */ 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. */ private final List> comparatorChain; /** Order - false (clear) = ascend; true (set) = descend. */ private BitSet orderingBits = null; /** Whether the chain has been "locked". */ private 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(final 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(final Comparator comparator, final boolean reverse) { comparatorChain = new ArrayList>(1); 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(final 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(final List> list, final 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(final 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(final Comparator comparator, final 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(final int index, final 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(final int index, final Comparator comparator, final 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(final 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(final 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; } /** * Throws an exception if the {@link ComparatorChain} is locked. * * @throws UnsupportedOperationException if the {@link ComparatorChain} is locked */ private void checkLocked() { if (isLocked == true) { throw new UnsupportedOperationException( "Comparator ordering cannot be changed after the first comparison is performed"); } } /** * Throws an exception if the {@link ComparatorChain} is empty. * * @throws UnsupportedOperationException if the {@link ComparatorChain} is empty */ private void checkChainIntegrity() { if (comparatorChain.size() == 0) { throw new UnsupportedOperationException("ComparatorChains must contain at least one Comparator"); } } //----------------------------------------------------------------------- /** * Perform comparisons on the Objects as per * Comparator.compare(o1,o2). * * @param o1 the first object to compare * @param o2 the second object to compare * @return -1, 0, or 1 * @throws UnsupportedOperationException if the ComparatorChain does not contain at least one Comparator */ public int compare(final E o1, final E o2) throws UnsupportedOperationException { if (isLocked == false) { checkChainIntegrity(); isLocked = true; } // iterate over all comparators in the chain final Iterator> comparators = comparatorChain.iterator(); for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) { final 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 (retval > 0) { retval = -1; } 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 3.0 */ @Override 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 3.0 */ @Override public boolean equals(final Object object) { if (this == object) { return true; } if (null == object) { return false; } if (object.getClass().equals(this.getClass())) { final ComparatorChain chain = (ComparatorChain) object; return (null == orderingBits ? null == chain.orderingBits : orderingBits.equals(chain.orderingBits)) && (null == comparatorChain ? null == chain.comparatorChain : comparatorChain.equals(chain.comparatorChain)); } return false; } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/TransformingComparator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/TransformingC100664 11674 12243235516 32020 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.comparators; import java.io.Serializable; import java.util.Comparator; import org.apache.commons.collections4.ComparatorUtils; import org.apache.commons.collections4.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. *

* This class is Serializable from Commons Collections 4.0. * * @since 2.1 * @version $Id: TransformingComparator.java 1477747 2013-04-30 18:16:48Z tn $ * * @see org.apache.commons.collections4.Transformer * @see org.apache.commons.collections4.comparators.ComparableComparator */ public class TransformingComparator implements Comparator, Serializable { /** Serialization version from Collections 4.0. */ private static final long serialVersionUID = 3456940356043606220L; /** The decorated comparator. */ private final Comparator decorated; /** The transformer being used. */ private final Transformer transformer; //----------------------------------------------------------------------- /** * Constructs an instance with the given Transformer and a * {@link ComparableComparator ComparableComparator}. * * @param transformer what will transform the arguments to compare */ @SuppressWarnings("unchecked") public TransformingComparator(final Transformer transformer) { this(transformer, ComparatorUtils.NATURAL_COMPARATOR); } /** * 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(final Transformer transformer, final 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(final I obj1, final I obj2) { final O value1 = this.transformer.transform(obj1); final O value2 = this.transformer.transform(obj2); return this.decorated.compare(value1, value2); } //----------------------------------------------------------------------- /** * Implement a hash code for this comparator that is consistent with * {@link #equals(Object) equals}. * * @return a hash code for this comparator. */ @Override public int hashCode() { int total = 17; total = total*37 + (decorated == null ? 0 : decorated.hashCode()); total = total*37 + (transformer == null ? 0 : transformer.hashCode()); return total; } /** * 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 TransformingComparator} * whose attributes are equal to mine. * * @param object the object to compare to * @return true if equal */ @Override public boolean equals(final Object object) { if (this == object) { return true; } if (null == object) { return false; } if (object.getClass().equals(this.getClass())) { final TransformingComparator comp = (TransformingComparator) object; return null == decorated ? null == comp.decorated : decorated.equals(comp.decorated) && null == transformer ? null == comp.transformer : transformer.equals(comp.transformer); } return false; } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/NullComparator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/NullComparato100664 16171 12243235516 32021 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.comparators; import java.io.Serializable; import java.util.Comparator; import org.apache.commons.collections4.ComparatorUtils; /** * A Comparator that will compare nulls to be either lower or higher than * other objects. * * @since 2.0 * @version $Id: NullComparator.java 1533984 2013-10-20 21:12:51Z tn $ */ 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 final Comparator nonNullComparator; /** * Specifies whether a null are compared as higher than * non-null objects. **/ private final 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. **/ @SuppressWarnings("unchecked") public NullComparator() { this(ComparatorUtils.NATURAL_COMPARATOR, 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(final 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. **/ @SuppressWarnings("unchecked") public NullComparator(final boolean nullsAreHigh) { this(ComparatorUtils.NATURAL_COMPARATOR, 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(final Comparator nonNullComparator, final 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(final E o1, final E 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. **/ @Override 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. **/ @Override public boolean equals(final Object obj) { if(obj == null) { return false; } if(obj == this) { return true; } if(!obj.getClass().equals(this.getClass())) { return false; } final NullComparator other = (NullComparator) obj; return this.nullsAreHigh == other.nullsAreHigh && this.nonNullComparator.equals(other.nonNullComparator); } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/FixedOrderComparator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/FixedOrderCom100664 26417 12243235516 31737 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.comparators; import java.io.Serializable; import java.util.Comparator; import java.util.HashMap; 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. *

* This class is Serializable from Commons Collections 4.0. * * @since 3.0 * @version $Id: FixedOrderComparator.java 1479344 2013-05-05 15:48:01Z tn $ */ public class FixedOrderComparator implements Comparator, Serializable { /** Serialization version from Collections 4.0. */ private static final long serialVersionUID = 82794675842863201L; /** * Unknown object behavior enum. * @since 4.0 */ public static enum UnknownObjectBehavior { BEFORE, AFTER, EXCEPTION; } /** 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 UnknownObjectBehavior unknownObjectBehavior = UnknownObjectBehavior.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(final T... items) { super(); if (items == null) { throw new IllegalArgumentException("The list of items must not be null"); } for (final T item : items) { add(item); } } /** * 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(final List items) { super(); if (items == null) { throw new IllegalArgumentException("The list of items must not be null"); } for (final T t : items) { add(t); } } // 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 {@link UnknownObjectBehavior} */ public UnknownObjectBehavior 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(final UnknownObjectBehavior unknownObjectBehavior) { checkLocked(); if (unknownObjectBehavior == null) { throw new IllegalArgumentException("Unknown object behavior must not be null"); } 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(final T obj) { checkLocked(); final Integer position = map.put(obj, Integer.valueOf(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(final T existingObj, final T newObj) { checkLocked(); final Integer position = map.get(existingObj); if (position == null) { throw new IllegalArgumentException(existingObj + " not known to " + this); } final Integer result = map.put(newObj, position); return result == null; } // Comparator methods //----------------------------------------------------------------------- /** * Compares two objects according to the order of this Comparator. *

* It is important to note that this class will throw an IllegalArgumentException * in the case of an unrecognised object. This is not specified in the * Comparator interface, but is the most appropriate exception. * * @param obj1 the first object to compare * @param obj2 the second object to compare * @return negative if obj1 is less, positive if greater, zero if equal * @throws IllegalArgumentException if obj1 or obj2 are not known * to this Comparator and an alternative behavior has not been set * via {@link #setUnknownObjectBehavior(UnknownObjectBehavior)}. */ public int compare(final T obj1, final T obj2) { isLocked = true; final Integer position1 = map.get(obj1); final Integer position2 = map.get(obj2); if (position1 == null || position2 == null) { switch (unknownObjectBehavior) { case BEFORE: return position1 == null ? position2 == null ? 0 : -1 : 1; case AFTER: return position1 == null ? position2 == null ? 0 : 1 : -1; case EXCEPTION: final Object unknownObj = position1 == null ? obj1 : obj2; throw new IllegalArgumentException("Attempting to compare unknown object " + unknownObj); default: //could be null throw new UnsupportedOperationException("Unknown unknownObjectBehavior: " + unknownObjectBehavior); } } return position1.compareTo(position2); } //----------------------------------------------------------------------- /** * Implement a hash code for this comparator that is consistent with * {@link #equals(Object) equals}. * * @return a hash code for this comparator. */ @Override public int hashCode() { int total = 17; total = total*37 + (map == null ? 0 : map.hashCode()); total = total*37 + (unknownObjectBehavior == null ? 0 : unknownObjectBehavior.hashCode()); total = total*37 + counter; total = total*37 + (isLocked ? 0 : 1); return total; } /** * 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 FixedOrderComparator} * whose attributes are equal to mine. * * @param object the object to compare to * @return true if equal */ @Override public boolean equals(final Object object) { if (this == object) { return true; } if (null == object) { return false; } if (object.getClass().equals(this.getClass())) { final FixedOrderComparator comp = (FixedOrderComparator) object; return null == map ? null == comp.map : map.equals(comp.map) && null == unknownObjectBehavior ? null == comp.unknownObjectBehavior : unknownObjectBehavior == comp.unknownObjectBehavior && counter == comp.counter && isLocked == comp.isLocked && unknownObjectBehavior == comp.unknownObjectBehavior; } return false; } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/ComparableComparator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/comparators/ComparableCom100664 12013 12243235516 31734 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 {@link java.util.SortedSet SortedSet} and {@link java.util.SortedMap 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 2.0 * @version $Id: ComparableComparator.java 1543950 2013-11-20 21:13:35Z tn $ * * @see java.util.Collections#reverseOrder() */ public class ComparableComparator> implements Comparator, Serializable { /** Serialization version. */ private static final long serialVersionUID=-291439688585137865L; /** The singleton instance. */ @SuppressWarnings("rawtypes") public 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. * * @param the element type * @return the singleton ComparableComparator * @since 4.0 */ @SuppressWarnings("unchecked") public static > ComparableComparator comparableComparator() { return (ComparableComparator) INSTANCE; } //----------------------------------------------------------------------- /** * Constructor whose use should be avoided. *

* Please use the {@link #comparableComparator()} 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 if obj1 is null, * or when ((Comparable)obj1).compareTo(obj2) does * @throws ClassCastException if obj1 is not a Comparable, * or when ((Comparable)obj1).compareTo(obj2) does */ public int compare(final E obj1, final E obj2) { return obj1.compareTo(obj2); } //----------------------------------------------------------------------- /** * Implement a hash code for this comparator that is consistent with * {@link #equals(Object) equals}. * * @return a hash code for this comparator. * @since 3.0 */ @Override public int hashCode() { return "ComparableComparator".hashCode(); } /** * Returns {@code true} iff that Object is is a {@link Comparator Comparator} * whose ordering is known to be equivalent to mine. *

* This implementation returns {@code 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 {@code true} if equal * @since 3.0 */ @Override public boolean equals(final Object object) { return this == object || null != object && object.getClass().equals(this.getClass()); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/SetUtils.java100664 31201 12243235517 27373 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Collection; import java.util.Collections; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.collections4.set.ListOrderedSet; import org.apache.commons.collections4.set.PredicatedSet; import org.apache.commons.collections4.set.PredicatedSortedSet; import org.apache.commons.collections4.set.TransformedSet; import org.apache.commons.collections4.set.TransformedSortedSet; import org.apache.commons.collections4.set.UnmodifiableSet; import org.apache.commons.collections4.set.UnmodifiableSortedSet; /** * Provides utility methods and decorators for * {@link Set} and {@link SortedSet} instances. * * @since 2.1 * @version $Id: SetUtils.java 1543964 2013-11-20 21:53:39Z tn $ */ public class SetUtils { /** * Get a typed empty unmodifiable Set. * @param the element type * @return an empty Set */ public static Set emptySet() { return Collections.emptySet(); } /** * An empty unmodifiable sorted set. * This is not provided in the JDK. */ @SuppressWarnings("rawtypes") public static final SortedSet EMPTY_SORTED_SET = UnmodifiableSortedSet.unmodifiableSortedSet(new TreeSet()); /** * Get a typed empty unmodifiable sorted set. * @param the element type * @return an empty sorted Set */ @SuppressWarnings("unchecked") // empty set is OK for any type public static SortedSet emptySortedSet() { return (SortedSet) EMPTY_SORTED_SET; } /** * SetUtils should not normally be instantiated. */ private SetUtils() {} //----------------------------------------------------------------------- /** * Returns an immutable empty set if the argument is null, * or the argument itself otherwise. * * @param the element type * @param set the set, possibly null * @return an empty set if the argument is null */ public static Set emptyIfNull(final Set set) { return set == null ? Collections.emptySet() : set; } /** * 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. * * @param the element type * @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; for (final T obj : set) { if (obj != null) { hashCode += obj.hashCode(); } } return hashCode; } //----------------------------------------------------------------------- /** * Returns a synchronized set backed by the given set. *

* You must manually synchronize on the returned set'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 is just a wrapper for {@link Collections#synchronizedSet(Set)}. * * @param the element type * @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(final Set set) { return Collections.synchronizedSet(set); } /** * Returns an unmodifiable set backed by the given set. *

* This method uses the implementation in the decorators subpackage. * * @param the element type * @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(final Set set) { return UnmodifiableSet.unmodifiableSet(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 the element type * @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(final Set set, final Predicate predicate) { return PredicatedSet.predicatedSet(set, predicate); } /** * 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. *

* Existing entries in the specified set will not be transformed. * If you want that behaviour, see {@link TransformedSet#transformedSet}. * * @param the element type * @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(final Set set, final Transformer transformer) { return TransformedSet.transformingSet(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 the element type * @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(final Set set) { return ListOrderedSet.listOrderedSet(set); } //----------------------------------------------------------------------- /** * Returns a synchronized sorted set backed by the given sorted set. *

* You must manually synchronize on the returned set'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 is just a wrapper for {@link Collections#synchronizedSortedSet(SortedSet)}. * * @param the element type * @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(final SortedSet set) { return Collections.synchronizedSortedSet(set); } /** * Returns an unmodifiable sorted set backed by the given sorted set. *

* This method uses the implementation in the decorators subpackage. * * @param the element type * @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(final SortedSet set) { return UnmodifiableSortedSet.unmodifiableSortedSet(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 the element type * @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(final SortedSet set, final Predicate predicate) { return PredicatedSortedSet.predicatedSortedSet(set, predicate); } /** * 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. *

* Existing entries in the specified set will not be transformed. * If you want that behaviour, see {@link TransformedSortedSet#transformedSortedSet}. * * @param the element type * @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(final SortedSet set, final Transformer transformer) { return TransformedSortedSet.transformingSortedSet(set, transformer); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/ComparatorUtils.java100664 22613 12243235516 30755 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Collection; import java.util.Comparator; import org.apache.commons.collections4.comparators.BooleanComparator; import org.apache.commons.collections4.comparators.ComparableComparator; import org.apache.commons.collections4.comparators.ComparatorChain; import org.apache.commons.collections4.comparators.NullComparator; import org.apache.commons.collections4.comparators.ReverseComparator; import org.apache.commons.collections4.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 2.1 * @version $Id: ComparatorUtils.java 1543971 2013-11-20 22:16:05Z tn $ */ public class ComparatorUtils { /** * ComparatorUtils should not normally be instantiated. */ private ComparatorUtils() {} /** * Comparator for natural sort order. * * @see ComparableComparator#comparableComparator() */ @SuppressWarnings({ "rawtypes", "unchecked" }) // explicit type needed for Java 1.5 compilation public static final Comparator NATURAL_COMPARATOR = ComparableComparator.comparableComparator(); /** * Gets a comparator that uses the natural order of the objects. * * @param the object type to compare * @return a comparator which uses natural order */ @SuppressWarnings("unchecked") public static > Comparator naturalComparator() { return NATURAL_COMPARATOR; } /** * 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 the object type to compare * @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( final Comparator... comparators) { final ComparatorChain chain = new ComparatorChain(); for (final Comparator comparator : comparators) { if (comparator == null) { throw new NullPointerException("Comparator cannot be null"); } chain.addComparator(comparator); } 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 the object type to compare * @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 */ @SuppressWarnings("unchecked") public static > Comparator chainedComparator( final Collection> comparators) { return chainedComparator( (Comparator[]) comparators.toArray(new Comparator[comparators.size()]) ); } /** * Gets a comparator that reverses the order of the given comparator. * * @param the object type to compare * @param comparator the comparator to reverse * @return a comparator that reverses the order of the input comparator * @see ReverseComparator */ public static Comparator reversedComparator(final Comparator 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(final boolean trueFirst) { return BooleanComparator.booleanComparator(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 the object type to compare * @param comparator the comparator that wants to allow nulls * @return a version of that comparator that allows nulls * @see NullComparator */ @SuppressWarnings("unchecked") 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 the object type to compare * @param comparator the comparator that wants to allow nulls * @return a version of that comparator that allows nulls * @see NullComparator */ @SuppressWarnings("unchecked") 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 the input object type of the transformed comparator * @param the object type of the decorated 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 */ @SuppressWarnings("unchecked") public static Comparator transformedComparator(Comparator comparator, final 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 the object type to compare * @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 */ @SuppressWarnings("unchecked") public static E min(final E o1, final E o2, Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } final 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 the object type to compare * @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 */ @SuppressWarnings("unchecked") public static E max(final E o1, final E o2, Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } final int c = comparator.compare(o1, o2); return c > 0 ? o1 : o2; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/package-info.java100664 2314 12243235517 30126 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This 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 {@code java.util Stack} *
* * @version $Id: package-info.java 1469004 2013-04-17 17:37:03Z tn $ */ package org.apache.commons.collections4; ././@LongLink100644 0 0 171 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/splitmap/AbstractIterableGetMapDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/splitmap/AbstractIterable100664 6447 12243235516 31740 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.splitmap; import java.util.Collection; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.IterableGet; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.map.EntrySetToMapIteratorAdapter; /** * {@link IterableGet} that uses a {@link Map} for the * {@link org.apache.commons.collections4.Get Get} implementation. * * @since 4.0 * @version $Id: AbstractIterableGetMapDecorator.java 1494296 2013-06-18 20:54:29Z tn $ */ public class AbstractIterableGetMapDecorator implements IterableGet { /** The map to decorate */ transient Map map; /** * Create a new AbstractSplitMapDecorator. * @param decorated the Map to decorate */ public AbstractIterableGetMapDecorator(final Map decorated) { this.map = decorated; } /** * Constructor only used in deserialization, do not use otherwise. */ protected AbstractIterableGetMapDecorator() { super(); } /** * Gets the map being decorated. * * @return the decorated map */ protected Map decorated() { return map; } public boolean containsKey(final Object key) { return decorated().containsKey(key); } public boolean containsValue(final Object value) { return decorated().containsValue(value); } public Set> entrySet() { return decorated().entrySet(); } public V get(final Object key) { return decorated().get(key); } public V remove(final Object key) { return decorated().remove(key); } public boolean isEmpty() { return decorated().isEmpty(); } public Set keySet() { return decorated().keySet(); } public int size() { return decorated().size(); } public Collection values() { return decorated().values(); } /** * Get a MapIterator over this Get. * @return MapIterator */ public MapIterator mapIterator() { return new EntrySetToMapIteratorAdapter(entrySet()); } @Override public boolean equals(final Object object) { if (object == this) { return true; } return decorated().equals(object); } @Override public int hashCode() { return decorated().hashCode(); } @Override public String toString() { return decorated().toString(); } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/splitmap/TransformedSplitMap.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/splitmap/TransformedSplit100664 20435 12243235516 32036 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.splitmap; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Map; import org.apache.commons.collections4.Put; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.map.LinkedMap; /** * Decorates another {@link 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. *

* The "put" and "get" type constraints of this class are mutually independent; * contrast with {@link org.apache.commons.collections4.map.TransformedMap} which, * by virtue of its implementing {@link Map}<K, V>, must be constructed in such * a way that its read and write parameters are generalized to a common (super-)type. * In practice this would often mean >Object, Object>, defeating * much of the usefulness of having parameterized types. *

* On the downside, this class is not drop-in compatible with {@link java.util.Map} * but is intended to be worked with either directly or by {@link Put} and * {@link org.apache.commons.collections4.Get Get} generalizations. * * @since 4.0 * @version $Id: TransformedSplitMap.java 1491944 2013-06-11 20:29:22Z tn $ * * @see org.apache.commons.collections4.SplitMapUtils#readableMap(Get) * @see org.apache.commons.collections4.SplitMapUtils#writableMap(Put) */ public class TransformedSplitMap extends AbstractIterableGetMapDecorator implements Put, Serializable { /** Serialization version */ private static final long serialVersionUID = 5966875321133456994L; /** The transformer to use for the key */ private final Transformer keyTransformer; /** The transformer to use for the value */ private final Transformer valueTransformer; /** * Factory method to create a transforming map. *

* If there are any elements already in the map being decorated, they are * NOT transformed. * * @param the input key type * @param the output key type * @param the input value type * @param the output value type * @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 * @return a new transformed map * @throws IllegalArgumentException if map is null */ public static TransformedSplitMap transformingMap(final Map map, final Transformer keyTransformer, final Transformer valueTransformer) { return new TransformedSplitMap(map, keyTransformer, valueTransformer); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

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

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

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

* The transformer itself may throw an exception if necessary. * * @param map the map to transform * @return the transformed object */ @SuppressWarnings("unchecked") protected Map transformMap(final Map map) { if (map.isEmpty()) { return (Map) map; } final Map result = new LinkedMap(map.size()); for (final Map.Entry entry : map.entrySet()) { 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 */ protected V checkSetValue(final U value) { return valueTransformer.transform(value); } //----------------------------------------------------------------------- public V put(final J key, final U value) { return decorated().put(transformKey(key), transformValue(value)); } public void putAll(final Map mapToCopy) { decorated().putAll(transformMap(mapToCopy)); } public void clear() { decorated().clear(); } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/splitmap/package-info.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/splitmap/package-info.jav100664 3472 12243235516 31623 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The "split map" concept is that of an object that implements * the {@link org.apache.commons.collections4.Put Put} and * {@link org.apache.commons.collections4.Get Get} interfaces, * with differing generic types. This is like a pre-generics * {@link java.util.Map Map} whose input key/value constraints are * different than its output key/value constraints. While it would * be possible to declare a "split map" with matching input/output * key/value constraints, this would be a {@link java.util.Map Map} * and would therefore make little sense (any Commons Collections * {@link java.util.Map Map} implementation will also implement * {@link org.apache.commons.collections4.Put Put} and * {@link org.apache.commons.collections4.Get Get} with matching * generic parameters). *

* The following decorators are provided: *

    *
  • Transformed - transforms each element added *
* * @version $Id: package-info.java 1469004 2013-04-17 17:37:03Z tn $ */ package org.apache.commons.collections4.splitmap; ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/TransformedQueue.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/TransformedQueue.ja100664 11774 12243235516 31721 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.queue; import java.util.Queue; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.collection.TransformedCollection; /** * Decorates another {@link Queue} to transform objects that are added. *

* The add/offer 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. * * @since 4.0 * @version $Id: TransformedQueue.java 1494280 2013-06-18 20:07:04Z tn $ */ public class TransformedQueue extends TransformedCollection implements Queue { /** Serialization version */ private static final long serialVersionUID = -7901091318986132033L; /** * Factory method to create a transforming queue. *

* If there are any elements already in the queue being decorated, they * are NOT transformed. * Contrast this with {@link #transformedQueue(Queue, Transformer)}. * * @param the type of the elements in the queue * @param queue the queue to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed Queue * @throws IllegalArgumentException if queue or transformer is null */ public static TransformedQueue transformingQueue(final Queue queue, final Transformer transformer) { return new TransformedQueue(queue, transformer); } /** * Factory method to create a transforming queue that will transform * existing contents of the specified queue. *

* If there are any elements already in the queue being decorated, they * will be transformed by this method. * Contrast this with {@link #transformingQueue(Queue, Transformer)}. * * @param the type of the elements in the queue * @param queue the queue to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed Queue * @throws IllegalArgumentException if queue or transformer is null * @since 4.0 */ public static TransformedQueue transformedQueue(final Queue queue, final Transformer transformer) { // throws IAE if queue or transformer is null final TransformedQueue decorated = new TransformedQueue(queue, transformer); if (queue.size() > 0) { @SuppressWarnings("unchecked") // queue is type final E[] values = (E[]) queue.toArray(); // NOPMD - false positive for generics queue.clear(); for (final E value : values) { decorated.decorated().add(transformer.transform(value)); } } return decorated; } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). *

* If there are any elements already in the queue being decorated, they * are NOT transformed. * * @param queue the queue to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @throws IllegalArgumentException if queue or transformer is null */ protected TransformedQueue(final Queue queue, final Transformer transformer) { super(queue, transformer); } /** * Gets the decorated queue. * * @return the decorated queue */ protected Queue getQueue() { return (Queue) decorated(); } //----------------------------------------------------------------------- public boolean offer(final E obj) { return getQueue().offer(transform(obj)); } public E poll() { return getQueue().poll(); } public E peek() { return getQueue().peek(); } public E element() { return getQueue().element(); } public E remove() { return getQueue().remove(); } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/AbstractQueueDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/AbstractQueueDecora100664 4740 12243235516 31700 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.queue; import java.util.Queue; import org.apache.commons.collections4.collection.AbstractCollectionDecorator; /** * Decorates another {@link Queue} to provide additional behaviour. *

* Methods are forwarded directly to the decorated queue. * * @param the type of the elements in the queue * @since 4.0 * @version $Id: AbstractQueueDecorator.java 1477765 2013-04-30 18:37:37Z tn $ */ public abstract class AbstractQueueDecorator extends AbstractCollectionDecorator implements Queue { /** Serialization version */ private static final long serialVersionUID = -2629815475789577029L; /** * Constructor only used in deserialization, do not use otherwise. */ protected AbstractQueueDecorator() { super(); } /** * Constructor that wraps (not copies). * * @param queue the queue to decorate, must not be null * @throws IllegalArgumentException if list is null */ protected AbstractQueueDecorator(final Queue queue) { super(queue); } /** * Gets the queue being decorated. * * @return the decorated queue */ @Override protected Queue decorated() { return (Queue) super.decorated(); } //----------------------------------------------------------------------- public boolean offer(final E obj) { return decorated().offer(obj); } public E poll() { return decorated().poll(); } public E peek() { return decorated().peek(); } public E element() { return decorated().element(); } public E remove() { return decorated().remove(); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/package-info.java100664 2751 12243235516 31256 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains implementations for the {@link java.util.Queue Queue} interface. *

* The following implementations are provided in the package: *

    *
  • CircularFifoQueue - implements a queue with a fixed size that discards oldest when full *
*

* The following decorators are provided in the package: *

    *
  • Predicated - ensures that only elements that are valid according to a predicate can be added *
  • Transformed - transforms elements added to the queue *
  • Unmodifiable - ensures the collection cannot be altered *
* * @version $Id: package-info.java 1477765 2013-04-30 18:37:37Z tn $ */ package org.apache.commons.collections4.queue; ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/PredicatedQueue.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/PredicatedQueue.jav100664 10224 12243235516 31654 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.queue; import java.util.Queue; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.collection.PredicatedCollection; /** * Decorates another {@link Queue} to validate that additions * match a specified predicate. *

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

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

Queue queue = PredicatedQueue.predicatedQueue(new UnboundedFifoQueue(), NotNullPredicate.INSTANCE);
* * @since 4.0 * @version $Id: PredicatedQueue.java 1477765 2013-04-30 18:37:37Z tn $ */ public class PredicatedQueue extends PredicatedCollection implements Queue { /** Serialization version */ private static final long serialVersionUID = 2307609000539943581L; /** * Factory method to create a predicated (validating) queue. *

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

* If there are any elements already in the collection being decorated, they * are validated. * * @param queue the queue to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @throws IllegalArgumentException if Queue or predicate is null * @throws IllegalArgumentException if the Queue contains invalid elements */ protected PredicatedQueue(final Queue queue, final Predicate predicate) { super(queue, predicate); } /** * Gets the queue being decorated. * * @return the decorated queue */ @Override protected Queue decorated() { return (Queue) super.decorated(); } //----------------------------------------------------------------------- /** * 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 queue * @throws IllegalArgumentException if the add is invalid */ public boolean offer(final E object) { validate(object); return decorated().offer(object); } public E poll() { return decorated().poll(); } public E peek() { return decorated().peek(); } public E element() { return decorated().element(); } public E remove() { return decorated().remove(); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/UnmodifiableQueue.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/UnmodifiableQueue.j100664 11667 12243235516 31673 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.queue; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.Iterator; import java.util.Queue; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableIterator; /** * Decorates another {@link Queue} to ensure it can't be altered. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 4.0 * @version $Id: UnmodifiableQueue.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class UnmodifiableQueue extends AbstractQueueDecorator implements Unmodifiable { /** Serialization version */ private static final long serialVersionUID = 1832948656215393357L; /** * Factory method to create an unmodifiable queue. *

* If the queue passed in is already unmodifiable, it is returned. * * @param the type of the elements in the queue * @param queue the queue to decorate, must not be null * @return an unmodifiable Queue * @throws IllegalArgumentException if queue is null */ public static Queue unmodifiableQueue(final Queue queue) { if (queue instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final Queue tmpQueue = (Queue) queue; return tmpQueue; } return new UnmodifiableQueue(queue); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param queue the queue to decorate, must not be null * @throws IllegalArgumentException if queue is null */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableQueue(final Queue queue) { super((Queue) queue); } //----------------------------------------------------------------------- /** * Write the collection out using a custom routine. * * @param out the output stream * @throws IOException if an I/O error occurs while writing to the output stream */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(decorated()); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException if an I/O error occurs while reading from the input stream * @throws ClassNotFoundException if the class of a serialized object can not be found */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); setCollection((Collection) in.readObject()); } //----------------------------------------------------------------------- @Override public Iterator iterator() { return UnmodifiableIterator.unmodifiableIterator(decorated().iterator()); } @Override public boolean add(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean addAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- @Override public boolean offer(final E obj) { throw new UnsupportedOperationException(); } @Override public E poll() { throw new UnsupportedOperationException(); } @Override public E remove() { throw new UnsupportedOperationException(); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/CircularFifoQueue.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/queue/CircularFifoQueue.j100664 27720 12243235516 31642 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.queue; 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 java.util.Queue; import org.apache.commons.collections4.BoundedCollection; /** * CircularFifoQueue is a first-in first-out queue with a fixed size that * replaces its oldest element if full. *

* The removal order of a {@link CircularFifoQueue} 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()}, {@link #peek()}, {@link #poll}, * {@link #offer(Object)} operations all perform in constant time. * All other operations perform in linear time or worse. *

* This queue prevents null objects from being added. * * @since 4.0 * @version $Id: CircularFifoQueue.java 1543246 2013-11-19 00:36:29Z ggregory $ */ public class CircularFifoQueue extends AbstractCollection implements Queue, BoundedCollection, Serializable { /** Serialization version. */ private static final long serialVersionUID = -8423413834657610406L; /** Underlying storage array. */ private transient E[] elements; /** Array index of first (oldest) queue element. */ private transient int start = 0; /** * Index mod maxElements of the array position following the last queue * element. Queue 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 queue [a,b,c]. */ private transient int end = 0; /** Flag to indicate if the queue is currently full. */ private transient boolean full = false; /** Capacity of the queue. */ private final int maxElements; /** * Constructor that creates a queue with the default size of 32. */ public CircularFifoQueue() { this(32); } /** * Constructor that creates a queue with the specified size. * * @param size the size of the queue (cannot be changed) * @throws IllegalArgumentException if the size is < 1 */ @SuppressWarnings("unchecked") public CircularFifoQueue(final int size) { if (size <= 0) { throw new IllegalArgumentException("The size must be greater than 0"); } elements = (E[]) new Object[size]; maxElements = elements.length; } /** * Constructor that creates a queue from the specified collection. * The collection size also sets the queue size. * * @param coll the collection to copy into the queue, may not be null * @throws NullPointerException if the collection is null */ public CircularFifoQueue(final Collection coll) { this(coll.size()); addAll(coll); } //----------------------------------------------------------------------- /** * Write the queue out using a custom routine. * * @param out the output stream * @throws IOException if an I/O error occurs while writing to the output stream */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(size()); for (final E e : this) { out.writeObject(e); } } /** * Read the queue in using a custom routine. * * @param in the input stream * @throws IOException if an I/O error occurs while writing to the output stream * @throws ClassNotFoundException if the class of a serialized object can not be found */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); elements = (E[]) new Object[maxElements]; final int size = in.readInt(); for (int i = 0; i < size; i++) { elements[i] = (E) in.readObject(); } start = 0; full = size == maxElements; if (full) { end = 0; } else { end = size; } } //----------------------------------------------------------------------- /** * Returns the number of elements stored in the queue. * * @return this queue's size */ @Override 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 queue is empty; false otherwise. * * @return true if this queue is empty */ @Override public boolean isEmpty() { return size() == 0; } /** * {@inheritDoc} *

* A {@code CircularFifoQueue} can never be full, thus this returns always * {@code false}. * * @return always returns {@code false} */ public boolean isFull() { return false; } private boolean isAtFullCapacity() { 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 queue. */ @Override public void clear() { full = false; start = 0; end = 0; Arrays.fill(elements, null); } /** * Adds the given element to this queue. If the queue 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 * @throws NullPointerException if the given element is null */ @Override public boolean add(final E element) { if (null == element) { throw new NullPointerException("Attempted to add null object to queue"); } if (isAtFullCapacity()) { remove(); } elements[end++] = element; if (end >= maxElements) { end = 0; } if (end == start) { full = true; } return true; } /** * Returns the element at the specified position in this queue. * * @param index the position of the element in the queue * @return the element at position {@code index} * @throws NoSuchElementException if the requested position is outside the range [0, size) */ public E get(final int index) { final int sz = size(); if (index < 0 || index >= sz) { throw new NoSuchElementException( String.format("The specified index (%1$d) is outside the available range [0, %2$d)", Integer.valueOf(index), Integer.valueOf(sz))); } final int idx = (start + index) % maxElements; return elements[idx]; } //----------------------------------------------------------------------- /** * Adds the given element to this queue. If the queue 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 * @throws NullPointerException if the given element is null */ public boolean offer(E element) { return add(element); } public E poll() { if (isEmpty()) { return null; } return remove(); } public E element() { if (isEmpty()) { throw new NoSuchElementException("queue is empty"); } return peek(); } public E peek() { if (isEmpty()) { return null; } return elements[start]; } public E remove() { if (isEmpty()) { throw new NoSuchElementException("queue is empty"); } final E element = elements[start]; if (null != element) { elements[start++] = null; if (start >= maxElements) { start = 0; } full = false; } return element; } //----------------------------------------------------------------------- /** * Increments the internal index. * * @param index the index to increment * @return the updated index */ private int increment(int index) { index++; if (index >= maxElements) { index = 0; } return index; } /** * Decrements the internal index. * * @param index the index to decrement * @return the updated index */ private int decrement(int index) { index--; if (index < 0) { index = maxElements - 1; } return index; } /** * Returns an iterator over this queue's elements. * * @return an iterator over this queue's elements */ @Override public Iterator iterator() { return new Iterator() { private int index = start; private int lastReturnedIndex = -1; private boolean isFirst = full; public boolean hasNext() { return isFirst || index != end; } public E next() { if (!hasNext()) { throw new NoSuchElementException(); } isFirst = false; lastReturnedIndex = index; index = increment(index); return elements[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) { throw new IllegalStateException(); } // First element can be removed quickly if (lastReturnedIndex == start) { CircularFifoQueue.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); } }; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/EditScript.java100664 10423 12243235516 31503 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.sequence; import java.util.ArrayList; import java.util.List; /** * This class gathers all the {@link EditCommand commands} needed to transform * one objects sequence into another objects sequence. *

* An edit script is the most general view of the differences between two * sequences. It is built as the result of the comparison between two sequences * by the {@link SequencesComparator SequencesComparator} class. The user can * walk through it using the visitor design pattern. *

* It is guaranteed that the objects embedded in the {@link InsertCommand insert * commands} come from the second sequence and that the objects embedded in * either the {@link DeleteCommand delete commands} or {@link KeepCommand keep * commands} come from the first sequence. This can be important if subclassing * is used for some elements in the first sequence and the equals * method is specialized. * * @see SequencesComparator * @see EditCommand * @see CommandVisitor * @see ReplacementsHandler * * @since 4.0 * @version $Id: EditScript.java 1477760 2013-04-30 18:34:03Z tn $ */ public class EditScript { /** Container for the commands. */ private final List> commands; /** Length of the longest common subsequence. */ private int lcsLength; /** Number of modifications. */ private int modifications; /** * Simple constructor. Creates a new empty script. */ public EditScript() { commands = new ArrayList>(); lcsLength = 0; modifications = 0; } /** * Add a keep command to the script. * * @param command command to add */ public void append(final KeepCommand command) { commands.add(command); ++lcsLength; } /** * Add an insert command to the script. * * @param command command to add */ public void append(final InsertCommand command) { commands.add(command); ++modifications; } /** * Add a delete command to the script. * * @param command command to add */ public void append(final DeleteCommand command) { commands.add(command); ++modifications; } /** * Visit the script. The script implements the visitor design * pattern, this method is the entry point to which the user supplies its * own visitor, the script will be responsible to drive it through the * commands in order and call the appropriate method as each command is * encountered. * * @param visitor the visitor that will visit all commands in turn */ public void visit(final CommandVisitor visitor) { for (final EditCommand command : commands) { command.accept(visitor); } } /** * Get the length of the Longest Common Subsequence (LCS). The length of the * longest common subsequence is the number of {@link KeepCommand keep * commands} in the script. * * @return length of the Longest Common Subsequence */ public int getLCSLength() { return lcsLength; } /** * Get the number of effective modifications. The number of effective * modification is the number of {@link DeleteCommand delete} and * {@link InsertCommand insert} commands in the script. * * @return number of effective modifications */ public int getModifications() { return modifications; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/ReplacementsFinder.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/ReplacementsFind100664 10103 12243235516 31727 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.sequence; import java.util.ArrayList; import java.util.List; /** * This class handles sequences of replacements resulting from a comparison. *

* The comparison of two objects sequences leads to the identification of common * parts and parts which only belong to the first or to the second sequence. The * common parts appear in the edit script in the form of keep commands, * they can be considered as synchronization objects between the two sequences. * These synchronization objects split the two sequences in synchronized * sub-sequences. The first sequence can be transformed into the second one by * replacing each synchronized sub-sequence of the first sequence by the * corresponding sub-sequence of the second sequence. This is a synthetic way to * see an {@link EditScript edit script}, replacing individual * {@link DeleteCommand delete}, {@link KeepCommand keep} and * {@link InsertCommand insert} commands by fewer replacements acting on * complete sub-sequences. *

* This class is devoted to perform this interpretation. It visits an * {@link EditScript edit script} (because it implements the * {@link CommandVisitor CommandVisitor} interface) and calls a user-supplied * handler implementing the {@link ReplacementsHandler ReplacementsHandler} * interface to process the sub-sequences. * * @see ReplacementsHandler * @see EditScript * @see SequencesComparator * * @since 4.0 * @version $Id: ReplacementsFinder.java 1477760 2013-04-30 18:34:03Z tn $ */ public class ReplacementsFinder implements CommandVisitor { private final List pendingInsertions; private final List pendingDeletions; private int skipped; /** Handler to call when synchronized sequences are found. */ private final ReplacementsHandler handler; /** * Simple constructor. Creates a new instance of {@link ReplacementsFinder}. * * @param handler handler to call when synchronized sequences are found */ public ReplacementsFinder(final ReplacementsHandler handler) { pendingInsertions = new ArrayList(); pendingDeletions = new ArrayList(); skipped = 0; this.handler = handler; } /** * Add an object to the pending insertions set. * * @param object object to insert */ public void visitInsertCommand(final T object) { pendingInsertions.add(object); } /** * Handle a synchronization object. *

* When a synchronization object is identified, the pending insertions and * pending deletions sets are provided to the user handler as subsequences. * * @param object synchronization object detected */ public void visitKeepCommand(final T object) { if (pendingDeletions.isEmpty() && pendingInsertions.isEmpty()) { ++skipped; } else { handler.handleReplacement(skipped, pendingDeletions, pendingInsertions); pendingDeletions.clear(); pendingInsertions.clear(); skipped = 1; } } /** * Add an object to the pending deletions set. * * @param object object to delete */ public void visitDeleteCommand(final T object) { pendingDeletions.add(object); } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/DeleteCommand.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/DeleteCommand.ja100664 4120 12243235516 31560 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.sequence; /** * Command representing the deletion of one object of the first sequence. *

* When one object of the first sequence has no corresponding object in the * second sequence at the right place, the {@link EditScript edit script} * transforming the first sequence into the second sequence uses an instance of * this class to represent the deletion of this object. The objects embedded in * these type of commands always come from the first sequence. * * @see SequencesComparator * @see EditScript * * @since 4.0 * @version $Id: DeleteCommand.java 1477760 2013-04-30 18:34:03Z tn $ */ public class DeleteCommand extends EditCommand { /** * Simple constructor. Creates a new instance of {@link DeleteCommand}. * * @param object the object of the first sequence that should be deleted */ public DeleteCommand(final T object) { super(object); } /** * Accept a visitor. When a DeleteCommand accepts a visitor, it calls * its {@link CommandVisitor#visitDeleteCommand visitDeleteCommand} method. * * @param visitor the visitor to be accepted */ @Override public void accept(final CommandVisitor visitor) { visitor.visitDeleteCommand(getObject()); } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/InsertCommand.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/InsertCommand.ja100664 4126 12243235516 31630 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.sequence; /** * Command representing the insertion of one object of the second sequence. *

* When one object of the second sequence has no corresponding object in the * first sequence at the right place, the {@link EditScript edit script} * transforming the first sequence into the second sequence uses an instance of * this class to represent the insertion of this object. The objects embedded in * these type of commands always come from the second sequence. * * @see SequencesComparator * @see EditScript * * @since 4.0 * @version $Id: InsertCommand.java 1477760 2013-04-30 18:34:03Z tn $ */ public class InsertCommand extends EditCommand { /** * Simple constructor. Creates a new instance of InsertCommand * * @param object the object of the second sequence that should be inserted */ public InsertCommand(final T object) { super(object); } /** * Accept a visitor. When an InsertCommand accepts a visitor, * it calls its {@link CommandVisitor#visitInsertCommand visitInsertCommand} * method. * * @param visitor the visitor to be accepted */ @Override public void accept(final CommandVisitor visitor) { visitor.visitInsertCommand(getObject()); } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/SequencesComparator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/SequencesCompara100664 31136 12243235516 31753 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.sequence; import java.util.List; import org.apache.commons.collections4.Equator; import org.apache.commons.collections4.functors.DefaultEquator; /** * This class allows to compare two objects sequences. *

* The two sequences can hold any object type, as only the equals * method is used to compare the elements of the sequences. It is guaranteed * that the comparisons will always be done as o1.equals(o2) where * o1 belongs to the first sequence and o2 belongs to * the second sequence. This can be important if subclassing is used for some * elements in the first sequence and the equals method is * specialized. *

* Comparison can be seen from two points of view: either as giving the smallest * modification allowing to transform the first sequence into the second one, or * as giving the longest sequence which is a subsequence of both initial * sequences. The equals method is used to compare objects, so any * object can be put into sequences. Modifications include deleting, inserting * or keeping one object, starting from the beginning of the first sequence. *

* This class implements the comparison algorithm, which is the very efficient * algorithm from Eugene W. Myers * * An O(ND) Difference Algorithm and Its Variations. This algorithm produces * the shortest possible * {@link EditScript edit script} * containing all the * {@link EditCommand commands} * needed to transform the first sequence into the second one. * * @see EditScript * @see EditCommand * @see CommandVisitor * * @since 4.0 * @version $Id: SequencesComparator.java 1540567 2013-11-10 22:19:29Z tn $ */ public class SequencesComparator { /** First sequence. */ private final List sequence1; /** Second sequence. */ private final List sequence2; /** The equator used for testing object equality. */ private final Equator equator; /** Temporary variables. */ private final int[] vDown; private final int[] vUp; /** * Simple constructor. *

* Creates a new instance of SequencesComparator using a {@link DefaultEquator}. *

* It is guaranteed that the comparisons will always be done as * o1.equals(o2) where o1 belongs to the first * sequence and o2 belongs to the second sequence. This can be * important if subclassing is used for some elements in the first sequence * and the equals method is specialized. * * @param sequence1 first sequence to be compared * @param sequence2 second sequence to be compared */ public SequencesComparator(final List sequence1, final List sequence2) { this(sequence1, sequence2, DefaultEquator.defaultEquator()); } /** * Simple constructor. *

* Creates a new instance of SequencesComparator with a custom {@link Equator}. *

* It is guaranteed that the comparisons will always be done as * Equator.equate(o1, o2) where o1 belongs to the first * sequence and o2 belongs to the second sequence. * * @param sequence1 first sequence to be compared * @param sequence2 second sequence to be compared * @param equator the equator to use for testing object equality */ public SequencesComparator(final List sequence1, final List sequence2, final Equator equator) { this.sequence1 = sequence1; this.sequence2 = sequence2; this.equator = equator; final int size = sequence1.size() + sequence2.size() + 2; vDown = new int[size]; vUp = new int[size]; } /** * Get the {@link EditScript} object. *

* It is guaranteed that the objects embedded in the {@link InsertCommand * insert commands} come from the second sequence and that the objects * embedded in either the {@link DeleteCommand delete commands} or * {@link KeepCommand keep commands} come from the first sequence. This can * be important if subclassing is used for some elements in the first * sequence and the equals method is specialized. * * @return the edit script resulting from the comparison of the two * sequences */ public EditScript getScript() { final EditScript script = new EditScript(); buildScript(0, sequence1.size(), 0, sequence2.size(), script); return script; } /** * Build a snake. * * @param start the value of the start of the snake * @param diag the value of the diagonal of the snake * @param end1 the value of the end of the first sequence to be compared * @param end2 the value of the end of the second sequence to be compared * @return the snake built */ private Snake buildSnake(final int start, final int diag, final int end1, final int end2) { int end = start; while (end - diag < end2 && end < end1 && equator.equate(sequence1.get(end), sequence2.get(end - diag))) { ++end; } return new Snake(start, end, diag); } /** * Get the middle snake corresponding to two subsequences of the * main sequences. *

* The snake is found using the MYERS Algorithm (this algorithms has * also been implemented in the GNU diff program). This algorithm is * explained in Eugene Myers article: * * An O(ND) Difference Algorithm and Its Variations. * * @param start1 the begin of the first sequence to be compared * @param end1 the end of the first sequence to be compared * @param start2 the begin of the second sequence to be compared * @param end2 the end of the second sequence to be compared * @return the middle snake */ private Snake getMiddleSnake(final int start1, final int end1, final int start2, final int end2) { // Myers Algorithm // Initialisations final int m = end1 - start1; final int n = end2 - start2; if (m == 0 || n == 0) { return null; } final int delta = m - n; final int sum = n + m; final int offset = (sum % 2 == 0 ? sum : sum + 1) / 2; vDown[1+offset] = start1; vUp[1+offset] = end1 + 1; for (int d = 0; d <= offset ; ++d) { // Down for (int k = -d; k <= d; k += 2) { // First step final int i = k + offset; if (k == -d || k != d && vDown[i-1] < vDown[i+1]) { vDown[i] = vDown[i+1]; } else { vDown[i] = vDown[i-1] + 1; } int x = vDown[i]; int y = x - start1 + start2 - k; while (x < end1 && y < end2 && equator.equate(sequence1.get(x), sequence2.get(y))) { vDown[i] = ++x; ++y; } // Second step if (delta % 2 != 0 && delta - d <= k && k <= delta + d) { if (vUp[i-delta] <= vDown[i]) { return buildSnake(vUp[i-delta], k + start1 - start2, end1, end2); } } } // Up for (int k = delta - d; k <= delta + d; k += 2) { // First step final int i = k + offset - delta; if (k == delta - d || k != delta + d && vUp[i+1] <= vUp[i-1]) { vUp[i] = vUp[i+1] - 1; } else { vUp[i] = vUp[i-1]; } int x = vUp[i] - 1; int y = x - start1 + start2 - k; while (x >= start1 && y >= start2 && equator.equate(sequence1.get(x), sequence2.get(y))) { vUp[i] = x--; y--; } // Second step if (delta % 2 == 0 && -d <= k && k <= d ) { if (vUp[i] <= vDown[i + delta]) { return buildSnake(vUp[i], k + start1 - start2, end1, end2); } } } } // this should not happen throw new RuntimeException("Internal Error"); } /** * Build an edit script. * * @param start1 the begin of the first sequence to be compared * @param end1 the end of the first sequence to be compared * @param start2 the begin of the second sequence to be compared * @param end2 the end of the second sequence to be compared * @param script the edited script */ private void buildScript(final int start1, final int end1, final int start2, final int end2, final EditScript script) { final Snake middle = getMiddleSnake(start1, end1, start2, end2); if (middle == null || middle.getStart() == end1 && middle.getDiag() == end1 - end2 || middle.getEnd() == start1 && middle.getDiag() == start1 - start2) { int i = start1; int j = start2; while (i < end1 || j < end2) { if (i < end1 && j < end2 && equator.equate(sequence1.get(i), sequence2.get(j))) { script.append(new KeepCommand(sequence1.get(i))); ++i; ++j; } else { if (end1 - start1 > end2 - start2) { script.append(new DeleteCommand(sequence1.get(i))); ++i; } else { script.append(new InsertCommand(sequence2.get(j))); ++j; } } } } else { buildScript(start1, middle.getStart(), start2, middle.getStart() - middle.getDiag(), script); for (int i = middle.getStart(); i < middle.getEnd(); ++i) { script.append(new KeepCommand(sequence1.get(i))); } buildScript(middle.getEnd(), end1, middle.getEnd() - middle.getDiag(), end2, script); } } /** * This class is a simple placeholder to hold the end part of a path * under construction in a {@link SequencesComparator SequencesComparator}. */ private static class Snake { /** Start index. */ private final int start; /** End index. */ private final int end; /** Diagonal number. */ private final int diag; /** * Simple constructor. Creates a new instance of Snake with specified indices. * * @param start start index of the snake * @param end end index of the snake * @param diag diagonal number */ public Snake(final int start, final int end, final int diag) { this.start = start; this.end = end; this.diag = diag; } /** * Get the start index of the snake. * * @return start index of the snake */ public int getStart() { return start; } /** * Get the end index of the snake. * * @return end index of the snake */ public int getEnd() { return end; } /** * Get the diagonal number of the snake. * * @return diagonal number of the snake */ public int getDiag() { return diag; } } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/EditCommand.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/EditCommand.java100664 6404 12243235516 31601 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.sequence; /** * Abstract base class for all commands used to transform an objects sequence * into another one. *

* When two objects sequences are compared through the * {@link SequencesComparator#getScript SequencesComparator.getScript} method, * the result is provided has a {@link EditScript script} containing the commands * that progressively transform the first sequence into the second one. *

* There are only three types of commands, all of which are subclasses of this * abstract class. Each command is associated with one object belonging to at * least one of the sequences. These commands are {@link InsertCommand * InsertCommand} which correspond to an object of the second sequence being * inserted into the first sequence, {@link DeleteCommand DeleteCommand} which * correspond to an object of the first sequence being removed and * {@link KeepCommand KeepCommand} which correspond to an object of the first * sequence which equals an object in the second sequence. It is * guaranteed that comparison is always performed this way (i.e. the * equals method of the object from the first sequence is used and * the object passed as an argument comes from the second sequence) ; this can * be important if subclassing is used for some elements in the first sequence * and the equals method is specialized. * * @see SequencesComparator * @see EditScript * * @since 4.0 * @version $Id: EditCommand.java 1477760 2013-04-30 18:34:03Z tn $ */ public abstract class EditCommand { /** Object on which the command should be applied. */ private final T object; /** * Simple constructor. Creates a new instance of EditCommand * * @param object reference to the object associated with this command, this * refers to an element of one of the sequences being compared */ protected EditCommand(final T object) { this.object = object; } /** * Returns the object associated with this command. * * @return the object on which the command is applied */ protected T getObject() { return object; } /** * Accept a visitor. *

* This method is invoked for each commands belonging to * an {@link EditScript EditScript}, in order to implement the visitor design pattern * * @param visitor the visitor to be accepted */ public abstract void accept(CommandVisitor visitor); } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/KeepCommand.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/KeepCommand.java100664 4305 12243235516 31576 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.sequence; /** * Command representing the keeping of one object present in both sequences. *

* When one object of the first sequence equals another objects in * the second sequence at the right place, the {@link EditScript edit script} * transforming the first sequence into the second sequence uses an instance of * this class to represent the keeping of this object. The objects embedded in * these type of commands always come from the first sequence. * * @see SequencesComparator * @see EditScript * * @since 4.0 * @version $Id: KeepCommand.java 1477760 2013-04-30 18:34:03Z tn $ */ public class KeepCommand extends EditCommand { /** * Simple constructor. Creates a new instance of KeepCommand * * @param object the object belonging to both sequences (the object is a * reference to the instance in the first sequence which is known * to be equal to an instance in the second sequence) */ public KeepCommand(final T object) { super(object); } /** * Accept a visitor. When a KeepCommand accepts a visitor, it * calls its {@link CommandVisitor#visitKeepCommand visitKeepCommand} method. * * @param visitor the visitor to be accepted */ @Override public void accept(final CommandVisitor visitor) { visitor.visitKeepCommand(getObject()); } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/package-info.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/package-info.jav100664 10523 12243235516 31615 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package provides classes to compare two sequences of objects. *

* The two sequences can hold any object type, as only the * equals method is used to compare the elements of the * sequences. It is guaranteed that the comparisons will always be done * as o1.equals(o2) where o1 belongs to the * first sequence and o2 belongs to the second * sequence. This can be important if subclassing is used for some * elements in the first sequence and the equals method is * specialized. *

* Comparison can be seen from two points of view: either as giving the * smallest modification allowing to transform the first sequence into * the second one, or as giving the longest sequence which is a * subsequence of both initial sequences. The equals method * is used to compare objects, so any object can be put into * sequences. Modifications include deleting, inserting or keeping one * object, starting from the beginning of the first sequence. Like most * algorithms of the same type, objects transpositions are not * supported. This means that if a sequence (A, B) is * compared to (B, A), the result will be either the * sequence of three commands delete A, keep B, * insert A or the sequence insert B, * keep A, delete B. *

* The package uses a very efficient comparison algorithm designed by * Eugene W. Myers and described in his paper: An O(ND) * Difference Algorithm and Its Variations. This algorithm produces * the shortest possible * {@link org.apache.commons.collections4.sequence.EditScript edit script} containing * all the {@link org.apache.commons.collections4.sequence.EditCommand commands} * needed to transform the first sequence into the second one. * The entry point for the user to this algorithm is the * {@link org.apache.commons.collections4.sequence.SequencesComparator} class. *

* As explained in Gene Myers paper, the edit script is equivalent to all * other representations and contains all the needed information either * to perform the transformation, of course, or to retrieve the longest * common subsequence for example. *

* If the user needs a very fine grained access to the comparison result, * he needs to go through this script by providing a visitor implementing * the {@link org.apache.commons.collections4.sequence.CommandVisitor} interface. *

* Sometimes however, a more synthetic approach is needed. If the user * prefers to see the differences between the two sequences as global * replacement operations acting on complete subsequences of * the original sequences, he will provide an object implementing the * simple {@link org.apache.commons.collections4.sequence.ReplacementsHandler} interface, * using an instance of the {@link org.apache.commons.collections4.sequence.ReplacementsFinder} * class as a command converting layer between his object and the edit script. The number of * objects which are common to both initial arrays and hence are skipped between each call to the user * {@link org.apache.commons.collections4.sequence.ReplacementsHandler#handleReplacement handleReplacement} * method is also provided. This allows the user to keep track of the current index in * both arrays if he needs so. * * @version $Id: package-info.java 1479338 2013-05-05 15:21:44Z tn $ */ package org.apache.commons.collections4.sequence; ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/CommandVisitor.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/CommandVisitor.j100664 10405 12243235516 31677 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.sequence; /** * This interface should be implemented by user object to walk * through {@link EditScript EditScript} objects. *

* Users should implement this interface in order to walk through * the {@link EditScript EditScript} object created by the comparison * of two sequences. This is a direct application of the visitor * design pattern. The {@link EditScript#visit EditScript.visit} * method takes an object implementing this interface as an argument, * it will perform the loop over all commands in the script and the * proper methods of the user class will be called as the commands are * encountered. *

* The implementation of the user visitor class will depend on the * need. Here are two examples. *

* The first example is a visitor that build the longest common * subsequence: *

 * import org.apache.commons.collections4.comparators.sequence.CommandVisitor;
 *
 * import java.util.ArrayList;
 *
 * public class LongestCommonSubSequence implements CommandVisitor {
 *
 *   public LongestCommonSubSequence() {
 *     a = new ArrayList();
 *   }
 *
 *   public void visitInsertCommand(Object object) {
 *   }
 *
 *   public void visitKeepCommand(Object object) {
 *     a.add(object);
 *   }
 *
 *   public void visitDeleteCommand(Object object) {
 *   }
 *
 *   public Object[] getSubSequence() {
 *     return a.toArray();
 *   }
 *
 *   private ArrayList a;
 *
 * }
 * 
*

* The second example is a visitor that shows the commands and the way * they transform the first sequence into the second one: *

 * import org.apache.commons.collections4.comparators.sequence.CommandVisitor;
 *
 * import java.util.Arrays;
 * import java.util.ArrayList;
 * import java.util.Iterator;
 *
 * public class ShowVisitor implements CommandVisitor {
 *
 *   public ShowVisitor(Object[] sequence1) {
 *     v = new ArrayList();
 *     v.addAll(Arrays.asList(sequence1));
 *     index = 0;
 *   }
 *
 *   public void visitInsertCommand(Object object) {
 *     v.insertElementAt(object, index++);
 *     display("insert", object);
 *   }
 *
 *   public void visitKeepCommand(Object object) {
 *     ++index;
 *     display("keep  ", object);
 *   }
 *
 *   public void visitDeleteCommand(Object object) {
 *     v.remove(index);
 *     display("delete", object);
 *   }
 *
 *   private void display(String commandName, Object object) {
 *     System.out.println(commandName + " " + object + " ->" + this);
 *   }
 *
 *   public String toString() {
 *     StringBuffer buffer = new StringBuffer();
 *     for (Iterator iter = v.iterator(); iter.hasNext();) {
 *       buffer.append(' ').append(iter.next());
 *     }
 *     return buffer.toString();
 *   }
 *
 *   private ArrayList v;
 *   private int index;
 *
 * }
 * 
* * @since 4.0 * @version $Id: CommandVisitor.java 1477760 2013-04-30 18:34:03Z tn $ */ public interface CommandVisitor { /** * Method called when an insert command is encountered. * * @param object object to insert (this object comes from the second sequence) */ void visitInsertCommand(T object); /** * Method called when a keep command is encountered. * * @param object object to keep (this object comes from the first sequence) */ void visitKeepCommand(T object); /** * Method called when a delete command is encountered. * * @param object object to delete (this object comes from the first sequence) */ void visitDeleteCommand(T object); } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/ReplacementsHandler.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/sequence/ReplacementsHand100664 4355 12243235516 31715 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.sequence; import java.util.List; /** * This interface is devoted to handle synchronized replacement sequences. * * @see ReplacementsFinder * @since 4.0 * @version $Id: ReplacementsHandler.java 1543277 2013-11-19 00:53:50Z ggregory $ */ public interface ReplacementsHandler { /** * Handle two synchronized sequences. *

* This method is called by a {@link ReplacementsFinder ReplacementsFinder} * instance when it has synchronized two sub-sequences of object arrays * being compared, and at least one of the sequences is non-empty. Since the * sequences are synchronized, the objects before the two sub-sequences are * equals (if they exist). This property also holds for the objects after * the two sub-sequences. *

* The replacement is defined as replacing the from * sub-sequence into the to sub-sequence. * * @param skipped number of tokens skipped since the last call (i.e. number of * tokens that were in both sequences), this number should be strictly positive * except on the very first call where it can be zero (if the first object of * the two sequences are different) * @param from sub-sequence of objects coming from the first sequence * @param to sub-sequence of objects coming from the second sequence */ void handleReplacement(int skipped, List from, List to); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/KeyAnalyzer.java100664 12575 12243235516 31034 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.trie; import java.io.Serializable; import java.util.Comparator; /** * Defines the interface to analyze {@link org.apache.commons.collections4.Trie Trie} keys on a bit level. * {@link KeyAnalyzer}'s methods return the length of the key in bits, whether or not a bit is set, * and bits per element in the key. *

* Additionally, a method determines if a key is a prefix of another * key and returns the bit index where one key is different from another * key (if the key and found key are equal than the return value is * {@link #EQUAL_BIT_KEY}). * * @since 4.0 * @version $Id: KeyAnalyzer.java 1491621 2013-06-10 22:05:38Z tn $ */ public abstract class KeyAnalyzer implements Comparator, Serializable { /** Serialization version */ private static final long serialVersionUID = -20497563720380683L; /** * Returned by {@link #bitIndex(Object, int, int, Object, int, int)} * if key's bits are all 0. */ public static final int NULL_BIT_KEY = -1; /** * Returned by {@link #bitIndex(Object, int, int, Object, int, int)} if key and found key are equal. * This is a very very specific case and shouldn't happen on a regular basis. */ public static final int EQUAL_BIT_KEY = -2; public static final int OUT_OF_BOUNDS_BIT_KEY = -3; /** * Returns true if bitIndex is a {@link KeyAnalyzer#OUT_OF_BOUNDS_BIT_KEY}. */ static boolean isOutOfBoundsIndex(final int bitIndex) { return bitIndex == OUT_OF_BOUNDS_BIT_KEY; } /** * Returns true if bitIndex is a {@link KeyAnalyzer#EQUAL_BIT_KEY}. */ static boolean isEqualBitKey(final int bitIndex) { return bitIndex == EQUAL_BIT_KEY; } /** * Returns true if bitIndex is a {@link KeyAnalyzer#NULL_BIT_KEY}. */ static boolean isNullBitKey(final int bitIndex) { return bitIndex == NULL_BIT_KEY; } /** * Returns true if the given bitIndex is valid. * Indices are considered valid if they're between 0 and {@link Integer#MAX_VALUE} */ static boolean isValidBitIndex(final int bitIndex) { return bitIndex >= 0; } /** * Returns the number of bits per element in the key. * This is only useful for variable-length keys, such as Strings. * * @return the number of bits per element */ public abstract int bitsPerElement(); /** * Returns the length of the Key in bits. * * @param key the key * @return the bit length of the key */ public abstract int lengthInBits(K key); /** * Returns whether or not a bit is set. * * @param key the key to check, may not be null * @param bitIndex the bit index to check * @param lengthInBits the maximum key length in bits to check * @return {@code true} if the bit is set in the given key and * {@code bitIndex} < {@code lengthInBits}, {@code false} otherwise. */ public abstract boolean isBitSet(K key, int bitIndex, int lengthInBits); /** * Returns the n-th different bit between key and other. This starts the comparison in * key at 'offsetInBits' and goes for 'lengthInBits' bits, and compares to the other key starting * at 'otherOffsetInBits' and going for 'otherLengthInBits' bits. * * @param key the key to use * @param offsetInBits the bit offset in the key * @param lengthInBits the maximum key length in bits to use * @param other the other key to use * @param otherOffsetInBits the bit offset in the other key * @param otherLengthInBits the maximum key length in bits for the other key * @return the bit index where the key and other first differ */ public abstract int bitIndex(K key, int offsetInBits, int lengthInBits, K other, int otherOffsetInBits, int otherLengthInBits); /** * Determines whether or not the given prefix (from offset to length) is a prefix of the given key. * * @param prefix the prefix to check * @param offsetInBits the bit offset in the key * @param lengthInBits the maximum key length in bits to use * @param key the key to check * @return {@code true} if this is a valid prefix for the given key */ public abstract boolean isPrefix(K prefix, int offsetInBits, int lengthInBits, K key); @SuppressWarnings("unchecked") public int compare(final K o1, final K o2) { if (o1 == null) { return o2 == null ? 0 : -1; } else if (o2 == null) { return 1; } return ((Comparable) o1).compareTo(o2); } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/AbstractBitwiseTrie.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/AbstractBitwiseTrie.100664 14256 12243235516 31650 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.trie; import java.io.Serializable; import java.util.AbstractMap; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.collections4.Trie; /** * This class provides some basic {@link Trie} functionality and * utility methods for actual bitwise {@link Trie} implementations. * * @since 4.0 * @version $Id: AbstractBitwiseTrie.java 1492866 2013-06-13 21:01:00Z tn $ */ public abstract class AbstractBitwiseTrie extends AbstractMap implements Trie, Serializable { private static final long serialVersionUID = 5826987063535505652L; /** * The {@link KeyAnalyzer} that's being used to build the PATRICIA {@link Trie}. */ private final KeyAnalyzer keyAnalyzer; /** * Constructs a new {@link Trie} using the given {@link KeyAnalyzer}. * * @param keyAnalyzer the {@link KeyAnalyzer} to use */ protected AbstractBitwiseTrie(final KeyAnalyzer keyAnalyzer) { if (keyAnalyzer == null) { throw new NullPointerException("keyAnalyzer"); } this.keyAnalyzer = keyAnalyzer; } /** * Returns the {@link KeyAnalyzer} that constructed the {@link Trie}. * @return the {@link KeyAnalyzer} used by this {@link Trie} */ protected KeyAnalyzer getKeyAnalyzer() { return keyAnalyzer; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); buffer.append("Trie[").append(size()).append("]={\n"); for (final Map.Entry entry : entrySet()) { buffer.append(" ").append(entry).append("\n"); } buffer.append("}\n"); return buffer.toString(); } /** * A utility method to cast keys. It actually doesn't cast anything. It's just fooling the compiler! */ @SuppressWarnings("unchecked") final K castKey(final Object key) { return (K) key; } /** * Returns the length of the given key in bits * * @see KeyAnalyzer#lengthInBits(Object) */ final int lengthInBits(final K key) { if (key == null) { return 0; } return keyAnalyzer.lengthInBits(key); } /** * Returns the number of bits per element in the key * * @see KeyAnalyzer#bitsPerElement() */ final int bitsPerElement() { return keyAnalyzer.bitsPerElement(); } /** * Returns whether or not the given bit on the key is set or false if the key is null. * * @see KeyAnalyzer#isBitSet(Object, int, int) */ final boolean isBitSet(final K key, final int bitIndex, final int lengthInBits) { if (key == null) { // root's might be null! return false; } return keyAnalyzer.isBitSet(key, bitIndex, lengthInBits); } /** * Utility method for calling {@link KeyAnalyzer#bitIndex(Object, int, int, Object, int, int)}. */ final int bitIndex(final K key, final K foundKey) { return keyAnalyzer.bitIndex(key, 0, lengthInBits(key), foundKey, 0, lengthInBits(foundKey)); } /** * An utility method for calling {@link KeyAnalyzer#compare(Object, Object)} */ final boolean compareKeys(final K key, final K other) { if (key == null) { return other == null; } else if (other == null) { return false; } return keyAnalyzer.compare(key, other) == 0; } /** * Returns true if both values are either null or equal. */ static boolean compare(final Object a, final Object b) { return a == null ? b == null : a.equals(b); } /** * A basic implementation of {@link Entry}. */ abstract static class BasicEntry implements Map.Entry, Serializable { private static final long serialVersionUID = -944364551314110330L; protected K key; protected V value; public BasicEntry(final K key) { this.key = key; } public BasicEntry(final K key, final V value) { this.key = key; this.value = value; } /** * Replaces the current key and value with the provided key & value. */ public V setKeyValue(final K key, final V value) { this.key = key; return setValue(value); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(final V value) { final V previous = this.value; this.value = value; return previous; } @Override public int hashCode() { return (getKey() == null ? 0 : getKey().hashCode()) ^ (getValue() == null ? 0 : getValue().hashCode()); } @Override public boolean equals(final Object o) { if (o == this) { return true; } else if (!(o instanceof Map.Entry)) { return false; } final Map.Entry other = (Map.Entry)o; if (compare(key, other.getKey()) && compare(value, other.getValue())) { return true; } return false; } @Override public String toString() { return key + "=" + value; } } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/UnmodifiableTrie.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/UnmodifiableTrie.jav100664 13105 12243235516 31645 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.trie; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.Trie; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableOrderedMapIterator; /** * An unmodifiable {@link Trie}. * * @since 4.0 * @version $Id: UnmodifiableTrie.java 1540763 2013-11-11 16:30:14Z tn $ */ public class UnmodifiableTrie implements Trie, Serializable, Unmodifiable { /** Serialization version */ private static final long serialVersionUID = -7156426030315945159L; private final Trie delegate; /** * Factory method to create a unmodifiable trie. * * @param the key type * @param the value type * @param trie the trie to decorate, must not be null * @return a new unmodifiable trie * @throws IllegalArgumentException if trie is null */ public static Trie unmodifiableTrie(final Trie trie) { if (trie instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final Trie tmpTrie = (Trie) trie; return tmpTrie; } return new UnmodifiableTrie(trie); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param trie the trie to decorate, must not be null * @throws IllegalArgumentException if trie is null */ public UnmodifiableTrie(final Trie trie) { if (trie == null) { throw new IllegalArgumentException("Trie must not be null"); } @SuppressWarnings("unchecked") // safe to upcast final Trie tmpTrie = (Trie) trie; this.delegate = tmpTrie; } //----------------------------------------------------------------------- public Set> entrySet() { return Collections.unmodifiableSet(delegate.entrySet()); } public Set keySet() { return Collections.unmodifiableSet(delegate.keySet()); } public Collection values() { return Collections.unmodifiableCollection(delegate.values()); } public void clear() { throw new UnsupportedOperationException(); } public boolean containsKey(final Object key) { return delegate.containsKey(key); } public boolean containsValue(final Object value) { return delegate.containsValue(value); } public V get(final Object key) { return delegate.get(key); } public boolean isEmpty() { return delegate.isEmpty(); } public V put(final K key, final V value) { throw new UnsupportedOperationException(); } public void putAll(final Map m) { throw new UnsupportedOperationException(); } public V remove(final Object key) { throw new UnsupportedOperationException(); } public int size() { return delegate.size(); } public K firstKey() { return delegate.firstKey(); } public SortedMap headMap(final K toKey) { return Collections.unmodifiableSortedMap(delegate.headMap(toKey)); } public K lastKey() { return delegate.lastKey(); } public SortedMap subMap(final K fromKey, final K toKey) { return Collections.unmodifiableSortedMap(delegate.subMap(fromKey, toKey)); } public SortedMap tailMap(final K fromKey) { return Collections.unmodifiableSortedMap(delegate.tailMap(fromKey)); } public SortedMap prefixMap(final K key) { return Collections.unmodifiableSortedMap(delegate.prefixMap(key)); } public Comparator comparator() { return delegate.comparator(); } //----------------------------------------------------------------------- public OrderedMapIterator mapIterator() { final OrderedMapIterator it = delegate.mapIterator(); return UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(it); } public K nextKey(K key) { return delegate.nextKey(key); } public K previousKey(K key) { return delegate.previousKey(key); } //----------------------------------------------------------------------- @Override public int hashCode() { return delegate.hashCode(); } @Override public boolean equals(final Object obj) { return delegate.equals(obj); } @Override public String toString() { return delegate.toString(); } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/analyzer/StringKeyAnalyzer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/analyzer/StringKeyAn100664 11015 12243235516 31665 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.trie.analyzer; import org.apache.commons.collections4.trie.KeyAnalyzer; /** * An {@link KeyAnalyzer} for {@link String}s. * * @since 4.0 * @version $Id: StringKeyAnalyzer.java 1543168 2013-11-18 21:22:43Z ggregory $ */ public class StringKeyAnalyzer extends KeyAnalyzer { private static final long serialVersionUID = -7032449491269434877L; /** A singleton instance of {@link StringKeyAnalyzer}. */ public static final StringKeyAnalyzer INSTANCE = new StringKeyAnalyzer(); /** The number of bits per {@link Character}. */ public static final int LENGTH = Character.SIZE; /** A bit mask where the first bit is 1 and the others are zero. */ private static final int MSB = 0x8000; /** Returns a bit mask where the given bit is set. */ private static int mask(final int bit) { return MSB >>> bit; } @Override public int bitsPerElement() { return LENGTH; } @Override public int lengthInBits(final String key) { return key != null ? key.length() * LENGTH : 0; } @Override public int bitIndex(final String key, final int offsetInBits, final int lengthInBits, final String other, final int otherOffsetInBits, final int otherLengthInBits) { boolean allNull = true; if (offsetInBits % LENGTH != 0 || otherOffsetInBits % LENGTH != 0 || lengthInBits % LENGTH != 0 || otherLengthInBits % LENGTH != 0) { throw new IllegalArgumentException("The offsets and lengths must be at Character boundaries"); } final int beginIndex1 = offsetInBits / LENGTH; final int beginIndex2 = otherOffsetInBits / LENGTH; final int endIndex1 = beginIndex1 + lengthInBits / LENGTH; final int endIndex2 = beginIndex2 + otherLengthInBits / LENGTH; final int length = Math.max(endIndex1, endIndex2); // Look at each character, and if they're different // then figure out which bit makes the difference // and return it. char k = 0, f = 0; for(int i = 0; i < length; i++) { final int index1 = beginIndex1 + i; final int index2 = beginIndex2 + i; if (index1 >= endIndex1) { k = 0; } else { k = key.charAt(index1); } if (other == null || index2 >= endIndex2) { f = 0; } else { f = other.charAt(index2); } if (k != f) { final int x = k ^ f; return i * LENGTH + Integer.numberOfLeadingZeros(x) - LENGTH; } if (k != 0) { allNull = false; } } // All bits are 0 if (allNull) { return KeyAnalyzer.NULL_BIT_KEY; } // Both keys are equal return KeyAnalyzer.EQUAL_BIT_KEY; } @Override public boolean isBitSet(final String key, final int bitIndex, final int lengthInBits) { if (key == null || bitIndex >= lengthInBits) { return false; } final int index = bitIndex / LENGTH; final int bit = bitIndex % LENGTH; return (key.charAt(index) & mask(bit)) != 0; } @Override public boolean isPrefix(final String prefix, final int offsetInBits, final int lengthInBits, final String key) { if (offsetInBits % LENGTH != 0 || lengthInBits % LENGTH != 0) { throw new IllegalArgumentException( "Cannot determine prefix outside of Character boundaries"); } final String s1 = prefix.substring(offsetInBits / LENGTH, lengthInBits / LENGTH); return key.startsWith(s1); } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/analyzer/package-info.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/analyzer/package-inf100664 2025 12243235516 31615 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains various {@link org.apache.commons.collections4.trie.KeyAnalyzer} implementations. * * @version $Id: package-info.java 1491615 2013-06-10 21:46:19Z tn $ */ package org.apache.commons.collections4.trie.analyzer; commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/package-info.java100664 2756 12243235516 31102 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains implementations of the * {@link org.apache.commons.collections4.Trie Trie} interface. *

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

    *
  • PatriciaTrie - an implementation of a PATRICIA trie *
*

* The following decorators are provided: *

    *
  • Unmodifiable - ensures the collection cannot be altered *
* * @version $Id: package-info.java 1493523 2013-06-16 15:56:35Z tn $ */ package org.apache.commons.collections4.trie; ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/AbstractPatriciaTrie.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/AbstractPatriciaTrie100664 227615 12243235516 31745 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.trie; 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.Collections; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import org.apache.commons.collections4.OrderedMapIterator; /** * This class implements the base PATRICIA algorithm and everything that * is related to the {@link Map} interface. * * @since 4.0 * @version $Id: AbstractPatriciaTrie.java 1543928 2013-11-20 20:15:35Z tn $ */ abstract class AbstractPatriciaTrie extends AbstractBitwiseTrie { private static final long serialVersionUID = 5155253417231339498L; /** The root node of the {@link Trie}. */ private transient TrieEntry root = new TrieEntry(null, null, -1); /** * Each of these fields are initialized to contain an instance of the * appropriate view the first time this view is requested. The views are * stateless, so there's no reason to create more than one of each. */ private transient volatile Set keySet; private transient volatile Collection values; private transient volatile Set> entrySet; /** The current size of the {@link Trie}. */ private transient int size = 0; /** * The number of times this {@link Trie} has been modified. * It's used to detect concurrent modifications and fail-fast the {@link Iterator}s. */ protected transient int modCount = 0; protected AbstractPatriciaTrie(final KeyAnalyzer keyAnalyzer) { super(keyAnalyzer); } /** * Constructs a new {@link org.apache.commons.collections4.Trie Trie} using the given * {@link KeyAnalyzer} and initializes the {@link org.apache.commons.collections4.Trie Trie} * with the values from the provided {@link Map}. */ protected AbstractPatriciaTrie(final KeyAnalyzer keyAnalyzer, final Map map) { super(keyAnalyzer); putAll(map); } //----------------------------------------------------------------------- @Override public void clear() { root.key = null; root.bitIndex = -1; root.value = null; root.parent = null; root.left = root; root.right = null; root.predecessor = root; size = 0; incrementModCount(); } @Override public int size() { return size; } /** * A helper method to increment the {@link Trie} size and the modification counter. */ void incrementSize() { size++; incrementModCount(); } /** * A helper method to decrement the {@link Trie} size and increment the modification counter. */ void decrementSize() { size--; incrementModCount(); } /** * A helper method to increment the modification counter. */ private void incrementModCount() { ++modCount; } @Override public V put(final K key, final V value) { if (key == null) { throw new NullPointerException("Key cannot be null"); } final int lengthInBits = lengthInBits(key); // The only place to store a key with a length // of zero bits is the root node if (lengthInBits == 0) { if (root.isEmpty()) { incrementSize(); } else { incrementModCount(); } return root.setKeyValue(key, value); } final TrieEntry found = getNearestEntryForKey(key, lengthInBits); if (compareKeys(key, found.key)) { if (found.isEmpty()) { // <- must be the root incrementSize(); } else { incrementModCount(); } return found.setKeyValue(key, value); } final int bitIndex = bitIndex(key, found.key); if (!KeyAnalyzer.isOutOfBoundsIndex(bitIndex)) { if (KeyAnalyzer.isValidBitIndex(bitIndex)) { // in 99.999...9% the case /* NEW KEY+VALUE TUPLE */ final TrieEntry t = new TrieEntry(key, value, bitIndex); addEntry(t, lengthInBits); incrementSize(); return null; } else if (KeyAnalyzer.isNullBitKey(bitIndex)) { // A bits of the Key are zero. The only place to // store such a Key is the root Node! /* NULL BIT KEY */ if (root.isEmpty()) { incrementSize(); } else { incrementModCount(); } return root.setKeyValue(key, value); } else if (KeyAnalyzer.isEqualBitKey(bitIndex)) { // This is a very special and rare case. /* REPLACE OLD KEY+VALUE */ if (found != root) { incrementModCount(); return found.setKeyValue(key, value); } } } throw new IllegalArgumentException("Failed to put: " + key + " -> " + value + ", " + bitIndex); } /** * Adds the given {@link TrieEntry} to the {@link Trie}. */ TrieEntry addEntry(final TrieEntry entry, final int lengthInBits) { TrieEntry current = root.left; TrieEntry path = root; while(true) { if (current.bitIndex >= entry.bitIndex || current.bitIndex <= path.bitIndex) { entry.predecessor = entry; if (!isBitSet(entry.key, entry.bitIndex, lengthInBits)) { entry.left = entry; entry.right = current; } else { entry.left = current; entry.right = entry; } entry.parent = path; if (current.bitIndex >= entry.bitIndex) { current.parent = entry; } // if we inserted an uplink, set the predecessor on it if (current.bitIndex <= path.bitIndex) { current.predecessor = entry; } if (path == root || !isBitSet(entry.key, path.bitIndex, lengthInBits)) { path.left = entry; } else { path.right = entry; } return entry; } path = current; if (!isBitSet(entry.key, current.bitIndex, lengthInBits)) { current = current.left; } else { current = current.right; } } } @Override public V get(final Object k) { final TrieEntry entry = getEntry(k); return entry != null ? entry.getValue() : null; } /** * Returns the entry associated with the specified key in the * PatriciaTrieBase. Returns null if the map contains no mapping * for this key. *

* This may throw ClassCastException if the object is not of type K. */ TrieEntry getEntry(final Object k) { final K key = castKey(k); if (key == null) { return null; } final int lengthInBits = lengthInBits(key); final TrieEntry entry = getNearestEntryForKey(key, lengthInBits); return !entry.isEmpty() && compareKeys(key, entry.key) ? entry : null; } /** * Returns the {@link Entry} whose key is closest in a bitwise XOR * metric to the given key. This is NOT lexicographic closeness. * For example, given the keys: * *

    *
  1. D = 1000100 *
  2. H = 1001000 *
  3. L = 1001100 *
* * If the {@link Trie} contained 'H' and 'L', a lookup of 'D' would * return 'L', because the XOR distance between D & L is smaller * than the XOR distance between D & H. * * @param key the key to use in the search * @return the {@link Entry} whose key is closest in a bitwise XOR metric * to the provided key */ public Map.Entry select(final K key) { final int lengthInBits = lengthInBits(key); final Reference> reference = new Reference>(); if (!selectR(root.left, -1, key, lengthInBits, reference)) { return reference.get(); } return null; } /** * Returns the key that is closest in a bitwise XOR metric to the * provided key. This is NOT lexicographic closeness! * * For example, given the keys: * *
    *
  1. D = 1000100 *
  2. H = 1001000 *
  3. L = 1001100 *
* * If the {@link Trie} contained 'H' and 'L', a lookup of 'D' would * return 'L', because the XOR distance between D & L is smaller * than the XOR distance between D & H. * * @param key the key to use in the search * @return the key that is closest in a bitwise XOR metric to the provided key */ public K selectKey(final K key) { final Map.Entry entry = select(key); if (entry == null) { return null; } return entry.getKey(); } /** * Returns the value whose key is closest in a bitwise XOR metric to * the provided key. This is NOT lexicographic closeness! * * For example, given the keys: * *
    *
  1. D = 1000100 *
  2. H = 1001000 *
  3. L = 1001100 *
* * If the {@link Trie} contained 'H' and 'L', a lookup of 'D' would * return 'L', because the XOR distance between D & L is smaller * than the XOR distance between D & H. * * @param key the key to use in the search * @return the value whose key is closest in a bitwise XOR metric * to the provided key */ public V selectValue(final K key) { final Map.Entry entry = select(key); if (entry == null) { return null; } return entry.getValue(); } /** * This is equivalent to the other {@link #selectR(TrieEntry, int, Object, int, Cursor, Reference)} * method but without its overhead because we're selecting only one best matching Entry from the {@link Trie}. */ private boolean selectR(final TrieEntry h, final int bitIndex, final K key, final int lengthInBits, final Reference> reference) { if (h.bitIndex <= bitIndex) { // If we hit the root Node and it is empty // we have to look for an alternative best // matching node. if (!h.isEmpty()) { reference.set(h); return false; } return true; } if (!isBitSet(key, h.bitIndex, lengthInBits)) { if (selectR(h.left, h.bitIndex, key, lengthInBits, reference)) { return selectR(h.right, h.bitIndex, key, lengthInBits, reference); } } else { if (selectR(h.right, h.bitIndex, key, lengthInBits, reference)) { return selectR(h.left, h.bitIndex, key, lengthInBits, reference); } } return false; } @Override public boolean containsKey(final Object k) { if (k == null) { return false; } final K key = castKey(k); final int lengthInBits = lengthInBits(key); final TrieEntry entry = getNearestEntryForKey(key, lengthInBits); return !entry.isEmpty() && compareKeys(key, entry.key); } @Override public Set> entrySet() { if (entrySet == null) { entrySet = new EntrySet(); } return entrySet; } @Override public Set keySet() { if (keySet == null) { keySet = new KeySet(); } return keySet; } @Override public Collection values() { if (values == null) { values = new Values(); } return values; } /** * {@inheritDoc} * * @throws ClassCastException if provided key is of an incompatible type */ @Override public V remove(final Object k) { if (k == null) { return null; } final K key = castKey(k); final int lengthInBits = lengthInBits(key); TrieEntry current = root.left; TrieEntry path = root; while (true) { if (current.bitIndex <= path.bitIndex) { if (!current.isEmpty() && compareKeys(key, current.key)) { return removeEntry(current); } else { return null; } } path = current; if (!isBitSet(key, current.bitIndex, lengthInBits)) { current = current.left; } else { current = current.right; } } } /** * Returns the nearest entry for a given key. This is useful * for finding knowing if a given key exists (and finding the value * for it), or for inserting the key. * * The actual get implementation. This is very similar to * selectR but with the exception that it might return the * root Entry even if it's empty. */ TrieEntry getNearestEntryForKey(final K key, final int lengthInBits) { TrieEntry current = root.left; TrieEntry path = root; while(true) { if (current.bitIndex <= path.bitIndex) { return current; } path = current; if (!isBitSet(key, current.bitIndex, lengthInBits)) { current = current.left; } else { current = current.right; } } } /** * Removes a single entry from the {@link Trie}. * * If we found a Key (Entry h) then figure out if it's * an internal (hard to remove) or external Entry (easy * to remove) */ V removeEntry(final TrieEntry h) { if (h != root) { if (h.isInternalNode()) { removeInternalEntry(h); } else { removeExternalEntry(h); } } decrementSize(); return h.setKeyValue(null, null); } /** * Removes an external entry from the {@link Trie}. * * If it's an external Entry then just remove it. * This is very easy and straight forward. */ private void removeExternalEntry(final TrieEntry h) { if (h == root) { throw new IllegalArgumentException("Cannot delete root Entry!"); } else if (!h.isExternalNode()) { throw new IllegalArgumentException(h + " is not an external Entry!"); } final TrieEntry parent = h.parent; final TrieEntry child = h.left == h ? h.right : h.left; if (parent.left == h) { parent.left = child; } else { parent.right = child; } // either the parent is changing, or the predecessor is changing. if (child.bitIndex > parent.bitIndex) { child.parent = parent; } else { child.predecessor = parent; } } /** * Removes an internal entry from the {@link Trie}. * * If it's an internal Entry then "good luck" with understanding * this code. The Idea is essentially that Entry p takes Entry h's * place in the trie which requires some re-wiring. */ private void removeInternalEntry(final TrieEntry h) { if (h == root) { throw new IllegalArgumentException("Cannot delete root Entry!"); } else if (!h.isInternalNode()) { throw new IllegalArgumentException(h + " is not an internal Entry!"); } final TrieEntry p = h.predecessor; // Set P's bitIndex p.bitIndex = h.bitIndex; // Fix P's parent, predecessor and child Nodes { final TrieEntry parent = p.parent; final TrieEntry child = p.left == h ? p.right : p.left; // if it was looping to itself previously, // it will now be pointed from it's parent // (if we aren't removing it's parent -- // in that case, it remains looping to itself). // otherwise, it will continue to have the same // predecessor. if (p.predecessor == p && p.parent != h) { p.predecessor = p.parent; } if (parent.left == p) { parent.left = child; } else { parent.right = child; } if (child.bitIndex > parent.bitIndex) { child.parent = parent; } } // Fix H's parent and child Nodes { // If H is a parent of its left and right child // then change them to P if (h.left.parent == h) { h.left.parent = p; } if (h.right.parent == h) { h.right.parent = p; } // Change H's parent if (h.parent.left == h) { h.parent.left = p; } else { h.parent.right = p; } } // Copy the remaining fields from H to P //p.bitIndex = h.bitIndex; p.parent = h.parent; p.left = h.left; p.right = h.right; // Make sure that if h was pointing to any uplinks, // p now points to them. if (isValidUplink(p.left, p)) { p.left.predecessor = p; } if (isValidUplink(p.right, p)) { p.right.predecessor = p; } } /** * Returns the entry lexicographically after the given entry. * If the given entry is null, returns the first node. */ TrieEntry nextEntry(final TrieEntry node) { if (node == null) { return firstEntry(); } else { return nextEntryImpl(node.predecessor, node, null); } } /** * Scans for the next node, starting at the specified point, and using 'previous' * as a hint that the last node we returned was 'previous' (so we know not to return * it again). If 'tree' is non-null, this will limit the search to the given tree. * * The basic premise is that each iteration can follow the following steps: * * 1) Scan all the way to the left. * a) If we already started from this node last time, proceed to Step 2. * b) If a valid uplink is found, use it. * c) If the result is an empty node (root not set), break the scan. * d) If we already returned the left node, break the scan. * * 2) Check the right. * a) If we already returned the right node, proceed to Step 3. * b) If it is a valid uplink, use it. * c) Do Step 1 from the right node. * * 3) Back up through the parents until we encounter find a parent * that we're not the right child of. * * 4) If there's no right child of that parent, the iteration is finished. * Otherwise continue to Step 5. * * 5) Check to see if the right child is a valid uplink. * a) If we already returned that child, proceed to Step 6. * Otherwise, use it. * * 6) If the right child of the parent is the parent itself, we've * already found & returned the end of the Trie, so exit. * * 7) Do Step 1 on the parent's right child. */ TrieEntry nextEntryImpl(final TrieEntry start, final TrieEntry previous, final TrieEntry tree) { TrieEntry current = start; // Only look at the left if this was a recursive or // the first check, otherwise we know we've already looked // at the left. if (previous == null || start != previous.predecessor) { while (!current.left.isEmpty()) { // stop traversing if we've already // returned the left of this node. if (previous == current.left) { break; } if (isValidUplink(current.left, current)) { return current.left; } current = current.left; } } // If there's no data at all, exit. if (current.isEmpty()) { return null; } // If we've already returned the left, // and the immediate right is null, // there's only one entry in the Trie // which is stored at the root. // // / ("") <-- root // \_/ \ // null <-- 'current' // if (current.right == null) { return null; } // If nothing valid on the left, try the right. if (previous != current.right) { // See if it immediately is valid. if (isValidUplink(current.right, current)) { return current.right; } // Must search on the right's side if it wasn't initially valid. return nextEntryImpl(current.right, previous, tree); } // Neither left nor right are valid, find the first parent // whose child did not come from the right & traverse it. while (current == current.parent.right) { // If we're going to traverse to above the subtree, stop. if (current == tree) { return null; } current = current.parent; } // If we're on the top of the subtree, we can't go any higher. if (current == tree) { return null; } // If there's no right, the parent must be root, so we're done. if (current.parent.right == null) { return null; } // If the parent's right points to itself, we've found one. if (previous != current.parent.right && isValidUplink(current.parent.right, current.parent)) { return current.parent.right; } // If the parent's right is itself, there can't be any more nodes. if (current.parent.right == current.parent) { return null; } // We need to traverse down the parent's right's path. return nextEntryImpl(current.parent.right, previous, tree); } /** * Returns the first entry the {@link Trie} is storing. *

* This is implemented by going always to the left until * we encounter a valid uplink. That uplink is the first key. */ TrieEntry firstEntry() { // if Trie is empty, no first node. if (isEmpty()) { return null; } return followLeft(root); } /** * Goes left through the tree until it finds a valid node. */ TrieEntry followLeft(TrieEntry node) { while(true) { TrieEntry child = node.left; // if we hit root and it didn't have a node, go right instead. if (child.isEmpty()) { child = node.right; } if (child.bitIndex <= node.bitIndex) { return child; } node = child; } } //----------------------------------------------------------------------- public Comparator comparator() { return getKeyAnalyzer(); } public K firstKey() { if (size() == 0) { throw new NoSuchElementException(); } return firstEntry().getKey(); } public K lastKey() { final TrieEntry entry = lastEntry(); if (entry != null) { return entry.getKey(); } else { throw new NoSuchElementException(); } } public K nextKey(final K key) { if (key == null) { throw new NullPointerException(); } final TrieEntry entry = getEntry(key); if (entry != null) { final TrieEntry nextEntry = nextEntry(entry); return nextEntry != null ? nextEntry.getKey() : null; } else { return null; } } public K previousKey(final K key) { if (key == null) { throw new NullPointerException(); } final TrieEntry entry = getEntry(key); if (entry != null) { final TrieEntry prevEntry = previousEntry(entry); return prevEntry != null ? prevEntry.getKey() : null; } else { return null; } } public OrderedMapIterator mapIterator() { return new TrieMapIterator(); } public SortedMap prefixMap(final K key) { return getPrefixMapByBits(key, 0, lengthInBits(key)); } /** * Returns a view of this {@link Trie} of all elements that are prefixed * by the number of bits in the given Key. *

* The view that this returns is optimized to have a very efficient * {@link Iterator}. The {@link SortedMap#firstKey()}, * {@link SortedMap#lastKey()} & {@link Map#size()} methods must * iterate over all possible values in order to determine the results. * This information is cached until the PATRICIA {@link Trie} changes. * All other methods (except {@link Iterator}) must compare the given * key to the prefix to ensure that it is within the range of the view. * The {@link Iterator}'s remove method must also relocate the subtree * that contains the prefixes if the entry holding the subtree is * removed or changes. Changing the subtree takes O(K) time. * * @param key the key to use in the search * @param offsetInBits the prefix offset * @param lengthInBits the number of significant prefix bits * @return a {@link SortedMap} view of this {@link Trie} with all elements whose * key is prefixed by the search key */ private SortedMap getPrefixMapByBits(final K key, final int offsetInBits, final int lengthInBits) { final int offsetLength = offsetInBits + lengthInBits; if (offsetLength > lengthInBits(key)) { throw new IllegalArgumentException(offsetInBits + " + " + lengthInBits + " > " + lengthInBits(key)); } if (offsetLength == 0) { return this; } return new PrefixRangeMap(key, offsetInBits, lengthInBits); } public SortedMap headMap(final K toKey) { return new RangeEntryMap(null, toKey); } public SortedMap subMap(final K fromKey, final K toKey) { return new RangeEntryMap(fromKey, toKey); } public SortedMap tailMap(final K fromKey) { return new RangeEntryMap(fromKey, null); } /** * Returns an entry strictly higher than the given key, * or null if no such entry exists. */ TrieEntry higherEntry(final K key) { // TODO: Cleanup so that we don't actually have to add/remove from the // tree. (We do it here because there are other well-defined // functions to perform the search.) final int lengthInBits = lengthInBits(key); if (lengthInBits == 0) { if (!root.isEmpty()) { // If data in root, and more after -- return it. if (size() > 1) { return nextEntry(root); } else { // If no more after, no higher entry. return null; } } else { // Root is empty & we want something after empty, return first. return firstEntry(); } } final TrieEntry found = getNearestEntryForKey(key, lengthInBits); if (compareKeys(key, found.key)) { return nextEntry(found); } final int bitIndex = bitIndex(key, found.key); if (KeyAnalyzer.isValidBitIndex(bitIndex)) { final TrieEntry added = new TrieEntry(key, null, bitIndex); addEntry(added, lengthInBits); incrementSize(); // must increment because remove will decrement final TrieEntry ceil = nextEntry(added); removeEntry(added); modCount -= 2; // we didn't really modify it. return ceil; } else if (KeyAnalyzer.isNullBitKey(bitIndex)) { if (!root.isEmpty()) { return firstEntry(); } else if (size() > 1) { return nextEntry(firstEntry()); } else { return null; } } else if (KeyAnalyzer.isEqualBitKey(bitIndex)) { return nextEntry(found); } // we should have exited above. throw new IllegalStateException("invalid lookup: " + key); } /** * Returns a key-value mapping associated with the least key greater * than or equal to the given key, or null if there is no such key. */ TrieEntry ceilingEntry(final K key) { // Basically: // Follow the steps of adding an entry, but instead... // // - If we ever encounter a situation where we found an equal // key, we return it immediately. // // - If we hit an empty root, return the first iterable item. // // - If we have to add a new item, we temporarily add it, // find the successor to it, then remove the added item. // // These steps ensure that the returned value is either the // entry for the key itself, or the first entry directly after // the key. // TODO: Cleanup so that we don't actually have to add/remove from the // tree. (We do it here because there are other well-defined // functions to perform the search.) final int lengthInBits = lengthInBits(key); if (lengthInBits == 0) { if (!root.isEmpty()) { return root; } else { return firstEntry(); } } final TrieEntry found = getNearestEntryForKey(key, lengthInBits); if (compareKeys(key, found.key)) { return found; } final int bitIndex = bitIndex(key, found.key); if (KeyAnalyzer.isValidBitIndex(bitIndex)) { final TrieEntry added = new TrieEntry(key, null, bitIndex); addEntry(added, lengthInBits); incrementSize(); // must increment because remove will decrement final TrieEntry ceil = nextEntry(added); removeEntry(added); modCount -= 2; // we didn't really modify it. return ceil; } else if (KeyAnalyzer.isNullBitKey(bitIndex)) { if (!root.isEmpty()) { return root; } else { return firstEntry(); } } else if (KeyAnalyzer.isEqualBitKey(bitIndex)) { return found; } // we should have exited above. throw new IllegalStateException("invalid lookup: " + key); } /** * Returns a key-value mapping associated with the greatest key * strictly less than the given key, or null if there is no such key. */ TrieEntry lowerEntry(final K key) { // Basically: // Follow the steps of adding an entry, but instead... // // - If we ever encounter a situation where we found an equal // key, we return it's previousEntry immediately. // // - If we hit root (empty or not), return null. // // - If we have to add a new item, we temporarily add it, // find the previousEntry to it, then remove the added item. // // These steps ensure that the returned value is always just before // the key or null (if there was nothing before it). // TODO: Cleanup so that we don't actually have to add/remove from the // tree. (We do it here because there are other well-defined // functions to perform the search.) final int lengthInBits = lengthInBits(key); if (lengthInBits == 0) { return null; // there can never be anything before root. } final TrieEntry found = getNearestEntryForKey(key, lengthInBits); if (compareKeys(key, found.key)) { return previousEntry(found); } final int bitIndex = bitIndex(key, found.key); if (KeyAnalyzer.isValidBitIndex(bitIndex)) { final TrieEntry added = new TrieEntry(key, null, bitIndex); addEntry(added, lengthInBits); incrementSize(); // must increment because remove will decrement final TrieEntry prior = previousEntry(added); removeEntry(added); modCount -= 2; // we didn't really modify it. return prior; } else if (KeyAnalyzer.isNullBitKey(bitIndex)) { return null; } else if (KeyAnalyzer.isEqualBitKey(bitIndex)) { return previousEntry(found); } // we should have exited above. throw new IllegalStateException("invalid lookup: " + key); } /** * Returns a key-value mapping associated with the greatest key * less than or equal to the given key, or null if there is no such key. */ TrieEntry floorEntry(final K key) { // TODO: Cleanup so that we don't actually have to add/remove from the // tree. (We do it here because there are other well-defined // functions to perform the search.) final int lengthInBits = lengthInBits(key); if (lengthInBits == 0) { if (!root.isEmpty()) { return root; } else { return null; } } final TrieEntry found = getNearestEntryForKey(key, lengthInBits); if (compareKeys(key, found.key)) { return found; } final int bitIndex = bitIndex(key, found.key); if (KeyAnalyzer.isValidBitIndex(bitIndex)) { final TrieEntry added = new TrieEntry(key, null, bitIndex); addEntry(added, lengthInBits); incrementSize(); // must increment because remove will decrement final TrieEntry floor = previousEntry(added); removeEntry(added); modCount -= 2; // we didn't really modify it. return floor; } else if (KeyAnalyzer.isNullBitKey(bitIndex)) { if (!root.isEmpty()) { return root; } else { return null; } } else if (KeyAnalyzer.isEqualBitKey(bitIndex)) { return found; } // we should have exited above. throw new IllegalStateException("invalid lookup: " + key); } /** * Finds the subtree that contains the prefix. * * This is very similar to getR but with the difference that * we stop the lookup if h.bitIndex > lengthInBits. */ TrieEntry subtree(final K prefix, final int offsetInBits, final int lengthInBits) { TrieEntry current = root.left; TrieEntry path = root; while(true) { if (current.bitIndex <= path.bitIndex || lengthInBits < current.bitIndex) { break; } path = current; if (!isBitSet(prefix, offsetInBits + current.bitIndex, offsetInBits + lengthInBits)) { current = current.left; } else { current = current.right; } } // Make sure the entry is valid for a subtree. final TrieEntry entry = current.isEmpty() ? path : current; // If entry is root, it can't be empty. if (entry.isEmpty()) { return null; } final int endIndexInBits = offsetInBits + lengthInBits; // if root && length of root is less than length of lookup, // there's nothing. // (this prevents returning the whole subtree if root has an empty // string and we want to lookup things with "\0") if (entry == root && lengthInBits(entry.getKey()) < endIndexInBits) { return null; } // Found key's length-th bit differs from our key // which means it cannot be the prefix... if (isBitSet(prefix, endIndexInBits, endIndexInBits) != isBitSet(entry.key, lengthInBits, lengthInBits(entry.key))) { return null; } // ... or there are less than 'length' equal bits final int bitIndex = getKeyAnalyzer().bitIndex(prefix, offsetInBits, lengthInBits, entry.key, 0, lengthInBits(entry.getKey())); if (bitIndex >= 0 && bitIndex < lengthInBits) { return null; } return entry; } /** * Returns the last entry the {@link Trie} is storing. * *

This is implemented by going always to the right until * we encounter a valid uplink. That uplink is the last key. */ TrieEntry lastEntry() { return followRight(root.left); } /** * Traverses down the right path until it finds an uplink. */ TrieEntry followRight(TrieEntry node) { // if Trie is empty, no last entry. if (node.right == null) { return null; } // Go as far right as possible, until we encounter an uplink. while (node.right.bitIndex > node.bitIndex) { node = node.right; } return node.right; } /** * Returns the node lexicographically before the given node (or null if none). * * This follows four simple branches: * - If the uplink that returned us was a right uplink: * - If predecessor's left is a valid uplink from predecessor, return it. * - Else, follow the right path from the predecessor's left. * - If the uplink that returned us was a left uplink: * - Loop back through parents until we encounter a node where * node != node.parent.left. * - If node.parent.left is uplink from node.parent: * - If node.parent.left is not root, return it. * - If it is root & root isEmpty, return null. * - If it is root & root !isEmpty, return root. * - If node.parent.left is not uplink from node.parent: * - Follow right path for first right child from node.parent.left * * @param start the start entry */ TrieEntry previousEntry(final TrieEntry start) { if (start.predecessor == null) { throw new IllegalArgumentException("must have come from somewhere!"); } if (start.predecessor.right == start) { if (isValidUplink(start.predecessor.left, start.predecessor)) { return start.predecessor.left; } else { return followRight(start.predecessor.left); } } else { TrieEntry node = start.predecessor; while (node.parent != null && node == node.parent.left) { node = node.parent; } if (node.parent == null) { // can be null if we're looking up root. return null; } if (isValidUplink(node.parent.left, node.parent)) { if (node.parent.left == root) { if (root.isEmpty()) { return null; } else { return root; } } else { return node.parent.left; } } else { return followRight(node.parent.left); } } } /** * Returns the entry lexicographically after the given entry. * If the given entry is null, returns the first node. * * This will traverse only within the subtree. If the given node * is not within the subtree, this will have undefined results. */ TrieEntry nextEntryInSubtree(final TrieEntry node, final TrieEntry parentOfSubtree) { if (node == null) { return firstEntry(); } else { return nextEntryImpl(node.predecessor, node, parentOfSubtree); } } /** * Returns true if 'next' is a valid uplink coming from 'from'. */ static boolean isValidUplink(final TrieEntry next, final TrieEntry from) { return next != null && next.bitIndex <= from.bitIndex && !next.isEmpty(); } /** * A {@link Reference} allows us to return something through a Method's * argument list. An alternative would be to an Array with a length of * one (1) but that leads to compiler warnings. Computationally and memory * wise there's no difference (except for the need to load the * {@link Reference} Class but that happens only once). */ private static class Reference { private E item; public void set(final E item) { this.item = item; } public E get() { return item; } } /** * A {@link Trie} is a set of {@link TrieEntry} nodes. */ protected static class TrieEntry extends BasicEntry { private static final long serialVersionUID = 4596023148184140013L; /** The index this entry is comparing. */ protected int bitIndex; /** The parent of this entry. */ protected TrieEntry parent; /** The left child of this entry. */ protected TrieEntry left; /** The right child of this entry. */ protected TrieEntry right; /** The entry who uplinks to this entry. */ protected TrieEntry predecessor; public TrieEntry(final K key, final V value, final int bitIndex) { super(key, value); this.bitIndex = bitIndex; this.parent = null; this.left = this; this.right = null; this.predecessor = this; } /** * Whether or not the entry is storing a key. * Only the root can potentially be empty, all other * nodes must have a key. */ public boolean isEmpty() { return key == null; } /** * Neither the left nor right child is a loopback. */ public boolean isInternalNode() { return left != this && right != this; } /** * Either the left or right child is a loopback. */ public boolean isExternalNode() { return !isInternalNode(); } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); if (bitIndex == -1) { buffer.append("RootEntry("); } else { buffer.append("Entry("); } buffer.append("key=").append(getKey()).append(" [").append(bitIndex).append("], "); buffer.append("value=").append(getValue()).append(", "); //buffer.append("bitIndex=").append(bitIndex).append(", "); if (parent != null) { if (parent.bitIndex == -1) { buffer.append("parent=").append("ROOT"); } else { buffer.append("parent=").append(parent.getKey()).append(" [").append(parent.bitIndex).append("]"); } } else { buffer.append("parent=").append("null"); } buffer.append(", "); if (left != null) { if (left.bitIndex == -1) { buffer.append("left=").append("ROOT"); } else { buffer.append("left=").append(left.getKey()).append(" [").append(left.bitIndex).append("]"); } } else { buffer.append("left=").append("null"); } buffer.append(", "); if (right != null) { if (right.bitIndex == -1) { buffer.append("right=").append("ROOT"); } else { buffer.append("right=").append(right.getKey()).append(" [").append(right.bitIndex).append("]"); } } else { buffer.append("right=").append("null"); } buffer.append(", "); if (predecessor != null) { if(predecessor.bitIndex == -1) { buffer.append("predecessor=").append("ROOT"); } else { buffer.append("predecessor=").append(predecessor.getKey()).append(" ["). append(predecessor.bitIndex).append("]"); } } buffer.append(")"); return buffer.toString(); } } /** * This is a entry set view of the {@link Trie} as returned by {@link Map#entrySet()}. */ private class EntrySet extends AbstractSet> { @Override public Iterator> iterator() { return new EntryIterator(); } @Override public boolean contains(final Object o) { if (!(o instanceof Map.Entry)) { return false; } final TrieEntry candidate = getEntry(((Map.Entry)o).getKey()); return candidate != null && candidate.equals(o); } @Override public boolean remove(final Object obj) { if (obj instanceof Map.Entry == false) { return false; } if (contains(obj) == false) { return false; } final Map.Entry entry = (Map.Entry) obj; AbstractPatriciaTrie.this.remove(entry.getKey()); return true; } @Override public int size() { return AbstractPatriciaTrie.this.size(); } @Override public void clear() { AbstractPatriciaTrie.this.clear(); } /** * An {@link Iterator} that returns {@link Entry} Objects. */ private class EntryIterator extends TrieIterator> { public Map.Entry next() { return nextEntry(); } } } /** * This is a key set view of the {@link Trie} as returned by {@link Map#keySet()}. */ private class KeySet extends AbstractSet { @Override public Iterator iterator() { return new KeyIterator(); } @Override public int size() { return AbstractPatriciaTrie.this.size(); } @Override public boolean contains(final Object o) { return containsKey(o); } @Override public boolean remove(final Object o) { final int size = size(); AbstractPatriciaTrie.this.remove(o); return size != size(); } @Override public void clear() { AbstractPatriciaTrie.this.clear(); } /** * An {@link Iterator} that returns Key Objects. */ private class KeyIterator extends TrieIterator { public K next() { return nextEntry().getKey(); } } } /** * This is a value view of the {@link Trie} as returned by {@link Map#values()}. */ private class Values extends AbstractCollection { @Override public Iterator iterator() { return new ValueIterator(); } @Override public int size() { return AbstractPatriciaTrie.this.size(); } @Override public boolean contains(final Object o) { return containsValue(o); } @Override public void clear() { AbstractPatriciaTrie.this.clear(); } @Override public boolean remove(final Object o) { for (final Iterator it = iterator(); it.hasNext(); ) { final V value = it.next(); if (compare(value, o)) { it.remove(); return true; } } return false; } /** * An {@link Iterator} that returns Value Objects. */ private class ValueIterator extends TrieIterator { public V next() { return nextEntry().getValue(); } } } /** * An iterator for the entries. */ abstract class TrieIterator implements Iterator { /** For fast-fail. */ protected int expectedModCount = AbstractPatriciaTrie.this.modCount; protected TrieEntry next; // the next node to return protected TrieEntry current; // the current entry we're on /** * Starts iteration from the root. */ protected TrieIterator() { next = AbstractPatriciaTrie.this.nextEntry(null); } /** * Starts iteration at the given entry. */ protected TrieIterator(final TrieEntry firstEntry) { next = firstEntry; } /** * Returns the next {@link TrieEntry}. */ protected TrieEntry nextEntry() { if (expectedModCount != AbstractPatriciaTrie.this.modCount) { throw new ConcurrentModificationException(); } final TrieEntry e = next; if (e == null) { throw new NoSuchElementException(); } next = findNext(e); current = e; return e; } /** * @see PatriciaTrie#nextEntry(TrieEntry) */ protected TrieEntry findNext(final TrieEntry prior) { return AbstractPatriciaTrie.this.nextEntry(prior); } public boolean hasNext() { return next != null; } public void remove() { if (current == null) { throw new IllegalStateException(); } if (expectedModCount != AbstractPatriciaTrie.this.modCount) { throw new ConcurrentModificationException(); } final TrieEntry node = current; current = null; AbstractPatriciaTrie.this.removeEntry(node); expectedModCount = AbstractPatriciaTrie.this.modCount; } } /** * An {@link OrderedMapIterator} for a {@link Trie}. */ private class TrieMapIterator extends TrieIterator implements OrderedMapIterator { protected TrieEntry previous; // the previous node to return public K next() { return nextEntry().getKey(); } public K getKey() { if (current == null) { throw new IllegalStateException(); } return current.getKey(); } public V getValue() { if (current == null) { throw new IllegalStateException(); } return current.getValue(); } public V setValue(final V value) { if (current == null) { throw new IllegalStateException(); } return current.setValue(value); } public boolean hasPrevious() { return previous != null; } public K previous() { return previousEntry().getKey(); } @Override protected TrieEntry nextEntry() { final TrieEntry nextEntry = super.nextEntry(); previous = nextEntry; return nextEntry; } protected TrieEntry previousEntry() { if (expectedModCount != AbstractPatriciaTrie.this.modCount) { throw new ConcurrentModificationException(); } final TrieEntry e = previous; if (e == null) { throw new NoSuchElementException(); } previous = AbstractPatriciaTrie.this.previousEntry(e); next = current; current = e; return current; } } /** * A range view of the {@link Trie}. */ private abstract class RangeMap extends AbstractMap implements SortedMap { /** The {@link #entrySet()} view. */ private transient volatile Set> entrySet; /** * Creates and returns an {@link #entrySet()} view of the {@link RangeMap}. */ protected abstract Set> createEntrySet(); /** * Returns the FROM Key. */ protected abstract K getFromKey(); /** * Whether or not the {@link #getFromKey()} is in the range. */ protected abstract boolean isFromInclusive(); /** * Returns the TO Key. */ protected abstract K getToKey(); /** * Whether or not the {@link #getToKey()} is in the range. */ protected abstract boolean isToInclusive(); public Comparator comparator() { return AbstractPatriciaTrie.this.comparator(); } @Override public boolean containsKey(final Object key) { if (!inRange(castKey(key))) { return false; } return AbstractPatriciaTrie.this.containsKey(key); } @Override public V remove(final Object key) { if (!inRange(castKey(key))) { return null; } return AbstractPatriciaTrie.this.remove(key); } @Override public V get(final Object key) { if (!inRange(castKey(key))) { return null; } return AbstractPatriciaTrie.this.get(key); } @Override public V put(final K key, final V value) { if (!inRange(key)) { throw new IllegalArgumentException("Key is out of range: " + key); } return AbstractPatriciaTrie.this.put(key, value); } @Override public Set> entrySet() { if (entrySet == null) { entrySet = createEntrySet(); } return entrySet; } public SortedMap subMap(final K fromKey, final K toKey) { if (!inRange2(fromKey)) { throw new IllegalArgumentException("FromKey is out of range: " + fromKey); } if (!inRange2(toKey)) { throw new IllegalArgumentException("ToKey is out of range: " + toKey); } return createRangeMap(fromKey, isFromInclusive(), toKey, isToInclusive()); } public SortedMap headMap(final K toKey) { if (!inRange2(toKey)) { throw new IllegalArgumentException("ToKey is out of range: " + toKey); } return createRangeMap(getFromKey(), isFromInclusive(), toKey, isToInclusive()); } public SortedMap tailMap(final K fromKey) { if (!inRange2(fromKey)) { throw new IllegalArgumentException("FromKey is out of range: " + fromKey); } return createRangeMap(fromKey, isFromInclusive(), getToKey(), isToInclusive()); } /** * Returns true if the provided key is greater than TO and less than FROM. */ protected boolean inRange(final K key) { final K fromKey = getFromKey(); final K toKey = getToKey(); return (fromKey == null || inFromRange(key, false)) && (toKey == null || inToRange(key, false)); } /** * This form allows the high endpoint (as well as all legit keys). */ protected boolean inRange2(final K key) { final K fromKey = getFromKey(); final K toKey = getToKey(); return (fromKey == null || inFromRange(key, false)) && (toKey == null || inToRange(key, true)); } /** * Returns true if the provided key is in the FROM range of the {@link RangeMap}. */ protected boolean inFromRange(final K key, final boolean forceInclusive) { final K fromKey = getFromKey(); final boolean fromInclusive = isFromInclusive(); final int ret = getKeyAnalyzer().compare(key, fromKey); if (fromInclusive || forceInclusive) { return ret >= 0; } else { return ret > 0; } } /** * Returns true if the provided key is in the TO range of the {@link RangeMap}. */ protected boolean inToRange(final K key, final boolean forceInclusive) { final K toKey = getToKey(); final boolean toInclusive = isToInclusive(); final int ret = getKeyAnalyzer().compare(key, toKey); if (toInclusive || forceInclusive) { return ret <= 0; } else { return ret < 0; } } /** * Creates and returns a sub-range view of the current {@link RangeMap}. */ protected abstract SortedMap createRangeMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive); } /** * A {@link RangeMap} that deals with {@link Entry}s. */ private class RangeEntryMap extends RangeMap { /** The key to start from, null if the beginning. */ private final K fromKey; /** The key to end at, null if till the end. */ private final K toKey; /** Whether or not the 'from' is inclusive. */ private final boolean fromInclusive; /** Whether or not the 'to' is inclusive. */ private final boolean toInclusive; /** * Creates a {@link RangeEntryMap} with the fromKey included and * the toKey excluded from the range. */ protected RangeEntryMap(final K fromKey, final K toKey) { this(fromKey, true, toKey, false); } /** * Creates a {@link RangeEntryMap}. */ protected RangeEntryMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { if (fromKey == null && toKey == null) { throw new IllegalArgumentException("must have a from or to!"); } if (fromKey != null && toKey != null && getKeyAnalyzer().compare(fromKey, toKey) > 0) { throw new IllegalArgumentException("fromKey > toKey"); } this.fromKey = fromKey; this.fromInclusive = fromInclusive; this.toKey = toKey; this.toInclusive = toInclusive; } public K firstKey() { Map.Entry e = null; if (fromKey == null) { e = firstEntry(); } else { if (fromInclusive) { e = ceilingEntry(fromKey); } else { e = higherEntry(fromKey); } } final K first = e != null ? e.getKey() : null; if (e == null || toKey != null && !inToRange(first, false)) { throw new NoSuchElementException(); } return first; } public K lastKey() { Map.Entry e; if (toKey == null) { e = lastEntry(); } else { if (toInclusive) { e = floorEntry(toKey); } else { e = lowerEntry(toKey); } } final K last = e != null ? e.getKey() : null; if (e == null || fromKey != null && !inFromRange(last, false)) { throw new NoSuchElementException(); } return last; } @Override protected Set> createEntrySet() { return new RangeEntrySet(this); } @Override public K getFromKey() { return fromKey; } @Override public K getToKey() { return toKey; } @Override public boolean isFromInclusive() { return fromInclusive; } @Override public boolean isToInclusive() { return toInclusive; } @Override protected SortedMap createRangeMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { return new RangeEntryMap(fromKey, fromInclusive, toKey, toInclusive); } } /** * A {@link Set} view of a {@link RangeMap}. */ private class RangeEntrySet extends AbstractSet> { private final RangeMap delegate; private transient int size = -1; private transient int expectedModCount; /** * Creates a {@link RangeEntrySet}. */ public RangeEntrySet(final RangeMap delegate) { if (delegate == null) { throw new NullPointerException("delegate"); } this.delegate = delegate; } @Override public Iterator> iterator() { final K fromKey = delegate.getFromKey(); final K toKey = delegate.getToKey(); TrieEntry first = null; if (fromKey == null) { first = firstEntry(); } else { first = ceilingEntry(fromKey); } TrieEntry last = null; if (toKey != null) { last = ceilingEntry(toKey); } return new EntryIterator(first, last); } @Override public int size() { if (size == -1 || expectedModCount != AbstractPatriciaTrie.this.modCount) { size = 0; for (final Iterator it = iterator(); it.hasNext(); it.next()) { ++size; } expectedModCount = AbstractPatriciaTrie.this.modCount; } return size; } @Override public boolean isEmpty() { return !iterator().hasNext(); } @SuppressWarnings("unchecked") @Override public boolean contains(final Object o) { if (!(o instanceof Map.Entry)) { return false; } final Map.Entry entry = (Map.Entry) o; final K key = entry.getKey(); if (!delegate.inRange(key)) { return false; } final TrieEntry node = getEntry(key); return node != null && compare(node.getValue(), entry.getValue()); } @SuppressWarnings("unchecked") @Override public boolean remove(final Object o) { if (!(o instanceof Map.Entry)) { return false; } final Map.Entry entry = (Map.Entry) o; final K key = entry.getKey(); if (!delegate.inRange(key)) { return false; } final TrieEntry node = getEntry(key); if (node != null && compare(node.getValue(), entry.getValue())) { removeEntry(node); return true; } return false; } /** * An {@link Iterator} for {@link RangeEntrySet}s. */ private final class EntryIterator extends TrieIterator> { private final K excludedKey; /** * Creates a {@link EntryIterator}. */ private EntryIterator(final TrieEntry first, final TrieEntry last) { super(first); this.excludedKey = last != null ? last.getKey() : null; } @Override public boolean hasNext() { return next != null && !compare(next.key, excludedKey); } public Map.Entry next() { if (next == null || compare(next.key, excludedKey)) { throw new NoSuchElementException(); } return nextEntry(); } } } /** * A submap used for prefix views over the {@link Trie}. */ private class PrefixRangeMap extends RangeMap { private final K prefix; private final int offsetInBits; private final int lengthInBits; private K fromKey = null; private K toKey = null; private transient int expectedModCount = 0; private int size = -1; /** * Creates a {@link PrefixRangeMap}. */ private PrefixRangeMap(final K prefix, final int offsetInBits, final int lengthInBits) { this.prefix = prefix; this.offsetInBits = offsetInBits; this.lengthInBits = lengthInBits; } /** * This method does two things. It determines the FROM * and TO range of the {@link PrefixRangeMap} and the number * of elements in the range. This method must be called every * time the {@link Trie} has changed. */ private int fixup() { // The trie has changed since we last found our toKey / fromKey if (size == - 1 || AbstractPatriciaTrie.this.modCount != expectedModCount) { final Iterator> it = super.entrySet().iterator(); size = 0; Map.Entry entry = null; if (it.hasNext()) { entry = it.next(); size = 1; } fromKey = entry == null ? null : entry.getKey(); if (fromKey != null) { final TrieEntry prior = previousEntry((TrieEntry)entry); fromKey = prior == null ? null : prior.getKey(); } toKey = fromKey; while (it.hasNext()) { ++size; entry = it.next(); } toKey = entry == null ? null : entry.getKey(); if (toKey != null) { entry = nextEntry((TrieEntry)entry); toKey = entry == null ? null : entry.getKey(); } expectedModCount = AbstractPatriciaTrie.this.modCount; } return size; } public K firstKey() { fixup(); Map.Entry e = null; if (fromKey == null) { e = firstEntry(); } else { e = higherEntry(fromKey); } final K first = e != null ? e.getKey() : null; if (e == null || !getKeyAnalyzer().isPrefix(prefix, offsetInBits, lengthInBits, first)) { throw new NoSuchElementException(); } return first; } public K lastKey() { fixup(); Map.Entry e = null; if (toKey == null) { e = lastEntry(); } else { e = lowerEntry(toKey); } final K last = e != null ? e.getKey() : null; if (e == null || !getKeyAnalyzer().isPrefix(prefix, offsetInBits, lengthInBits, last)) { throw new NoSuchElementException(); } return last; } /** * Returns true if this {@link PrefixRangeMap}'s key is a prefix of the provided key. */ @Override protected boolean inRange(final K key) { return getKeyAnalyzer().isPrefix(prefix, offsetInBits, lengthInBits, key); } /** * Same as {@link #inRange(Object)}. */ @Override protected boolean inRange2(final K key) { return inRange(key); } /** * Returns true if the provided Key is in the FROM range of the {@link PrefixRangeMap}. */ @Override protected boolean inFromRange(final K key, final boolean forceInclusive) { return getKeyAnalyzer().isPrefix(prefix, offsetInBits, lengthInBits, key); } /** * Returns true if the provided Key is in the TO range of the {@link PrefixRangeMap}. */ @Override protected boolean inToRange(final K key, final boolean forceInclusive) { return getKeyAnalyzer().isPrefix(prefix, offsetInBits, lengthInBits, key); } @Override protected Set> createEntrySet() { return new PrefixRangeEntrySet(this); } @Override public K getFromKey() { return fromKey; } @Override public K getToKey() { return toKey; } @Override public boolean isFromInclusive() { return false; } @Override public boolean isToInclusive() { return false; } @Override protected SortedMap createRangeMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { return new RangeEntryMap(fromKey, fromInclusive, toKey, toInclusive); } } /** * A prefix {@link RangeEntrySet} view of the {@link Trie}. */ private final class PrefixRangeEntrySet extends RangeEntrySet { private final PrefixRangeMap delegate; private TrieEntry prefixStart; private int expectedModCount = 0; /** * Creates a {@link PrefixRangeEntrySet}. */ public PrefixRangeEntrySet(final PrefixRangeMap delegate) { super(delegate); this.delegate = delegate; } @Override public int size() { return delegate.fixup(); } @Override public Iterator> iterator() { if (AbstractPatriciaTrie.this.modCount != expectedModCount) { prefixStart = subtree(delegate.prefix, delegate.offsetInBits, delegate.lengthInBits); expectedModCount = AbstractPatriciaTrie.this.modCount; } if (prefixStart == null) { final Set> empty = Collections.emptySet(); return empty.iterator(); } else if (delegate.lengthInBits >= prefixStart.bitIndex) { return new SingletonIterator(prefixStart); } else { return new EntryIterator(prefixStart, delegate.prefix, delegate.offsetInBits, delegate.lengthInBits); } } /** * An {@link Iterator} that holds a single {@link TrieEntry}. */ private final class SingletonIterator implements Iterator> { private final TrieEntry entry; private int hit = 0; public SingletonIterator(final TrieEntry entry) { this.entry = entry; } public boolean hasNext() { return hit == 0; } public Map.Entry next() { if (hit != 0) { throw new NoSuchElementException(); } ++hit; return entry; } public void remove() { if (hit != 1) { throw new IllegalStateException(); } ++hit; AbstractPatriciaTrie.this.removeEntry(entry); } } /** * An {@link Iterator} for iterating over a prefix search. */ private final class EntryIterator extends TrieIterator> { // values to reset the subtree if we remove it. private final K prefix; private final int offset; private final int lengthInBits; private boolean lastOne; private TrieEntry subtree; // the subtree to search within /** * Starts iteration at the given entry & search only * within the given subtree. */ EntryIterator(final TrieEntry startScan, final K prefix, final int offset, final int lengthInBits) { subtree = startScan; next = AbstractPatriciaTrie.this.followLeft(startScan); this.prefix = prefix; this.offset = offset; this.lengthInBits = lengthInBits; } public Map.Entry next() { final Map.Entry entry = nextEntry(); if (lastOne) { next = null; } return entry; } @Override protected TrieEntry findNext(final TrieEntry prior) { return AbstractPatriciaTrie.this.nextEntryInSubtree(prior, subtree); } @Override public void remove() { // If the current entry we're removing is the subtree // then we need to find a new subtree parent. boolean needsFixing = false; final int bitIdx = subtree.bitIndex; if (current == subtree) { needsFixing = true; } super.remove(); // If the subtree changed its bitIndex or we // removed the old subtree, get a new one. if (bitIdx != subtree.bitIndex || needsFixing) { subtree = subtree(prefix, offset, lengthInBits); } // If the subtree's bitIndex is less than the // length of our prefix, it's the last item // in the prefix tree. if (lengthInBits >= subtree.bitIndex) { lastOne = true; } } } } //----------------------------------------------------------------------- /** * Reads the content of the stream. */ @SuppressWarnings("unchecked") // This will fail at runtime if the stream is incorrect private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException{ stream.defaultReadObject(); root = new TrieEntry(null, null, -1); int size = stream.readInt(); for(int i = 0; i < size; i++){ K k = (K) stream.readObject(); V v = (V) stream.readObject(); put(k, v); } } /** * Writes the content to the stream for serialization. */ private void writeObject(final ObjectOutputStream stream) throws IOException{ stream.defaultWriteObject(); stream.writeInt(this.size()); for (final Entry entry : entrySet()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/trie/PatriciaTrie.java100664 6166 12243235516 31135 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.trie; import java.util.Map; import org.apache.commons.collections4.trie.analyzer.StringKeyAnalyzer; /** * Implementation of a PATRICIA Trie (Practical Algorithm to Retrieve Information * Coded in Alphanumeric). *

* A PATRICIA {@link Trie} is a compressed {@link Trie}. Instead of storing * all data at the edges of the {@link Trie} (and having empty internal nodes), * PATRICIA stores data in every node. This allows for very efficient traversal, * insert, delete, predecessor, successor, prefix, range, and {@link #select(Object)} * operations. All operations are performed at worst in O(K) time, where K * is the number of bits in the largest item in the tree. In practice, * operations actually take O(A(K)) time, where A(K) is the average number of * bits of all items in the tree. *

* Most importantly, PATRICIA requires very few comparisons to keys while * doing any operation. While performing a lookup, each comparison (at most * K of them, described above) will perform a single bit comparison against * the given key, instead of comparing the entire key to another key. *

* The {@link Trie} can return operations in lexicographical order using the * 'prefixMap', 'submap', or 'iterator' methods. The {@link Trie} can also * scan for items that are 'bitwise' (using an XOR metric) by the 'select' method. * Bitwise closeness is determined by the {@link KeyAnalyzer} returning true or * false for a bit being set or not in a given key. *

* This PATRICIA {@link Trie} supports both variable length & fixed length * keys. Some methods, such as {@link #prefixMap(Object)} are suited only * to variable length keys. * * @see Radix Tree * @see PATRICIA * @see Crit-Bit Tree * @since 4.0 * @version $Id: PatriciaTrie.java 1543928 2013-11-20 20:15:35Z tn $ */ public class PatriciaTrie extends AbstractPatriciaTrie { private static final long serialVersionUID = 4446367780901817838L; public PatriciaTrie() { super(new StringKeyAnalyzer()); } public PatriciaTrie(final Map m) { super(new StringKeyAnalyzer(), m); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/Put.java100664 3431 12243235516 26352 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Map; /** * The "write" subset of the {@link Map} interface. *

* NOTE: in the original {@link Map} interface, {@link Map#put(Object, Object)} is known * to have the same return type as {@link Map#get(Object)}, namely {@code V}. {@link Put} * makes no assumptions in this regard (there is no association with, nor even knowledge * of, a "reading" interface) and thus defines {@link #put(Object, Object)} as returning * {@link Object}. * * @since 4.0 * @version $Id: Put.java 1543257 2013-11-19 00:45:55Z ggregory $ * * @see Get */ public interface Put { /** * @see Map#clear() */ void clear(); /** * Note that the return type is Object, rather than V as in the Map interface. * See the class Javadoc for further info. * * @see Map#put(Object, Object) */ Object put(K key, V value); /** * @see Map#putAll(Map) */ void putAll(Map t); } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/UnmodifiableCollection.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/UnmodifiableCo100664 7352 12243235516 31703 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableIterator; /** * Decorates another {@link Collection} to ensure it can't be altered. *

* This class is Serializable from Commons Collections 3.1. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @param the type of the elements in the collection * @since 3.0 * @version $Id: UnmodifiableCollection.java 1533984 2013-10-20 21:12:51Z tn $ */ public final class UnmodifiableCollection extends AbstractCollectionDecorator 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 the type of the elements in the collection * @param coll the collection to decorate, must not be null * @return an unmodifiable collection * @throws IllegalArgumentException if collection is null * @since 4.0 */ public static Collection unmodifiableCollection(final Collection coll) { if (coll instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final Collection tmpColl = (Collection) coll; return tmpColl; } 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 */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableCollection(final Collection coll) { super((Collection) coll); } //----------------------------------------------------------------------- @Override public Iterator iterator() { return UnmodifiableIterator.unmodifiableIterator(decorated().iterator()); } @Override public boolean add(final E object) { throw new UnsupportedOperationException(); } @Override public boolean addAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException(); } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/IndexedCollection.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/IndexedCollect100664 21111 12243235516 31716 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.Collection; import java.util.HashMap; import org.apache.commons.collections4.MultiMap; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.map.MultiValueMap; /** * An IndexedCollection is a Map-like view onto a Collection. It accepts a * keyTransformer to define how the keys are converted from the values. *

* Modifications made to this decorator modify the index as well as the * decorated {@link Collection}. However, modifications to the underlying * {@link Collection} will not update the index and it will get out of sync. *

* If modification of the decorated {@link Collection} is unavoidable, then a * call to {@link #reindex()} will update the index to the current contents of * the {@link Collection}. * * @param the type of object in the index. * @param the type of object in the collection. * * @since 4.0 * @version $Id: IndexedCollection.java 1543740 2013-11-20 09:33:14Z ebourg $ */ public class IndexedCollection extends AbstractCollectionDecorator { /** Serialization version */ private static final long serialVersionUID = -5512610452568370038L; /** The {@link Transformer} for generating index keys. */ private final Transformer keyTransformer; /** The map of indexes to collected objects. */ private final MultiMap index; /** The uniqueness constraint for the index. */ private final boolean uniqueIndex; /** * Create an {@link IndexedCollection} for a unique index. *

* If an element is added, which maps to an existing key, an {@link IllegalArgumentException} * will be thrown. * * @param the index object type. * @param the collection type. * @param coll the decorated {@link Collection}. * @param keyTransformer the {@link Transformer} for generating index keys. * @return the created {@link IndexedCollection}. */ public static IndexedCollection uniqueIndexedCollection(final Collection coll, final Transformer keyTransformer) { return new IndexedCollection(coll, keyTransformer, MultiValueMap.multiValueMap(new HashMap>()), true); } /** * Create an {@link IndexedCollection} for a non-unique index. * * @param the index object type. * @param the collection type. * @param coll the decorated {@link Collection}. * @param keyTransformer the {@link Transformer} for generating index keys. * @return the created {@link IndexedCollection}. */ public static IndexedCollection nonUniqueIndexedCollection(final Collection coll, final Transformer keyTransformer) { return new IndexedCollection(coll, keyTransformer, MultiValueMap.multiValueMap(new HashMap>()), false); } /** * Create a {@link IndexedCollection}. * * @param coll decorated {@link Collection} * @param keyTransformer {@link Transformer} for generating index keys * @param map map to use as index * @param uniqueIndex if the index shall enforce uniqueness of index keys */ public IndexedCollection(final Collection coll, final Transformer keyTransformer, final MultiMap map, final boolean uniqueIndex) { super(coll); this.keyTransformer = keyTransformer; this.index = map; this.uniqueIndex = uniqueIndex; reindex(); } /** * {@inheritDoc} * * @throws IllegalArgumentException if the object maps to an existing key and the index * enforces a uniqueness constraint */ @Override public boolean add(final C object) { final boolean added = super.add(object); if (added) { addToIndex(object); } return added; } @Override public boolean addAll(final Collection coll) { boolean changed = false; for (final C c: coll) { changed |= add(c); } return changed; } @Override public void clear() { super.clear(); index.clear(); } /** * {@inheritDoc} *

* Note: uses the index for fast lookup */ @SuppressWarnings("unchecked") @Override public boolean contains(final Object object) { return index.containsKey(keyTransformer.transform((C) object)); } /** * {@inheritDoc} *

* Note: uses the index for fast lookup */ @Override public boolean containsAll(final Collection coll) { for (final Object o : coll) { if (!contains(o)) { return false; } } return true; } /** * Get the element associated with the given key. *

* In case of a non-unique index, this method will return the first * value associated with the given key. To retrieve all elements associated * with a key, use {@link #values(Object)}. * * @param key key to look up * @return element found * @see #values(Object) */ public C get(final K key) { @SuppressWarnings("unchecked") // index is a MultiMap which returns a Collection final Collection coll = (Collection) index.get(key); return coll == null ? null : coll.iterator().next(); } /** * Get all elements associated with the given key. * * @param key key to look up * @return a collection of elements found, or null if {@code contains(key) == false} */ @SuppressWarnings("unchecked") // index is a MultiMap which returns a Collection public Collection values(final K key) { return (Collection) index.get(key); } /** * Clears the index and re-indexes the entire decorated {@link Collection}. */ public void reindex() { index.clear(); for (final C c : decorated()) { addToIndex(c); } } @SuppressWarnings("unchecked") @Override public boolean remove(final Object object) { final boolean removed = super.remove(object); if (removed) { removeFromIndex((C) object); } return removed; } @Override public boolean removeAll(final Collection coll) { boolean changed = false; for (final Object o : coll) { changed |= remove(o); } return changed; } @Override public boolean retainAll(final Collection coll) { final boolean changed = super.retainAll(coll); if (changed) { reindex(); } return changed; } //----------------------------------------------------------------------- /** * Provides checking for adding the index. * * @param object the object to index * @throws IllegalArgumentException if the object maps to an existing key and the index * enforces a uniqueness constraint */ private void addToIndex(final C object) { final K key = keyTransformer.transform(object); if (uniqueIndex && index.containsKey(key)) { throw new IllegalArgumentException("Duplicate key in uniquely indexed collection."); } index.put(key, object); } /** * Removes an object from the index. * * @param object the object to remove */ private void removeFromIndex(final C object) { index.remove(keyTransformer.transform(object)); } } ././@LongLink100644 0 0 171 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/UnmodifiableBoundedCollection.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/UnmodifiableBo100664 13632 12243235516 31720 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.Collection; import java.util.Iterator; import org.apache.commons.collections4.BoundedCollection; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableIterator; /** * {@link UnmodifiableBoundedCollection} decorates another * {@link 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. *

* Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableBoundedCollection.java 1540766 2013-11-11 16:47:20Z tn $ */ public final class UnmodifiableBoundedCollection extends AbstractCollectionDecorator implements BoundedCollection, Unmodifiable { /** Serialization version */ private static final long serialVersionUID = -7112672385450340330L; /** * Factory method to create an unmodifiable bounded collection. * * @param the type of the elements in the collection * @param coll the BoundedCollection to decorate, must not be null * @return a new unmodifiable bounded collection * @throws IllegalArgumentException if {@code coll} is {@code null} * @since 4.0 */ public static BoundedCollection unmodifiableBoundedCollection(final BoundedCollection coll) { if (coll instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final BoundedCollection tmpColl = (BoundedCollection) coll; return tmpColl; } 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 the type of the elements in the collection * @param coll the BoundedCollection to decorate, must not be null * @return a new unmodifiable bounded collection * @throws IllegalArgumentException if {@code coll} is {@code null} * @since 4.0 */ @SuppressWarnings("unchecked") public static BoundedCollection unmodifiableBoundedCollection(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 } if (coll instanceof AbstractCollectionDecorator) { coll = ((AbstractCollectionDecorator) coll).decorated(); } else if (coll instanceof SynchronizedCollection) { coll = ((SynchronizedCollection) coll).decorated(); } } 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 */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableBoundedCollection(final BoundedCollection coll) { super((BoundedCollection) coll); } //----------------------------------------------------------------------- @Override public Iterator iterator() { return UnmodifiableIterator.unmodifiableIterator(decorated().iterator()); } @Override public boolean add(final E object) { throw new UnsupportedOperationException(); } @Override public boolean addAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- public boolean isFull() { return decorated().isFull(); } public int maxSize() { return decorated().maxSize(); } @Override protected BoundedCollection decorated() { return (BoundedCollection) super.decorated(); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/package-info.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/package-info.j100664 3200 12243235516 31563 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This 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 *
  • Transformed - transforms elements as they are added *
  • Indexed - provides a map-like view onto another collection *
* * @version $Id: package-info.java 1477746 2013-04-30 18:11:20Z tn $ */ package org.apache.commons.collections4.collection; ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/CompositeCollection.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/CompositeColle100664 41371 12243235516 31763 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.io.Serializable; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.apache.commons.collections4.iterators.EmptyIterator; import org.apache.commons.collections4.iterators.IteratorChain; import org.apache.commons.collections4.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. * * @param the type of the elements in the collection * @since 3.0 * @version $Id: CompositeCollection.java 1543268 2013-11-19 00:49:59Z ggregory $ */ public class CompositeCollection implements Collection, Serializable { /** Serialization version */ private static final long serialVersionUID = 8417515734108306801L; /** CollectionMutator to handle changes to the collection */ private CollectionMutator mutator; /** Collections in the composite */ private final List> all = new ArrayList>(); /** * Create an empty CompositeCollection. */ public CompositeCollection() { super(); } /** * Create a Composite Collection with one collection. * * @param compositeCollection the Collection to be appended to the composite */ public CompositeCollection(final Collection compositeCollection) { super(); addComposited(compositeCollection); } /** * Create a Composite Collection with two collections. * * @param compositeCollection1 the Collection to be appended to the composite * @param compositeCollection2 the Collection to be appended to the composite */ public CompositeCollection(final Collection compositeCollection1, final Collection compositeCollection2) { super(); addComposited(compositeCollection1, compositeCollection2); } /** * Create a Composite Collection with an array of collections. * * @param compositeCollections the collections to composite */ public CompositeCollection(final Collection... compositeCollections) { super(); addComposited(compositeCollections); } //----------------------------------------------------------------------- /** * 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 (final Collection item : all) { size += item.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 (final Collection item : all) { if (item.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(final Object obj) { for (final Collection item : all) { if (item.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 (all.isEmpty()) { return EmptyIterator.emptyIterator(); } final IteratorChain chain = new IteratorChain(); for (final Collection item : all) { chain.addIterator(item.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[size()]; int i = 0; for (final Iterator it = 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 the type of the elements in the collection * @param array the array to use, populating if possible * @return an array of all the elements in the collection */ @SuppressWarnings("unchecked") public T[] toArray(final T[] array) { final int size = size(); Object[] result = null; if (array.length >= size) { result = array; } else { result = (Object[]) Array.newInstance(array.getClass().getComponentType(), size); } int offset = 0; for (final Collection item : all) { for (final E e : item) { result[offset++] = e; } } if (result.length > size) { result[size] = null; } return (T[]) result; } /** * Adds an object to the collection, throwing UnsupportedOperationException * unless a CollectionMutator strategy is specified. * * @param obj the object to add * @return {@code 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(final E obj) { if (mutator == null) { throw new UnsupportedOperationException( "add() is not supported on CompositeCollection without a CollectionMutator strategy"); } return mutator.add(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(final Object obj) { if (mutator == null) { throw new UnsupportedOperationException( "remove() is not supported on CompositeCollection without a CollectionMutator strategy"); } return mutator.remove(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(final Collection coll) { for (final Object item : coll) { if (contains(item) == 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(final Collection coll) { if (mutator == null) { throw new UnsupportedOperationException( "addAll() is not supported on CompositeCollection without a CollectionMutator strategy"); } return mutator.addAll(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(final Collection coll) { if (coll.size() == 0) { return false; } boolean changed = false; for (final Collection item : all) { changed |= item.removeAll(coll); } 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 (final Collection item : all) { changed |= item.retainAll(coll); } 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 (final Collection coll : all) { coll.clear(); } } //----------------------------------------------------------------------- /** * Specify a CollectionMutator strategy instance to handle changes. * * @param mutator the mutator to use */ public void setMutator(final CollectionMutator mutator) { this.mutator = mutator; } /** * Add these Collections to the list of collections in this composite * * @param compositeCollection the Collection to be appended to the composite */ public void addComposited(final Collection compositeCollection) { all.add(compositeCollection); } /** * Add these Collections to the list of collections in this composite * * @param compositeCollection1 the Collection to be appended to the composite * @param compositeCollection2 the Collection to be appended to the composite */ public void addComposited(final Collection compositeCollection1, final Collection compositeCollection2) { all.add(compositeCollection1); all.add(compositeCollection2); } /** * Add these Collections to the list of collections in this composite * * @param compositeCollections the Collections to be appended to the composite */ public void addComposited(final Collection... compositeCollections) { all.addAll(Arrays.asList(compositeCollections)); } /** * Removes a collection from the those being decorated in this composite. * * @param coll collection to be removed */ public void removeComposited(final Collection coll) { all.remove(coll); } //----------------------------------------------------------------------- /** * 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 list of all collections in this composite. */ public List> getCollections() { return UnmodifiableList.unmodifiableList(all); } /** * Get the collection mutator to be used for this CompositeCollection. * @return CollectionMutator */ protected CollectionMutator getMutator() { return mutator; } //----------------------------------------------------------------------- /** * Pluggable strategy to handle changes to the composite. * * @param the element being held in the collection */ public interface CollectionMutator extends Serializable { /** * 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 */ boolean add(CompositeCollection composite, List> collections, E 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 */ boolean addAll(CompositeCollection composite, List> 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 */ boolean remove(CompositeCollection composite, List> collections, Object obj); } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/SynchronizedCollection.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/SynchronizedCo100664 14057 12243235516 32004 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; /** * Decorates another {@link 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. * * @param the type of the elements in the collection * @since 3.0 * @version $Id: SynchronizedCollection.java 1479401 2013-05-05 21:51:47Z tn $ */ public class SynchronizedCollection implements Collection, Serializable { /** Serialization version */ private static final long serialVersionUID = 2412805092710877986L; /** The collection to decorate */ private 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 the type of the elements in the collection * @param coll the collection to decorate, must not be null * @return a new synchronized collection * @throws IllegalArgumentException if collection is null * @since 4.0 */ public static SynchronizedCollection synchronizedCollection(final 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(final 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(final Collection collection, final Object lock) { if (collection == null) { throw new IllegalArgumentException("Collection must not be null"); } this.collection = collection; this.lock = lock; } /** * Gets the collection being decorated. * * @return the decorated collection */ protected Collection decorated() { return collection; } //----------------------------------------------------------------------- public boolean add(final E object) { synchronized (lock) { return decorated().add(object); } } public boolean addAll(final Collection coll) { synchronized (lock) { return decorated().addAll(coll); } } public void clear() { synchronized (lock) { decorated().clear(); } } public boolean contains(final Object object) { synchronized (lock) { return decorated().contains(object); } } public boolean containsAll(final Collection coll) { synchronized (lock) { return decorated().containsAll(coll); } } public boolean isEmpty() { synchronized (lock) { return decorated().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 decorated().iterator(); } public Object[] toArray() { synchronized (lock) { return decorated().toArray(); } } public T[] toArray(final T[] object) { synchronized (lock) { return decorated().toArray(object); } } public boolean remove(final Object object) { synchronized (lock) { return decorated().remove(object); } } public boolean removeAll(final Collection coll) { synchronized (lock) { return decorated().removeAll(coll); } } public boolean retainAll(final Collection coll) { synchronized (lock) { return decorated().retainAll(coll); } } public int size() { synchronized (lock) { return decorated().size(); } } @Override public boolean equals(final Object object) { synchronized (lock) { if (object == this) { return true; } return object == this || decorated().equals(object); } } @Override public int hashCode() { synchronized (lock) { return decorated().hashCode(); } } @Override public String toString() { synchronized (lock) { return decorated().toString(); } } } ././@LongLink100644 0 0 167 12243235652 10263 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/AbstractCollectionDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/AbstractCollec100664 11514 12243235516 31723 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.io.Serializable; 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. * * @param the type of the elements in the collection * @since 3.0 * @version $Id: AbstractCollectionDecorator.java 1494280 2013-06-18 20:07:04Z tn $ */ public abstract class AbstractCollectionDecorator implements Collection, Serializable { /** Serialization version */ private static final long serialVersionUID = 6249888059822088500L; /** The collection being decorated */ private Collection collection; /** * Constructor only used in deserialization, do not use otherwise. * @since 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(final Collection coll) { if (coll == null) { throw new IllegalArgumentException("Collection must not be null"); } this.collection = coll; } /** * Gets the collection being decorated. * All access to the decorated collection goes via this method. * * @return the decorated collection */ protected Collection decorated() { return collection; } /** * Sets the collection being decorated. *

* NOTE: this method should only be used during deserialization * * @param coll the decorated collection */ protected void setCollection(final Collection coll) { this.collection = coll; } //----------------------------------------------------------------------- public boolean add(final E object) { return decorated().add(object); } public boolean addAll(final Collection coll) { return decorated().addAll(coll); } public void clear() { decorated().clear(); } public boolean contains(final Object object) { return decorated().contains(object); } public boolean isEmpty() { return decorated().isEmpty(); } public Iterator iterator() { return decorated().iterator(); } public boolean remove(final Object object) { return decorated().remove(object); } public int size() { return decorated().size(); } public Object[] toArray() { return decorated().toArray(); } public T[] toArray(final T[] object) { return decorated().toArray(object); } public boolean containsAll(final Collection coll) { return decorated().containsAll(coll); } public boolean removeAll(final Collection coll) { return decorated().removeAll(coll); } public boolean retainAll(final Collection coll) { return decorated().retainAll(coll); } @Override public boolean equals(final Object object) { return object == this || decorated().equals(object); } @Override public int hashCode() { return decorated().hashCode(); } @Override public String toString() { return decorated().toString(); } } ././@LongLink100644 0 0 161 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/TransformedCollection.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/TransformedCol100664 13740 12243235516 31763 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.collections4.Transformer; /** * Decorates another {@link 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. * * @param the type of the elements in the collection * @since 3.0 * @version $Id: TransformedCollection.java 1479401 2013-05-05 21:51:47Z tn $ */ public class TransformedCollection extends AbstractCollectionDecorator { /** 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. * Contrast this with {@link #transformedCollection(Collection, Transformer)}. * * @param the type of the elements in the collection * @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 * @since 4.0 */ public static TransformedCollection transformingCollection(final Collection coll, final Transformer transformer) { return new TransformedCollection(coll, transformer); } /** * Factory method to create a transforming collection that will transform * existing contents of the specified collection. *

* If there are any elements already in the collection being decorated, they * will be transformed by this method. * Contrast this with {@link #transformingCollection(Collection, Transformer)}. * * @param the type of the elements in the collection * @param collection 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 * @since 4.0 */ public static TransformedCollection transformedCollection(final Collection collection, final Transformer transformer) { final TransformedCollection decorated = new TransformedCollection(collection, transformer); // null collection & transformer are disallowed by the constructor call above if (collection.size() > 0) { @SuppressWarnings("unchecked") // collection is of type E final E[] values = (E[]) collection.toArray(); // NOPMD - false positive for generics collection.clear(); for (final E value : values) { decorated.decorated().add(transformer.transform(value)); } } return decorated; } //----------------------------------------------------------------------- /** * 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(final Collection coll, final 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 E transform(final E 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(final Collection coll) { final List list = new ArrayList(coll.size()); for (final E item : coll) { list.add(transform(item)); } return list; } //----------------------------------------------------------------------- @Override public boolean add(final E object) { return decorated().add(transform(object)); } @Override public boolean addAll(final Collection coll) { return decorated().addAll(transform(coll)); } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/PredicatedCollection.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/collection/PredicatedColl100664 12552 12243235516 31717 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.collection; import java.util.Collection; import org.apache.commons.collections4.Predicate; /** * Decorates another {@link 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. * * @param the type of the elements in the collection * @since 3.0 * @version $Id: PredicatedCollection.java 1479401 2013-05-05 21:51:47Z tn $ */ public class PredicatedCollection extends AbstractCollectionDecorator { /** 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 the type of the elements in the collection * @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 * @since 4.0 */ public static PredicatedCollection predicatedCollection(final Collection coll, final 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(final Collection coll, final Predicate predicate) { super(coll); if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } this.predicate = predicate; for (final E item : coll) { validate(item); } } /** * 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(final E object) { if (predicate.evaluate(object) == false) { throw new IllegalArgumentException("Cannot add Object '" + object + "' - Predicate '" + 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 */ @Override public boolean add(final E object) { validate(object); return decorated().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 */ @Override public boolean addAll(final Collection coll) { for (final E item : coll) { validate(item); } return decorated().addAll(coll); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/TransformerUtils.java100664 46624 12243235516 31160 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Collection; import java.util.Map; import org.apache.commons.collections4.functors.ChainedTransformer; import org.apache.commons.collections4.functors.CloneTransformer; import org.apache.commons.collections4.functors.ClosureTransformer; import org.apache.commons.collections4.functors.ConstantTransformer; import org.apache.commons.collections4.functors.EqualPredicate; import org.apache.commons.collections4.functors.ExceptionTransformer; import org.apache.commons.collections4.functors.FactoryTransformer; import org.apache.commons.collections4.functors.InstantiateTransformer; import org.apache.commons.collections4.functors.InvokerTransformer; import org.apache.commons.collections4.functors.MapTransformer; import org.apache.commons.collections4.functors.NOPTransformer; import org.apache.commons.collections4.functors.PredicateTransformer; import org.apache.commons.collections4.functors.StringValueTransformer; import org.apache.commons.collections4.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 3.0 * @version $Id: TransformerUtils.java 1479347 2013-05-05 16:01:15Z tn $ */ public class TransformerUtils { /** * This class is not normally instantiated. */ private TransformerUtils() {} /** * Gets a transformer that always throws an exception. * This could be useful during testing as a placeholder. * * @param the input type * @param the output type * @return the transformer * @see org.apache.commons.collections4.functors.ExceptionTransformer */ public static Transformer exceptionTransformer() { return ExceptionTransformer.exceptionTransformer(); } /** * Gets a transformer that always returns null. * * @param the input type * @param the output type * @return the transformer * @see org.apache.commons.collections4.functors.ConstantTransformer */ public static Transformer nullTransformer() { return ConstantTransformer.nullTransformer(); } /** * 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). * * @param the input/output type * @return the transformer * @see org.apache.commons.collections4.functors.NOPTransformer */ public static Transformer nopTransformer() { return NOPTransformer.nopTransformer(); } /** * 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 *
      * * @param the input/output type * @return the transformer * @see org.apache.commons.collections4.functors.CloneTransformer */ public static Transformer cloneTransformer() { return CloneTransformer.cloneTransformer(); } /** * Creates a Transformer that will return the same object each time the * transformer is used. * * @param the input type * @param the output type * @param constantToReturn the constant object to return each time in the transformer * @return the transformer. * @see org.apache.commons.collections4.functors.ConstantTransformer */ public static Transformer constantTransformer(final O constantToReturn) { return ConstantTransformer.constantTransformer(constantToReturn); } /** * Creates a Transformer that calls a Closure each time the transformer is used. * The transformer returns the input object. * * @param the input/output type * @param closure the closure to run each time in the transformer, not null * @return the transformer * @throws IllegalArgumentException if the closure is null * @see org.apache.commons.collections4.functors.ClosureTransformer */ public static Transformer asTransformer(final Closure closure) { return ClosureTransformer.closureTransformer(closure); } /** * Creates a Transformer that calls a Predicate each time the transformer is used. * The transformer will return either Boolean.TRUE or Boolean.FALSE. * * @param the input type * @param predicate the predicate to run each time in the transformer, not null * @return the transformer * @throws IllegalArgumentException if the predicate is null * @see org.apache.commons.collections4.functors.PredicateTransformer */ public static Transformer asTransformer(final Predicate predicate) { return PredicateTransformer.predicateTransformer(predicate); } /** * Creates a Transformer that calls a Factory each time the transformer is used. * The transformer will return the value returned by the factory. * * @param the input type * @param the output type * @param factory the factory to run each time in the transformer, not null * @return the transformer * @throws IllegalArgumentException if the factory is null * @see org.apache.commons.collections4.functors.FactoryTransformer */ public static Transformer asTransformer(final Factory factory) { return FactoryTransformer.factoryTransformer(factory); } /** * Create a new Transformer that calls each transformer in turn, passing the * result into the next transformer. * * @param the input/output type * @param transformers an array of transformers to chain * @return the transformer * @throws IllegalArgumentException if the transformers array or any of the transformers is null * @see org.apache.commons.collections4.functors.ChainedTransformer */ public static Transformer chainedTransformer( final Transformer... transformers) { return ChainedTransformer.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 the input/output type * @param transformers a collection of transformers to chain * @return the transformer * @throws IllegalArgumentException if the transformers collection or any of the transformers is null * @see org.apache.commons.collections4.functors.ChainedTransformer */ public static Transformer chainedTransformer( final Collection> transformers) { return ChainedTransformer.chainedTransformer(transformers); } /** * Create a new Transformer that calls one of two transformers depending * on the specified predicate. * * @param the input type * @param the output type * @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 either the predicate or transformer is null * @see org.apache.commons.collections4.functors.SwitchTransformer */ @SuppressWarnings("unchecked") public static Transformer switchTransformer(final Predicate predicate, final Transformer trueTransformer, final Transformer falseTransformer) { return SwitchTransformer.switchTransformer(new Predicate[] { predicate }, new Transformer[] { trueTransformer }, falseTransformer); } /** * Create a new Transformer that calls one of the transformers depending * on the predicates. The transformer at array location 0 is called if the * predicate at array location 0 returned true. Each predicate is evaluated * until one returns true. If no predicates evaluate to true, null is returned. * * @param the input type * @param the output type * @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 or empty * @throws IllegalArgumentException if any element in the arrays is null * @throws IllegalArgumentException if the arrays are different sizes * @see org.apache.commons.collections4.functors.SwitchTransformer */ public static Transformer switchTransformer(final Predicate[] predicates, final Transformer[] transformers) { return SwitchTransformer.switchTransformer(predicates, transformers, null); } /** * Create a new Transformer that calls one of the transformers depending * on the predicates. The transformer at array location 0 is called if the * predicate at array location 0 returned true. Each predicate is evaluated * until one returns true. If no predicates evaluate to true, the default * transformer is called. If the default transformer is null, null is returned. * * @param the input type * @param the output type * @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 or empty * @throws IllegalArgumentException if any element in the arrays is null * @throws IllegalArgumentException if the arrays are different sizes * @see org.apache.commons.collections4.functors.SwitchTransformer */ public static Transformer switchTransformer(final Predicate[] predicates, final Transformer[] transformers, final Transformer defaultTransformer) { return SwitchTransformer.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. If no default transformer is set, null will be returned in a default * case. The ordering is that of the iterator() method on the entryset collection * of the map. * * @param the input type * @param the output type * @param predicatesAndTransformers a map of predicates to transformers * @return the transformer * @throws IllegalArgumentException if the map is null or empty * @throws IllegalArgumentException if any transformer in the map is null * @throws ClassCastException if the map elements are of the wrong type * @see org.apache.commons.collections4.functors.SwitchTransformer */ public static Transformer switchTransformer( final Map, Transformer> predicatesAndTransformers) { return SwitchTransformer.switchTransformer(predicatesAndTransformers); } /** * Create a new Transformer that uses the input object as a key to find the * transformer to call. *

      * The Map consists of object keys and Transformer values. A transformer * is called if the input object equals the key. If there is no match, the * default transformer is called. The default transformer is set in the map * using a null key. If no default is set, null will be returned in a default case. * * @param the input type * @param the output type * @param objectsAndTransformers a map of objects to transformers * @return the transformer * @throws IllegalArgumentException if the map is null or empty * @throws IllegalArgumentException if any transformer in the map is null * @see org.apache.commons.collections4.functors.SwitchTransformer */ @SuppressWarnings("unchecked") public static Transformer switchMapTransformer( final Map> objectsAndTransformers) { if (objectsAndTransformers == null) { throw new IllegalArgumentException("The object and transformer map must not be null"); } final Transformer def = objectsAndTransformers.remove(null); final int size = objectsAndTransformers.size(); final Transformer[] trs = new Transformer[size]; final Predicate[] preds = new Predicate[size]; int i = 0; for (final Map.Entry> entry : objectsAndTransformers.entrySet()) { preds[i] = EqualPredicate.equalPredicate(entry.getKey()); trs[i++] = entry.getValue(); } return TransformerUtils.switchTransformer(preds, trs, def); } /** * Gets a Transformer that expects an input Class object that it will instantiate. * * @param the output type * @return the transformer * @see org.apache.commons.collections4.functors.InstantiateTransformer */ public static Transformer, T> instantiateTransformer() { return InstantiateTransformer.instantiateTransformer(); } /** * Creates a Transformer that expects an input Class object that it will * instantiate. The constructor used is determined by the arguments specified * to this method. * * @param the output type * @param paramTypes parameter types for the constructor, can be null * @param args the arguments to pass to the constructor, can be null * @return the transformer * @throws IllegalArgumentException if the paramTypes and args don't match * @see org.apache.commons.collections4.functors.InstantiateTransformer */ public static Transformer, T> instantiateTransformer( final Class[] paramTypes, final Object[] args) { return InstantiateTransformer.instantiateTransformer(paramTypes, args); } /** * Creates a Transformer that uses the passed in Map to transform the input * object (as a simple lookup). * * @param the input type * @param the output type * @param map the map to use to transform the objects * @return the transformer, or a {@link ConstantTransformer#NULL_INSTANCE} if the {@code map} is {@code null} * @see org.apache.commons.collections4.functors.MapTransformer */ public static Transformer mapTransformer(final Map map) { return MapTransformer.mapTransformer(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. * * @param the input type * @param the output type * @param methodName the method name to call on the input object, may not be null * @return the transformer * @throws IllegalArgumentException if the methodName is null. * @see org.apache.commons.collections4.functors.InvokerTransformer */ public static Transformer invokerTransformer(final String methodName) { return InvokerTransformer.invokerTransformer(methodName, null, null); } /** * Gets a Transformer that invokes a method on the input object. * The method parameters are specified. If the input object is {@code null}, * {@code null} is returned. * * @param the input type * @param the output type * @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 or the paramTypes and args don't match * @see org.apache.commons.collections4.functors.InvokerTransformer */ public static Transformer invokerTransformer(final String methodName, final Class[] paramTypes, final Object[] args) { return InvokerTransformer.invokerTransformer(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'. * * @param the input type * @return the transformer * @see org.apache.commons.collections4.functors.StringValueTransformer */ public static Transformer stringValueTransformer() { return StringValueTransformer.stringValueTransformer(); } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractEmptyMapIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractEmptyMa100664 3036 12243235516 31737 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; /** * Provides an implementation of an empty map iterator. * * @since 4.0 * @version $Id: AbstractEmptyMapIterator.java 1477802 2013-04-30 20:01:28Z tn $ */ public abstract class AbstractEmptyMapIterator extends AbstractEmptyIterator { /** * Create a new AbstractEmptyMapIterator. */ public AbstractEmptyMapIterator() { super(); } public K getKey() { throw new IllegalStateException("Iterator contains no elements"); } public V getValue() { throw new IllegalStateException("Iterator contains no elements"); } public V setValue(final V value) { throw new IllegalStateException("Iterator contains no elements"); } } ././@LongLink100644 0 0 176 12243235652 10263 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractOrderedMapIteratorDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractOrdered100664 5660 12243235516 31754 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import org.apache.commons.collections4.OrderedMapIterator; /** * Provides basic behaviour for decorating an ordered map iterator with extra functionality. *

      * All methods are forwarded to the decorated map iterator. * * @since 3.0 * @version $Id: AbstractOrderedMapIteratorDecorator.java 1477802 2013-04-30 20:01:28Z tn $ */ public class AbstractOrderedMapIteratorDecorator implements OrderedMapIterator { /** The iterator being decorated */ private 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(final 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; } //----------------------------------------------------------------------- /** {@inheritDoc} */ public boolean hasNext() { return iterator.hasNext(); } /** {@inheritDoc} */ public K next() { return iterator.next(); } /** {@inheritDoc} */ public boolean hasPrevious() { return iterator.hasPrevious(); } /** {@inheritDoc} */ public K previous() { return iterator.previous(); } /** {@inheritDoc} */ public void remove() { iterator.remove(); } /** {@inheritDoc} */ public K getKey() { return iterator.getKey(); } /** {@inheritDoc} */ public V getValue() { return iterator.getValue(); } /** {@inheritDoc} */ public V setValue(final V obj) { return iterator.setValue(obj); } } ././@LongLink100644 0 0 167 12243235652 10263 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractMapIteratorDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractMapIter100664 5231 12243235516 31723 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import org.apache.commons.collections4.MapIterator; /** * Provides basic behaviour for decorating a map iterator with extra functionality. *

      * All methods are forwarded to the decorated map iterator. * * @since 3.0 * @version $Id: AbstractMapIteratorDecorator.java 1477802 2013-04-30 20:01:28Z tn $ */ public class AbstractMapIteratorDecorator implements MapIterator { /** The iterator being decorated */ private 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(final 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; } //----------------------------------------------------------------------- /** {@inheritDoc} */ public boolean hasNext() { return iterator.hasNext(); } /** {@inheritDoc} */ public K next() { return iterator.next(); } /** {@inheritDoc} */ public void remove() { iterator.remove(); } /** {@inheritDoc} */ public K getKey() { return iterator.getKey(); } /** {@inheritDoc} */ public V getValue() { return iterator.getValue(); } /** {@inheritDoc} */ public V setValue(final V obj) { return iterator.setValue(obj); } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/LazyIteratorChain.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/LazyIteratorCha100664 13160 12243235516 31763 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; /** * An LazyIteratorChain is an Iterator that wraps a number of Iterators in a lazy manner. *

      * This class makes multiple iterators look like one to the caller. When any * method from the Iterator interface is called, the LazyIteratorChain will delegate * to a single underlying Iterator. The LazyIteratorChain will invoke the Iterators * in sequence until all Iterators are exhausted. *

      * The Iterators are provided by {@link #nextIterator(int)} which has to be overridden by * sub-classes and allows to lazily create the Iterators as they are accessed: *

       * return new LazyIteratorChain<String>() {
       *     protected Iterator<String> nextIterator(int count) {
       *         return count == 1 ? Arrays.asList("foo", "bar").iterator() : null;
       *     }
       * };
       * 
      *

      * Once the inner Iterator's {@link Iterator#hasNext()} method returns false, * {@link #nextIterator(int)} will be called to obtain another iterator, and so on * until {@link #nextIterator(int)} returns null, indicating that the chain is exhausted. *

      * NOTE: The LazyIteratorChain may contain no iterators. In this case the class will * function as an empty iterator. * * @since 4.0 * @version $Id: LazyIteratorChain.java 1482073 2013-05-13 20:09:40Z tn $ */ public abstract class LazyIteratorChain implements Iterator { /** The number of times {@link #nextIterator()} was already called. */ private int callCounter = 0; /** Indicates that the Iterator chain has been exhausted. */ private boolean chainExhausted = false; /** The current iterator. */ private 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. */ private Iterator lastUsedIterator = null; //----------------------------------------------------------------------- /** * Gets the next iterator after the previous one has been exhausted. *

      * This method MUST return null when there are no more iterators. * * @param count the number of time this method has been called (starts with 1) * @return the next iterator, or null if there are no more. */ protected abstract Iterator nextIterator(int count); /** * Updates the current iterator field to ensure that the current Iterator * is not exhausted. */ private void updateCurrentIterator() { if (callCounter == 0) { currentIterator = nextIterator(++callCounter); if (currentIterator == null) { currentIterator = EmptyIterator.emptyIterator(); chainExhausted = true; } // 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 && !chainExhausted) { final Iterator nextIterator = nextIterator(++callCounter); if (nextIterator != null) { currentIterator = nextIterator; } else { chainExhausted = true; } } } //----------------------------------------------------------------------- /** * Return true if any Iterator in the chain has a remaining element. * * @return true if elements remain */ public boolean hasNext() { updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.hasNext(); } /** * Returns the next element of the current Iterator * * @return element from the current Iterator * @throws java.util.NoSuchElementException if all the Iterators are exhausted */ public E next() { 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() { if (currentIterator == null) { updateCurrentIterator(); } lastUsedIterator.remove(); } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractEmptyIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractEmptyIt100664 4012 12243235516 31751 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.NoSuchElementException; /** * Provides an implementation of an empty iterator. * * @since 3.1 * @version $Id: AbstractEmptyIterator.java 1477802 2013-04-30 20:01:28Z tn $ */ abstract class AbstractEmptyIterator { /** * Constructor. */ protected AbstractEmptyIterator() { super(); } public boolean hasNext() { return false; } public E next() { throw new NoSuchElementException("Iterator contains no elements"); } public boolean hasPrevious() { return false; } public E previous() { throw new NoSuchElementException("Iterator contains no elements"); } public int nextIndex() { return 0; } public int previousIndex() { return -1; } public void add(final E obj) { throw new UnsupportedOperationException("add() not supported for empty Iterator"); } public void set(final E obj) { throw new IllegalStateException("Iterator contains no elements"); } public void remove() { throw new IllegalStateException("Iterator contains no elements"); } public void reset() { // do nothing } } ././@LongLink100644 0 0 173 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractUntypedIteratorDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractUntyped100664 4030 12243235516 32006 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; /** * Provides basic behaviour for decorating an iterator with extra functionality * without committing the generic type of the Iterator implementation. *

      * All methods are forwarded to the decorated iterator. * * @since 4.0 * @version $Id: AbstractUntypedIteratorDecorator.java 1477802 2013-04-30 20:01:28Z tn $ */ public abstract class AbstractUntypedIteratorDecorator implements Iterator { /** The iterator being decorated */ private final Iterator iterator; /** * Create a new AbstractUntypedIteratorDecorator. * * @param iterator the iterator to decorate */ protected AbstractUntypedIteratorDecorator(final 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 void remove() { iterator.remove(); } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ObjectGraphIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ObjectGraphIter100664 21770 12243235516 31740 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ArrayStack; import org.apache.commons.collections4.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 3.1 * @version $Id: ObjectGraphIterator.java 1477802 2013-04-30 20:01:28Z tn $ */ @SuppressWarnings("deprecation") // we use the deprecated ArrayStack - change to ArrayDeque (Java 1.6) public class ObjectGraphIterator implements Iterator { /** The stack of iterators */ private final ArrayStack> stack = new ArrayStack>(8); /** The root object in the tree */ private E root; /** The transformer to use */ private final Transformer transformer; /** Whether there is another element in the iteration */ private boolean hasNext = false; /** The current iterator */ private Iterator currentIterator; /** The current value */ private E currentValue; /** The last used iterator, needed for remove() */ private 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 */ @SuppressWarnings("unchecked") public ObjectGraphIterator(final E root, final 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(final 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) { // NOPMD // 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 */ @SuppressWarnings("unchecked") protected void findNext(final E 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(final Iterator iterator) { if (iterator != currentIterator) { // recurse a level if (currentIterator != null) { stack.push(currentIterator); } currentIterator = iterator; } while (currentIterator.hasNext() && hasNext == false) { E next = currentIterator.next(); if (transformer != null) { next = transformer.transform(next); } findNext(next); } // if we havn't found the next value and iterators are not yet exhausted if (!hasNext && !stack.isEmpty()) { // current iterator exhausted, go up a level currentIterator = 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 E next() { updateCurrentIterator(); if (hasNext == false) { throw new NoSuchElementException("No more elements in the iteration"); } lastUsedIterator = currentIterator; final E 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; } } ././@LongLink100644 0 0 171 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/UnmodifiableOrderedMapIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/UnmodifiableOrd100664 6706 12243235516 31751 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.Unmodifiable; /** * Decorates an ordered map iterator such that it cannot be modified. *

      * Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableOrderedMapIterator.java 1533984 2013-10-20 21:12:51Z tn $ */ public final class UnmodifiableOrderedMapIterator implements OrderedMapIterator, Unmodifiable { /** The iterator being decorated */ private final OrderedMapIterator iterator; //----------------------------------------------------------------------- /** * Decorates the specified iterator such that it cannot be modified. * * @param the key type * @param the value type * @param iterator the iterator to decorate * @return a new unmodifiable ordered map iterator * @throws IllegalArgumentException if the iterator is null */ public static OrderedMapIterator unmodifiableOrderedMapIterator( final OrderedMapIterator iterator) { if (iterator == null) { throw new IllegalArgumentException("OrderedMapIterator must not be null"); } if (iterator instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final OrderedMapIterator tmpIterator = (OrderedMapIterator) iterator; return tmpIterator; } return new UnmodifiableOrderedMapIterator(iterator); } //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ private UnmodifiableOrderedMapIterator(final OrderedMapIterator iterator) { super(); this.iterator = iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public K next() { return iterator.next(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public K previous() { return iterator.previous(); } public K getKey() { return iterator.getKey(); } public V getValue() { return iterator.getValue(); } public V setValue(final V value) { throw new UnsupportedOperationException("setValue() is not supported"); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } } ././@LongLink100644 0 0 170 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractListIteratorDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractListIte100664 5654 12243235516 31750 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 3.0 * @version $Id: AbstractListIteratorDecorator.java 1477802 2013-04-30 20:01:28Z tn $ */ public class AbstractListIteratorDecorator implements ListIterator { /** The iterator being decorated */ private 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(final 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; } //----------------------------------------------------------------------- /** {@inheritDoc} */ public boolean hasNext() { return iterator.hasNext(); } /** {@inheritDoc} */ public E next() { return iterator.next(); } /** {@inheritDoc} */ public int nextIndex() { return iterator.nextIndex(); } /** {@inheritDoc} */ public boolean hasPrevious() { return iterator.hasPrevious(); } /** {@inheritDoc} */ public E previous() { return iterator.previous(); } /** {@inheritDoc} */ public int previousIndex() { return iterator.previousIndex(); } /** {@inheritDoc} */ public void remove() { iterator.remove(); } /** {@inheritDoc} */ public void set(final E obj) { iterator.set(obj); } /** {@inheritDoc} */ public void add(final E obj) { iterator.add(obj); } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/FilterListIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/FilterListItera100664 17637 12243235516 32001 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.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 2.0 * @version $Id: FilterListIterator.java 1477802 2013-04-30 20:01:28Z tn $ */ public class FilterListIterator implements ListIterator { /** The iterator being used */ private ListIterator iterator; /** The predicate being used */ private Predicate predicate; /** * The value of the next (matching) object, when * {@link #nextObjectSet} is true. */ private E nextObject; /** * Whether or not the {@link #nextObject} has been set * (possibly to null). */ private boolean nextObjectSet = false; /** * The value of the previous (matching) object, when * {@link #previousObjectSet} is true. */ private E previousObject; /** * Whether or not the {@link #previousObject} has been set * (possibly to null). */ private boolean previousObjectSet = false; /** * The index of the element that would be returned by {@link #next}. */ private int nextIndex = 0; //----------------------------------------------------------------------- /** * Constructs a new FilterListIterator that will not function * until {@link #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(final ListIterator iterator ) { super(); this.iterator = iterator; } /** * Constructs a new FilterListIterator. * * @param iterator the iterator to use * @param predicate the predicate to use */ public FilterListIterator(final ListIterator iterator, final 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(final Predicate predicate) { super(); this.predicate = predicate; } //----------------------------------------------------------------------- /** Not supported. */ public void add(final E o) { throw new UnsupportedOperationException("FilterListIterator.add(Object) is not supported."); } public boolean hasNext() { return nextObjectSet || setNextObject(); } public boolean hasPrevious() { return previousObjectSet || setPreviousObject(); } public E next() { if (!nextObjectSet) { if (!setNextObject()) { throw new NoSuchElementException(); } } nextIndex++; final E temp = nextObject; clearNextObject(); return temp; } public int nextIndex() { return nextIndex; } public E previous() { if (!previousObjectSet) { if (!setPreviousObject()) { throw new NoSuchElementException(); } } nextIndex--; final E temp = previousObject; clearPreviousObject(); return temp; } public int previousIndex() { return nextIndex-1; } /** Not supported. */ public void remove() { throw new UnsupportedOperationException("FilterListIterator.remove() is not supported."); } /** Not supported. */ public void set(final E o) { throw new UnsupportedOperationException("FilterListIterator.set(Object) is not supported."); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public ListIterator getListIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setListIterator(final 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(final 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; } clearNextObject(); } if (iterator == null) { return false; } while (iterator.hasNext()) { final E object = iterator.next(); if (predicate.evaluate(object)) { nextObject = object; nextObjectSet = true; return true; } } return false; } private void clearPreviousObject() { previousObject = null; previousObjectSet = false; } private boolean setPreviousObject() { // if nextObjectSet, // then we've walked back one step in the // underlying list (due to a hasNext() call) // so skip ahead one matching object if (nextObjectSet) { clearNextObject(); if (!setPreviousObject()) { return false; } clearPreviousObject(); } if (iterator == null) { return false; } while (iterator.hasPrevious()) { final E object = iterator.previous(); if (predicate.evaluate(object)) { previousObject = object; previousObjectSet = true; return true; } } return false; } } ././@LongLink100644 0 0 164 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractIteratorDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/AbstractIterato100664 3272 12243235516 31774 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; /** * Provides basic behaviour for decorating an iterator with extra functionality. *

      * All methods are forwarded to the decorated iterator. * * @since 3.0 * @version $Id: AbstractIteratorDecorator.java 1469004 2013-04-17 17:37:03Z tn $ */ public abstract class AbstractIteratorDecorator extends AbstractUntypedIteratorDecorator { //----------------------------------------------------------------------- /** * Constructor that decorates the specified iterator. * * @param iterator the iterator to decorate, must not be null * @throws IllegalArgumentException if the collection is null */ protected AbstractIteratorDecorator(final Iterator iterator) { super(iterator); } /** {@inheritDoc} */ public E next() { return getIterator().next(); } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/PermutationIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/PermutationIter100664 12562 12243235516 32056 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; /** * This iterator creates permutations of an input collection, using the * Steinhaus-Johnson-Trotter algorithm (also called plain changes). *

      * The iterator will return exactly n! permutations of the input collection. * The {@code remove()} operation is not supported, and will throw an * {@code UnsupportedOperationException}. *

      * NOTE: in case an empty collection is provided, the iterator will * return exactly one empty list as result, as 0! = 1. * * @param the type of the objects being permuted * * @version $Id: PermutationIterator.java 1533984 2013-10-20 21:12:51Z tn $ * @since 4.0 */ public class PermutationIterator implements Iterator> { /** * Permutation is done on theses keys to handle equal objects. */ private int[] keys; /** * Mapping between keys and objects. */ private Map objectMap; /** * Direction table used in the algorithm: *

        *
      • false is left
      • *
      • true is right
      • *
      */ private boolean[] direction; /** * Next permutation to return. When a permutation is requested * this instance is provided and the next one is computed. */ private List nextPermutation; /** * Standard constructor for this class. * @param coll the collection to generate permutations for * @throws NullPointerException if coll is null */ public PermutationIterator(final Collection coll) { if (coll == null) { throw new NullPointerException("The collection must not be null"); } keys = new int[coll.size()]; direction = new boolean[coll.size()]; Arrays.fill(direction, false); int value = 1; objectMap = new HashMap(); for (E e : coll) { objectMap.put(Integer.valueOf(value), e); keys[value - 1] = value; value++; } nextPermutation = new ArrayList(coll); } /** * Indicates if there are more permutation available. * @return true if there are more permutations, otherwise false */ public boolean hasNext() { return nextPermutation != null; } /** * Returns the next permutation of the input collection. * @return a list of the permutator's elements representing a permutation * @throws NoSuchElementException if there are no more permutations */ public List next() { if (!hasNext()) { throw new NoSuchElementException(); } // find the largest mobile integer k int indexOfLargestMobileInteger = -1; int largestKey = -1; for (int i = 0; i < keys.length; i++) { if ((direction[i] && i < keys.length - 1 && keys[i] > keys[i + 1]) || (!direction[i] && i > 0 && keys[i] > keys[i - 1])) { if (keys[i] > largestKey) { largestKey = keys[i]; indexOfLargestMobileInteger = i; } } } if (largestKey == -1) { List toReturn = nextPermutation; nextPermutation = null; return toReturn; } // swap k and the adjacent integer it is looking at final int offset = direction[indexOfLargestMobileInteger] ? 1 : -1; final int tmpKey = keys[indexOfLargestMobileInteger]; keys[indexOfLargestMobileInteger] = keys[indexOfLargestMobileInteger + offset]; keys[indexOfLargestMobileInteger + offset] = tmpKey; boolean tmpDirection = direction[indexOfLargestMobileInteger]; direction[indexOfLargestMobileInteger] = direction[indexOfLargestMobileInteger + offset]; direction[indexOfLargestMobileInteger + offset] = tmpDirection; // reverse the direction of all integers larger than k and build the result final List nextP = new ArrayList(); for (int i = 0; i < keys.length; i++) { if (keys[i] > largestKey) { direction[i] = !direction[i]; } nextP.add(objectMap.get(Integer.valueOf(keys[i]))); } final List result = nextPermutation; nextPermutation = nextP; return result; } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/NodeListIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/NodeListIterato100664 5503 12243235516 31751 0ustartntn 0 0 /* * Copyright 2013 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * An {@link Iterator} over a {@link NodeList}. *

      * This iterator does not support {@link #remove()} as a {@link NodeList} does not support * removal of items. * * @since 4.0 * @version $Id: NodeListIterator.java 1543241 2013-11-19 00:31:39Z ggregory $ * @see NodeList */ public class NodeListIterator implements Iterator { /** the original NodeList instance */ private final NodeList nodeList; /** The current iterator index */ private int index = 0; /** * Convenience constructor, which creates a new NodeListIterator from * the specified node's childNodes. * * @param node Node, who's child nodes are wrapped by this class. Must not be null * @throws IllegalArgumentException if node is null */ public NodeListIterator(final Node node) { if (node == null) { throw new IllegalArgumentException("node must not be null!"); } this.nodeList = node.getChildNodes(); } /** * Constructor, that creates a new NodeListIterator from the specified * org.w3c.NodeList * * @param nodeList node list, which is wrapped by this class. Must not be null * @throws IllegalArgumentException if nodeList is null */ public NodeListIterator(final NodeList nodeList) { if (nodeList == null) { throw new IllegalArgumentException("nodeList must not be null!"); } this.nodeList = nodeList; } public boolean hasNext() { return nodeList == null ? false : index < nodeList.getLength(); } public Node next() { if (nodeList != null && index < nodeList.getLength()) { return nodeList.item(index++); } throw new NoSuchElementException("underlying nodeList has no more elements"); } /** * Throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException("remove() method not supported for a NodeListIterator."); } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EntrySetMapIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EntrySetMapIter100664 12752 12243235516 31763 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.Map; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.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 3.0 * @version $Id: EntrySetMapIterator.java 1477802 2013-04-30 20:01:28Z tn $ */ 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(final Map map) { super(); this.map = map; this.iterator = map.entrySet().iterator(); } //----------------------------------------------------------------------- /** * Checks to see if there are more entries still to be iterated. * * @return true if the iterator has more elements */ public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next key from the Map. * * @return the next key in the iteration * @throws java.util.NoSuchElementException if the iteration is finished */ public K next() { last = iterator.next(); canRemove = true; return last.getKey(); } //----------------------------------------------------------------------- /** * Removes the last returned key from the underlying Map. *

      * This method can be called once per call to next(). * * @throws UnsupportedOperationException if remove is not supported by the map * @throws IllegalStateException if next() has not yet been called * @throws IllegalStateException if remove() has already been called * since the last call to next() */ public void remove() { if (canRemove == false) { throw new IllegalStateException("Iterator remove() can only be called once after next()"); } iterator.remove(); last = null; canRemove = false; } //----------------------------------------------------------------------- /** * Gets the current key, which is the key returned by the last call * to next(). * * @return the current key * @throws IllegalStateException if next() has not yet been called */ public K getKey() { if (last == null) { throw new IllegalStateException("Iterator getKey() can only be called after next() and before remove()"); } return last.getKey(); } /** * Gets the current value, which is the value associated with the last key * returned by next(). * * @return the current value * @throws IllegalStateException if next() has not yet been called */ public V getValue() { if (last == null) { throw new IllegalStateException("Iterator getValue() can only be called after next() and before remove()"); } return last.getValue(); } /** * Sets the value associated with the current key. * * @param value the new value * @return the previous value * @throws UnsupportedOperationException if setValue is not supported by the map * @throws IllegalStateException if next() has not yet been called * @throws IllegalStateException if remove() has been called since the * last call to next() */ public V setValue(final V value) { if (last == null) { throw new IllegalStateException("Iterator setValue() can only be called after next() and before remove()"); } return last.setValue(value); } //----------------------------------------------------------------------- /** * Resets the state of the iterator. */ public void reset() { iterator = map.entrySet().iterator(); last = null; canRemove = false; } /** * Gets the iterator as a String. * * @return a string version of the iterator */ @Override public String toString() { if (last != null) { return "MapIterator[" + getKey() + "=" + getValue() + "]"; } return "MapIterator[]"; } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ListIteratorWrapper.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ListIteratorWra100664 21716 12243235516 32023 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableListIterator; /** * Converts an {@link Iterator} into a {@link ResettableListIterator}. * For plain Iterators this is accomplished by caching the returned * elements. This class can also be used to simply add * {@link org.apache.commons.collections4.ResettableIterator ResettableIterator} * functionality to a given {@link ListIterator}. *

      * 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 for plain Iterators. *

      * This class implements ResettableListIterator from Commons Collections 3.2. * * @since 2.1 * @version $Id: ListIteratorWrapper.java 1477802 2013-04-30 20:01:28Z tn $ */ public class ListIteratorWrapper implements ResettableListIterator { /** Message used when set or add are called. */ private static final String UNSUPPORTED_OPERATION_MESSAGE = "ListIteratorWrapper does not support optional operations of ListIterator."; /** Message used when set or add are called. */ private static final String CANNOT_REMOVE_MESSAGE = "Cannot remove element at index {0}."; /** 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; /** recall whether the wrapped iterator's "cursor" is in such a state as to allow remove() to be called */ private boolean removeState; // 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(final Iterator iterator) { super(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } this.iterator = iterator; } // ListIterator interface //------------------------------------------------------------------------- /** * Throws {@link UnsupportedOperationException} * unless the underlying Iterator is a ListIterator. * * @param obj the object to add * @throws UnsupportedOperationException if the underlying iterator is not of * type {@link ListIterator} */ public void add(final E obj) throws UnsupportedOperationException { if (iterator instanceof ListIterator) { @SuppressWarnings("unchecked") final ListIterator li = (ListIterator) iterator; li.add(obj); return; } 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 || iterator instanceof ListIterator) { 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 (iterator instanceof ListIterator) { final ListIterator li = (ListIterator) iterator; return li.hasPrevious(); } return currentIndex > 0; } /** * Returns the next element from the iterator. * * @return the next element from the iterator * @throws NoSuchElementException if there are no more elements */ public E next() throws NoSuchElementException { if (iterator instanceof ListIterator) { return iterator.next(); } if (currentIndex < wrappedIteratorIndex) { ++currentIndex; return list.get(currentIndex - 1); } final E retval = iterator.next(); list.add(retval); ++currentIndex; ++wrappedIteratorIndex; removeState = true; return retval; } /** * Returns the index of the next element. * * @return the index of the next element */ public int nextIndex() { if (iterator instanceof ListIterator) { final ListIterator li = (ListIterator) iterator; return li.nextIndex(); } return currentIndex; } /** * Returns the the previous element. * * @return the previous element * @throws NoSuchElementException if there are no previous elements */ public E previous() throws NoSuchElementException { if (iterator instanceof ListIterator) { @SuppressWarnings("unchecked") final ListIterator li = (ListIterator) iterator; return li.previous(); } if (currentIndex == 0) { throw new NoSuchElementException(); } removeState = wrappedIteratorIndex == currentIndex; return list.get(--currentIndex); } /** * Returns the index of the previous element. * * @return the index of the previous element */ public int previousIndex() { if (iterator instanceof ListIterator) { final ListIterator li = (ListIterator) iterator; return li.previousIndex(); } return currentIndex - 1; } /** * Throws {@link UnsupportedOperationException} if {@link #previous()} has ever been called. * * @throws UnsupportedOperationException always */ public void remove() throws UnsupportedOperationException { if (iterator instanceof ListIterator) { iterator.remove(); return; } int removeIndex = currentIndex; if (currentIndex == wrappedIteratorIndex) { --removeIndex; } if (!removeState || wrappedIteratorIndex - currentIndex > 1) { throw new IllegalStateException(MessageFormat.format(CANNOT_REMOVE_MESSAGE, Integer.valueOf(removeIndex))); } iterator.remove(); list.remove(removeIndex); currentIndex = removeIndex; wrappedIteratorIndex--; removeState = false; } /** * Throws {@link UnsupportedOperationException} * unless the underlying Iterator is a ListIterator. * * @param obj the object to set * @throws UnsupportedOperationException if the underlying iterator is not of * type {@link ListIterator} */ public void set(final E obj) throws UnsupportedOperationException { if (iterator instanceof ListIterator) { @SuppressWarnings("unchecked") final ListIterator li = (ListIterator) iterator; li.set(obj); return; } throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE); } // ResettableIterator interface //------------------------------------------------------------------------- /** * Resets this iterator back to the position at which the iterator * was created. * * @since 3.2 */ public void reset() { if (iterator instanceof ListIterator) { final ListIterator li = (ListIterator) iterator; while (li.previousIndex() >= 0) { li.previous(); } return; } currentIndex = 0; } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ArrayIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ArrayIterator.j100664 14741 12243235516 31744 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.lang.reflect.Array; import java.util.NoSuchElementException; import org.apache.commons.collections4.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.collections4.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 1.0 * @version $Id: ArrayIterator.java 1494282 2013-06-18 20:09:15Z sebb $ */ public class ArrayIterator implements ResettableIterator { /** The array to iterate over */ final Object array; /** The start index to loop from */ final int startIndex; /** The end index to loop to */ final int endIndex; /** The current iterator index */ int index = 0; // Constructors // ---------------------------------------------------------------------- /** * 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) { this(array, 0); } /** * 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) { this(array, startIndex, Array.getLength(array)); } /** * 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(); this.array = array; this.startIndex = startIndex; this.endIndex = endIndex; this.index = startIndex; final int len = Array.getLength(array); checkBound(startIndex, len, "start"); checkBound(endIndex, len, "end"); if (endIndex < startIndex) { throw new IllegalArgumentException("End index must not be less than start index."); } } /** * Checks whether the index is valid or not. * * @param bound the index to check * @param len the length of the array * @param type the index type (for error messages) * @throws IndexOutOfBoundsException if the index is invalid */ protected void checkBound(final int bound, final int len, final String type ) { if (bound > len) { 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 */ @SuppressWarnings("unchecked") public E next() { if (hasNext() == false) { throw new NoSuchElementException(); } return (E) Array.get(array, index++); } /** * Throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException("remove() method is not supported"); } // Properties //----------------------------------------------------------------------- /** * Gets the array that this iterator is iterating over. * * @return the array this iterator iterates over. */ public Object getArray() { return array; } /** * Gets the start index to loop from. * * @return the start index * @since 4.0 */ public int getStartIndex() { return this.startIndex; } /** * Gets the end index to loop to. * * @return the end index * @since 4.0 */ public int getEndIndex() { return this.endIndex; } /** * Resets the iterator back to the start index. */ public void reset() { this.index = this.startIndex; } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EmptyOrderedIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EmptyOrderedIte100664 3465 12243235516 31752 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import org.apache.commons.collections4.OrderedIterator; import org.apache.commons.collections4.ResettableIterator; /** * Provides an implementation of an empty ordered iterator. * * @since 3.1 * @version $Id: EmptyOrderedIterator.java 1543955 2013-11-20 21:23:53Z tn $ */ public class EmptyOrderedIterator extends AbstractEmptyIterator implements OrderedIterator, ResettableIterator { /** * Singleton instance of the iterator. * @since 3.1 */ @SuppressWarnings("rawtypes") public static final OrderedIterator INSTANCE = new EmptyOrderedIterator(); /** * Typed instance of the iterator. * @param the element type * @return OrderedIterator */ @SuppressWarnings("unchecked") public static OrderedIterator emptyOrderedIterator() { return (OrderedIterator) INSTANCE; } /** * Constructor. */ protected EmptyOrderedIterator() { super(); } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/UnmodifiableIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/UnmodifiableIte100664 5552 12243235516 31744 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import org.apache.commons.collections4.Unmodifiable; /** * Decorates an iterator such that it cannot be modified. *

      * Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableIterator.java 1533984 2013-10-20 21:12:51Z tn $ */ public final class UnmodifiableIterator implements Iterator, Unmodifiable { /** The iterator being decorated */ private final Iterator iterator; //----------------------------------------------------------------------- /** * Decorates the specified iterator such that it cannot be modified. *

      * If the iterator is already unmodifiable it is returned directly. * * @param the element type * @param iterator the iterator to decorate * @return a new unmodifiable iterator * @throws IllegalArgumentException if the iterator is null */ public static Iterator unmodifiableIterator(final Iterator iterator) { if (iterator == null) { throw new IllegalArgumentException("Iterator must not be null"); } if (iterator instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final Iterator tmpIterator = (Iterator) iterator; return tmpIterator; } return new UnmodifiableIterator(iterator); } //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ private UnmodifiableIterator(final Iterator iterator) { super(); this.iterator = iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public E next() { return iterator.next(); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EmptyOrderedMapIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EmptyOrderedMap100664 3645 12243235516 31746 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import org.apache.commons.collections4.OrderedMapIterator; import org.apache.commons.collections4.ResettableIterator; /** * Provides an implementation of an empty ordered map iterator. * * @since 3.1 * @version $Id: EmptyOrderedMapIterator.java 1543955 2013-11-20 21:23:53Z tn $ */ public class EmptyOrderedMapIterator extends AbstractEmptyMapIterator implements OrderedMapIterator, ResettableIterator { /** * Singleton instance of the iterator. * @since 3.1 */ @SuppressWarnings("rawtypes") public static final OrderedMapIterator INSTANCE = new EmptyOrderedMapIterator(); /** * Get a typed instance of the iterator. * @param the key type * @param the value type * @return {@link OrderedMapIterator} */ @SuppressWarnings("unchecked") public static OrderedMapIterator emptyOrderedMapIterator() { return (OrderedMapIterator) INSTANCE; } /** * Constructor. */ protected EmptyOrderedMapIterator() { super(); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/IteratorChain.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/IteratorChain.j100664 23477 12243235516 31716 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; /** * 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 Iterator after a method in the Iterator * interface has been called will result in an UnsupportedOperationException. *

      * NOTE: As from version 3.0, the IteratorChain may contain no iterators. In * this case the class will function as an empty iterator. *

      * NOTE: As from version 4.0, the IteratorChain stores the iterators in a queue * and removes any reference to them as soon as they are not used anymore. Thus * the methods {@code setIterator(Iterator)} and {@code getIterators()} have been * removed and {@link #size()} will return the number of remaining iterators in * the queue. * * @since 2.1 * @version $Id: IteratorChain.java 1482514 2013-05-14 18:36:12Z tn $ */ public class IteratorChain implements Iterator { /** The chain of iterators */ private final Queue> iteratorChain = new LinkedList>(); /** The current iterator */ private 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 */ private Iterator lastUsedIterator = null; /** * ComparatorChain is "locked" after the first time compare(Object,Object) * is called */ private 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. *

      * This method takes one iterator. The newly constructed iterator will * iterate through that iterator. Thus calling this constructor on its own * will have no effect other than decorating the input iterator. *

      * You will normally use {@link #addIterator(Iterator)} to add some more * iterators after using this constructor. * * @param iterator the first child iterator in the IteratorChain, not null * @throws NullPointerException if the iterator is null */ public IteratorChain(final Iterator iterator) { super(); addIterator(iterator); } /** * Constructs a new IteratorChain over the two given iterators. *

      * This method takes two iterators. The newly constructed iterator will * iterate through each one of the input iterators in turn. * * @param first the first child iterator in the IteratorChain, not null * @param second the second child iterator in the IteratorChain, not null * @throws NullPointerException if either iterator is null */ public IteratorChain(final Iterator first, final Iterator second) { super(); addIterator(first); addIterator(second); } /** * Constructs a new IteratorChain over the array of iterators. *

      * This method takes an array of iterators. The newly constructed iterator * will iterate through each one of the input iterators in turn. * * @param iteratorChain the array of iterators, not null * @throws NullPointerException if iterators array is or contains null */ public IteratorChain(final Iterator... iteratorChain) { super(); for (final Iterator element : iteratorChain) { addIterator(element); } } /** * Constructs a new IteratorChain over the collection of * iterators. *

      * This method takes a collection of iterators. The newly constructed * iterator will iterate through each one of the input iterators in turn. * * @param iteratorChain the collection of iterators, not null * @throws NullPointerException if iterators collection is or contains null * @throws ClassCastException if iterators collection doesn't contain an * iterator */ public IteratorChain(final Collection> iteratorChain) { super(); for (final Iterator iterator : iteratorChain) { addIterator(iterator); } } //----------------------------------------------------------------------- /** * Add an Iterator to the end of the chain * * @param iterator Iterator to add * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void addIterator(final Iterator iterator) { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iteratorChain.add(iterator); } /** * Returns the remaining 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. emptyIterator(); } else { currentIterator = iteratorChain.remove(); } // 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 && !iteratorChain.isEmpty()) { currentIterator = iteratorChain.remove(); } } //----------------------------------------------------------------------- /** * Return true if any Iterator in the IteratorChain has a remaining element. * * @return true if elements remain */ public boolean hasNext() { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.hasNext(); } /** * Returns the next Object of the current Iterator * * @return Object from the current Iterator * @throws java.util.NoSuchElementException if all the Iterators are * exhausted */ public E next() { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.next(); } /** * Removes from the underlying collection the last element returned by the * Iterator. As with next() and hasNext(), this method calls remove() on the * underlying Iterator. Therefore, this method may throw an * UnsupportedOperationException if the underlying Iterator does not support * this method. * * @throws UnsupportedOperationException if the remove operator is not * supported by the underlying Iterator * @throws IllegalStateException if the next method has not yet been called, * or the remove method has already been called after the last call to the * next method. */ public void remove() { lockChain(); if (currentIterator == null) { updateCurrentIterator(); } lastUsedIterator.remove(); } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ObjectArrayIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ObjectArrayIter100664 13105 12243235516 31746 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.NoSuchElementException; import org.apache.commons.collections4.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 3.0 * @version $Id: ObjectArrayIterator.java 1543928 2013-11-20 20:15:35Z tn $ */ public class ObjectArrayIterator implements ResettableIterator { /** The array */ final E[] array; /** The start index to loop from */ final int startIndex; /** The end index to loop to */ final int endIndex; /** The current iterator index */ int index = 0; //------------------------------------------------------------------------- /** * 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(final E... array) { this(array, 0, array.length); } /** * Constructs an ObjectArrayIterator that will iterate over the values in the * specified array from a specific start index. * * @param array the array to iterate over * @param start the index to start iterating at * @throws NullPointerException if array is null * @throws IndexOutOfBoundsException if the start index is out of bounds */ public ObjectArrayIterator(final E array[], final 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(final E array[], final int start, final int end) { super(); if (start < 0) { throw new ArrayIndexOutOfBoundsException("Start index must not be less than zero"); } if (end > array.length) { throw new ArrayIndexOutOfBoundsException("End index must not be greater than the array length"); } if (start > array.length) { throw new ArrayIndexOutOfBoundsException("Start index must not be greater than the array length"); } if (end < start) { throw new IllegalArgumentException("End index must not be less than start index"); } this.array = array; this.startIndex = start; this.endIndex = end; this.index = start; } // Iterator interface //------------------------------------------------------------------------- /** * Returns true if there are more elements to return from the array. * * @return true if there is a next element to return */ public boolean hasNext() { return this.index < this.endIndex; } /** * Returns the next element in the array. * * @return the next element in the array * @throws NoSuchElementException if all the elements in the array * have already been returned */ public E next() { if (hasNext() == false) { throw new NoSuchElementException(); } return this.array[this.index++]; } /** * Throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException("remove() method is not supported for an ObjectArrayIterator"); } // Properties //------------------------------------------------------------------------- /** * Gets the array that this iterator is iterating over. * * @return the array this iterator iterates over */ public E[] getArray() { return this.array; } /** * 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; } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EnumerationIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EnumerationIter100664 11151 12243235516 32026 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 1.0 * @version $Id: EnumerationIterator.java 1477802 2013-04-30 20:01:28Z tn $ */ public class EnumerationIterator implements Iterator { /** The collection to remove elements from */ private final Collection collection; /** The enumeration being converted */ private Enumeration enumeration; /** The last object retrieved */ private E last; // Constructors //----------------------------------------------------------------------- /** * Constructs a new EnumerationIterator that will not * function until {@link #setEnumeration(Enumeration)} is called. */ public EnumerationIterator() { this(null, null); } /** * Constructs a new EnumerationIterator that provides * an iterator view of the given enumeration. * * @param enumeration the enumeration to use */ public EnumerationIterator(final Enumeration enumeration) { this(enumeration, null); } /** * Constructs a new EnumerationIterator that will remove * elements from the specified collection. * * @param enumeration the enumeration to use * @param collection the collection to remove elements from */ public EnumerationIterator(final Enumeration enumeration, final Collection collection) { super(); this.enumeration = enumeration; this.collection = collection; this.last = null; } // Iterator interface //----------------------------------------------------------------------- /** * Returns true if the underlying enumeration has more elements. * * @return true if the underlying enumeration has more elements * @throws NullPointerException if the underlying enumeration is null */ public boolean hasNext() { return enumeration.hasMoreElements(); } /** * Returns the next object from the enumeration. * * @return the next object from the enumeration * @throws NullPointerException if the enumeration is null */ public E next() { last = enumeration.nextElement(); return last; } /** * Removes the last retrieved element if a collection is attached. *

      * Functions if an associated Collection is known. * If so, the first occurrence of the last returned object from this * iterator will be removed from the collection. * * @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; } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ReverseListIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ReverseListIter100664 12770 12243235516 32017 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.List; import java.util.ListIterator; import org.apache.commons.collections4.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. * * @since 3.2 * @version $Id: ReverseListIterator.java 1469004 2013-04-17 17:37:03Z tn $ */ 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(final 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 E next() { final E 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 E previous() { final E 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(final E 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(final E 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()); } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/IteratorIterable.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/IteratorIterabl100664 11420 12243235516 32007 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import org.apache.commons.collections4.ResettableIterator; /** * Adapter to make an {@link Iterator Iterator} instance appear to be an * {@link Iterable Iterable} instance. The iterable can be constructed in one * of two variants: single use, multiple use. * *

      * In the single use iterable case, the iterable is only usable for one * iterative operation over the source iterator. Subsequent iterative * operations use the same, exhausted source iterator. To create a single use * iterable, construct a new {@link IteratorIterable} using a {@link Iterator} * that is NOT a {@link ResettableIterator} iterator: *

       *   Iterator iterator = // some non-resettable iterator
       *   Iterable iterable = new IteratorIterable(iterator);
       * 
      *

      * *

      * In the multiple use iterable case, the iterable is usable for any number of * iterative operations over the source iterator. Of special note, even though * the iterable supports multiple iterations, it does not support concurrent * iterations. To implicitly create a multiple use iterable, construct a new * {@link IteratorIterable} using a {@link ResettableIterator} iterator: *

       *   Integer[] array = {Integer.valueOf(1),Integer.valueOf(2),Integer.valueOf(3)};
       *   Iterator iterator = IteratorUtils.arrayIterator(array); // a resettable iterator
       *   Iterable iterable = new IteratorIterable(iterator);
       * 
      *

      * *

      * A multiple use iterable can also be explicitly constructed using any * {@link Iterator} and specifying true for the * multipleUse flag: *

       *   Iterator iterator = // some non-resettable iterator
       *   Iterable iterable = new IteratorIterable(iterator, true);
       * 
      *

      * * @since 4.0 * @version $Id: IteratorIterable.java 1477802 2013-04-30 20:01:28Z tn $ */ public class IteratorIterable implements Iterable { /** * Factory method to create an {@link Iterator Iterator} from another * iterator over objects of a different subtype. */ private static Iterator createTypesafeIterator( final Iterator iterator) { return new Iterator() { public boolean hasNext() { return iterator.hasNext(); } public E next() { return iterator.next(); } public void remove() { iterator.remove(); } }; } /** the iterator being adapted into an iterable. */ private final Iterator iterator; /** the iterator parameterized as the {@link #iterator()} return type. */ private final Iterator typeSafeIterator; /** * Constructs a new IteratorIterable that will use the given * iterator. * * @param iterator the iterator to use. */ public IteratorIterable(final Iterator iterator) { this(iterator, false); } /** * Constructs a new IteratorIterable that will use the given * iterator. * * @param iterator the iterator to use. * @param multipleUse true if the new iterable can be used in multiple iterations */ public IteratorIterable(final Iterator iterator, final boolean multipleUse) { super(); if (multipleUse && !(iterator instanceof ResettableIterator)) { this.iterator = new ListIteratorWrapper(iterator); } else { this.iterator = iterator; } this.typeSafeIterator = createTypesafeIterator(this.iterator); } /** * Gets the iterator wrapped by this iterable. * * @return the iterator */ public Iterator iterator() { if (iterator instanceof ResettableIterator) { ((ResettableIterator)iterator).reset(); } return typeSafeIterator; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/SingletonIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/SingletonIterat100664 7506 12243235516 32020 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableIterator; /** * SingletonIterator is an {@link Iterator} over a single * object instance. * * @since 2.0 * @version $Id: SingletonIterator.java 1543928 2013-11-20 20:15:35Z tn $ */ public class SingletonIterator implements ResettableIterator { /** Whether remove is allowed */ private final boolean removeAllowed; /** Is the cursor before the first element */ private boolean beforeFirst = true; /** Has the element been removed */ private boolean removed = false; /** The object */ private E object; /** * Constructs a new SingletonIterator where remove * is a permitted operation. * * @param object the single object to return from the iterator */ public SingletonIterator(final E object) { this(object, true); } /** * Constructs a new SingletonIterator optionally choosing if * remove is a permitted operation. * * @param object the single object to return from the iterator * @param removeAllowed true if remove is allowed * @since 3.1 */ public SingletonIterator(final E object, final boolean removeAllowed) { super(); this.object = object; this.removeAllowed = removeAllowed; } //----------------------------------------------------------------------- /** * Is another object available from the iterator? *

      * This returns true if the single object hasn't been returned yet. * * @return true if the single object hasn't been returned yet */ public boolean hasNext() { return beforeFirst && !removed; } /** * Get the next object from the iterator. *

      * This returns the single object if it hasn't been returned yet. * * @return the single object * @throws NoSuchElementException if the single object has already * been returned */ public E next() { if (!beforeFirst || removed) { throw new NoSuchElementException(); } beforeFirst = false; return object; } /** * Remove the object from this iterator. * * @throws IllegalStateException if the next method has not * yet been called, or the remove method has already * been called after the last call to the next * method. * @throws UnsupportedOperationException if remove is not supported */ public void remove() { if (removeAllowed) { if (removed || beforeFirst) { throw new IllegalStateException(); } object = null; removed = true; } else { throw new UnsupportedOperationException(); } } /** * Reset the iterator to the start. */ public void reset() { beforeFirst = true; } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/IteratorEnumeration.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/IteratorEnumera100664 5565 12243235516 32016 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 1.0 * @version $Id: IteratorEnumeration.java 1543728 2013-11-20 07:51:32Z ebourg $ */ 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() { } /** * Constructs a new IteratorEnumeration that will use the given * iterator. * * @param iterator the iterator to use */ public IteratorEnumeration(final Iterator iterator) { this.iterator = iterator; } // Iterator interface //------------------------------------------------------------------------- /** * Returns true if the underlying iterator has more elements. * * @return true if the underlying iterator has more elements */ public boolean hasMoreElements() { return iterator.hasNext(); } /** * Returns the next element from the underlying iterator. * * @return the next element from the underlying iterator. * @throws java.util.NoSuchElementException if the underlying iterator has * no more elements */ public E nextElement() { return iterator.next(); } // Properties //------------------------------------------------------------------------- /** * Returns the underlying iterator. * * @return the underlying iterator */ public Iterator getIterator() { return iterator; } /** * Sets the underlying iterator. * * @param iterator the new underlying iterator */ public void setIterator(final Iterator iterator) { this.iterator = iterator; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/TransformIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/TransformIterat100664 11257 12243235516 32047 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import org.apache.commons.collections4.Transformer; /** * Decorates an iterator such that each element returned is transformed. * * @since 1.0 * @version $Id: TransformIterator.java 1477802 2013-04-30 20:01:28Z tn $ */ 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} and * {@link #setTransformer(Transformer)} methods are 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(final 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(final Iterator iterator, final Transformer transformer) { super(); this.iterator = iterator; this.transformer = transformer; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } /** * Gets the next object from the iteration, transforming it using the * current transformer. If the transformer is null, no transformation * occurs and the object from the iterator is returned directly. * * @return the next object * @throws java.util.NoSuchElementException if there are no more elements */ public O next() { return transform(iterator.next()); } public void remove() { iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator. */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final 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(final Transformer transformer) { this.transformer = transformer; } //----------------------------------------------------------------------- /** * Transforms the given object using the transformer. * If the transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected O transform(final I source) { return transformer.transform(source); } } ././@LongLink100644 0 0 163 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/UnmodifiableListIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/UnmodifiableLis100664 6561 12243235516 31753 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ListIterator; import org.apache.commons.collections4.Unmodifiable; /** * Decorates a list iterator such that it cannot be modified. *

      * Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableListIterator.java 1533984 2013-10-20 21:12:51Z tn $ */ public final class UnmodifiableListIterator implements ListIterator, Unmodifiable { /** The iterator being decorated */ private final ListIterator iterator; //----------------------------------------------------------------------- /** * Decorates the specified iterator such that it cannot be modified. * * @param the element type * @param iterator the iterator to decorate * @return a new unmodifiable list iterator * @throws IllegalArgumentException if the iterator is null */ public static ListIterator umodifiableListIterator(final ListIterator iterator) { if (iterator == null) { throw new IllegalArgumentException("ListIterator must not be null"); } if (iterator instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final ListIterator tmpIterator = (ListIterator) iterator; return tmpIterator; } return new UnmodifiableListIterator(iterator); } //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ private UnmodifiableListIterator(final ListIterator iterator) { super(); this.iterator = iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public E next() { return iterator.next(); } public int nextIndex() { return iterator.nextIndex(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public E previous() { return iterator.previous(); } public int previousIndex() { return iterator.previousIndex(); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } public void set(final E obj) { throw new UnsupportedOperationException("set() is not supported"); } public void add(final E obj) { throw new UnsupportedOperationException("add() is not supported"); } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/LoopingIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/LoopingIterator100664 10255 12243235516 32041 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.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 3.0 * @version $Id: LoopingIterator.java 1477802 2013-04-30 20:01:28Z tn $ */ public class LoopingIterator implements ResettableIterator { /** The collection to base the iterator on */ private final 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(final 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. * * @return the next object * @throws NoSuchElementException if there are no elements * at all. Use {@link #hasNext} to avoid this error. */ public E next() { if (collection.size() == 0) { throw new NoSuchElementException("There are no elements for this iterator to loop on"); } if (iterator.hasNext() == false) { reset(); } return iterator.next(); } /** * Removes the previously retrieved item from the underlying collection. *

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

      * This method can only be called after at least one {@link #next} method call. * After a removal, the remove method may not be called again until another * next has been performed. If the {@link #reset} is called, then remove may * not be called until {@link #next} is called again. */ public void remove() { iterator.remove(); } /** * Resets the iterator back to the start of the collection. */ public void reset() { iterator = collection.iterator(); } /** * Gets the size of the collection underlying the iterator. * * @return the current collection size */ public int size() { return collection.size(); } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/FilterIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/FilterIterator.100664 13650 12243235516 31737 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.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 1.0 * @version $Id: FilterIterator.java 1477802 2013-04-30 20:01:28Z tn $ */ public class FilterIterator implements Iterator { /** The iterator being used */ private Iterator iterator; /** The predicate being used */ private Predicate predicate; /** The next object in the iteration */ private E nextObject; /** Whether the next object has been calculated yet */ private boolean nextObjectSet = false; //----------------------------------------------------------------------- /** * Constructs a new FilterIterator that will not function * until {@link #setIterator(Iterator) setIterator} is invoked. */ public FilterIterator() { super(); } /** * Constructs a new FilterIterator that will not function * until {@link #setPredicate(Predicate) setPredicate} is invoked. * * @param iterator the iterator to use */ public FilterIterator(final 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(final Iterator iterator, final 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() { return nextObjectSet || 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 E next() { if (!nextObjectSet) { if (!setNextObject()) { throw new NoSuchElementException(); } } nextObjectSet = false; return nextObject; } /** * Removes from the underlying collection of the base iterator the last * element returned by this iterator. * This method can only be called * if next() was called, but not after * hasNext(), because the hasNext() call * changes the base iterator. * * @throws IllegalStateException if hasNext() has already * been called. */ public void remove() { if (nextObjectSet) { throw new IllegalStateException("remove() cannot be called"); } iterator.remove(); } //----------------------------------------------------------------------- /** * Gets the iterator this iterator is using. * * @return the iterator */ public Iterator getIterator() { return iterator; } /** * Sets the iterator for this iterator to use. * If iteration has started, this effectively resets the iterator. * * @param iterator the iterator to use */ public void setIterator(final 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(final 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()) { final E object = iterator.next(); if (predicate.evaluate(object)) { nextObject = object; nextObjectSet = true; return true; } } return false; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/CollatingIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/CollatingIterat100664 33461 12243235516 32011 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.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 2.1 * @version $Id: CollatingIterator.java 1477802 2013-04-30 20:01:28Z tn $ */ 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. A comparator must be * set by calling {@link #setComparator(Comparator)} before invoking * {@link #hasNext()}, or {@link #next()} for the first time. 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; must not be null, * unless you'll be invoking {@link #setComparator(Comparator)} * later on. */ 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; must not be null, * unless you'll be invoking {@link #setComparator(Comparator)} * later on. * @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; must not be null, * unless you'll be invoking {@link #setComparator(Comparator)} * later on. * @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; must not be null, * unless you'll be invoking {@link #setComparator(Comparator)} * later on. * @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 (final Iterator iterator : iterators) { addIterator(iterator); } } /** * 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; must not be null, * unless you'll be invoking {@link #setComparator(Comparator)} * later on. * @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 (final Iterator iterator : iterators) { addIterator(iterator); } } // 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.unmodifiableList(iterators); } /** * Gets the {@link Comparator} by which collatation occurs. * * @return the {@link Comparator} */ public Comparator getComparator() { return comparator; } /** * Sets the {@link Comparator} by which collation occurs. If you * would like to use the natural sort order (or, in other words, * if the elements in the iterators are implementing the * {@link java.lang.Comparable} interface), then use the * {@link org.apache.commons.collections4.comparators.ComparableComparator}. * * @param comp the {@link Comparator} to set * @throws IllegalStateException if iteration has started */ public void setComparator(final Comparator comp) { checkNotStarted(); comparator = comp; } // Iterator Methods // ------------------------------------------------------------------- /** * Returns true if any child iterator has remaining elements. * * @return true if this iterator has remaining elements */ public boolean hasNext() { start(); return anyValueSet(valueSet) || anyHasNext(iterators); } /** * Returns the next ordered element from a child iterator. * * @return the next ordered element * @throws NoSuchElementException if no child iterator has any more elements */ public E next() throws NoSuchElementException { if (hasNext() == false) { throw new NoSuchElementException(); } final int leastIndex = least(); if (leastIndex == -1) { throw new NoSuchElementException(); } final E val = values.get(leastIndex); clear(leastIndex); lastReturned = leastIndex; return val; } /** * Removes the last returned element from the child iterator that produced * it. * * @throws IllegalStateException if there is no last returned element, or if * the last returned element has already been removed */ public void remove() { if (lastReturned == -1) { throw new IllegalStateException("No value can be removed at present"); } iterators.get(lastReturned).remove(); } /** * Returns the index of the iterator that returned the last element. * * @return the index of the iterator that returned the last element * @throws IllegalStateException if there is no last returned element */ public int getIteratorIndex() { if (lastReturned == -1) { throw new IllegalStateException("No value has been returned yet"); } return lastReturned; } // 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(final int i) { final Iterator it = iterators.get(i); if (it.hasNext()) { values.set(i, it.next()); valueSet.set(i); return true; } values.set(i, null); valueSet.clear(i); return false; } /** * Clears the {@link #values} and {@link #valueSet} attributes at position * i. */ private void clear(final 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 NullPointerException if no comparator is set */ private int least() { int leastIndex = -1; E leastObject = null; for (int i = 0; i < values.size(); i++) { if (valueSet.get(i) == false) { set(i); } if (valueSet.get(i)) { if (leastIndex == -1) { leastIndex = i; leastObject = values.get(i); } else { final E curObject = values.get(i); if (comparator == null) { throw new NullPointerException("You must invoke setComparator() to set a comparator first."); } 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(final 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(final ArrayList> iters) { for (final Iterator iterator : iters) { if (iterator.hasNext()) { return true; } } return false; } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/package-info.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/package-info.ja100664 2344 12243235516 31615 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains implementations of the * {@link java.util.Iterator Iterator} interface. *

      * You may also consider using * {@link org.apache.commons.collections4.IteratorUtils IteratorUtils}, * which is a single class that uses static methods to construct instances * of the classes in this package. * * @version $Id: package-info.java 1477802 2013-04-30 20:01:28Z tn $ */ package org.apache.commons.collections4.iterators; ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/UnmodifiableMapIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/UnmodifiableMap100664 6310 12243235516 31731 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.Unmodifiable; /** * Decorates a map iterator such that it cannot be modified. *

      * Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableMapIterator.java 1533984 2013-10-20 21:12:51Z tn $ */ public final class UnmodifiableMapIterator implements MapIterator, Unmodifiable { /** The iterator being decorated */ private final MapIterator iterator; //----------------------------------------------------------------------- /** * Decorates the specified iterator such that it cannot be modified. * * @param the key type * @param the value type * @param iterator the iterator to decorate * @return a new unmodifiable map iterator * @throws IllegalArgumentException if the iterator is null */ public static MapIterator unmodifiableMapIterator( final MapIterator iterator) { if (iterator == null) { throw new IllegalArgumentException("MapIterator must not be null"); } if (iterator instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final MapIterator tmpIterator = (MapIterator) iterator; return tmpIterator; } return new UnmodifiableMapIterator(iterator); } //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ private UnmodifiableMapIterator(final MapIterator iterator) { super(); this.iterator = iterator; } //----------------------------------------------------------------------- public boolean hasNext() { return iterator.hasNext(); } public K next() { return iterator.next(); } public K getKey() { return iterator.getKey(); } public V getValue() { return iterator.getValue(); } public V setValue(final V value) { throw new UnsupportedOperationException("setValue() is not supported"); } public void remove() { throw new UnsupportedOperationException("remove() is not supported"); } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/SingletonListIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/SingletonListIt100664 12013 12243235516 32005 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.NoSuchElementException; import org.apache.commons.collections4.ResettableListIterator; /** * SingletonIterator is an {@link ListIterator} over a single * object instance. * * @since 2.1 * @version $Id: SingletonListIterator.java 1543928 2013-11-20 20:15:35Z tn $ */ public class SingletonListIterator implements ResettableListIterator { private boolean beforeFirst = true; private boolean nextCalled = false; private boolean removed = false; private E object; /** * Constructs a new SingletonListIterator. * * @param object the single object to return from the iterator */ public SingletonListIterator(final E object) { super(); this.object = object; } /** * Is another object available from the iterator? *

      * This returns true if the single object hasn't been returned yet. * * @return true if the single object hasn't been returned yet */ public boolean hasNext() { return beforeFirst && !removed; } /** * Is a previous object available from the iterator? *

      * This returns true if the single object has been returned. * * @return true if the single object has been returned */ public boolean hasPrevious() { return !beforeFirst && !removed; } /** * Returns the index of the element that would be returned by a subsequent * call to next. * * @return 0 or 1 depending on current state. */ public int nextIndex() { return beforeFirst ? 0 : 1; } /** * Returns the index of the element that would be returned by a subsequent * call to previous. A return value of -1 indicates that the iterator is currently at * the start. * * @return 0 or -1 depending on current state. */ public int previousIndex() { return beforeFirst ? -1 : 0; } /** * Get the next object from the iterator. *

      * This returns the single object if it hasn't been returned yet. * * @return the single object * @throws NoSuchElementException if the single object has already * been returned */ public E next() { if (!beforeFirst || removed) { throw new NoSuchElementException(); } beforeFirst = false; nextCalled = true; return object; } /** * Get the previous object from the iterator. *

      * This returns the single object if it has been returned. * * @return the single object * @throws NoSuchElementException if the single object has not already * been returned */ public E previous() { if (beforeFirst || removed) { throw new NoSuchElementException(); } beforeFirst = true; return object; } /** * Remove the object from this iterator. * @throws IllegalStateException if the next or previous * method has not yet been called, or the remove method * has already been called after the last call to next * or previous. */ public void remove() { if(!nextCalled || removed) { throw new IllegalStateException(); } object = null; removed = true; } /** * Add always throws {@link UnsupportedOperationException}. * * @param obj the object to add * @throws UnsupportedOperationException always */ public void add(final E obj) { throw new UnsupportedOperationException("add() is not supported by this iterator"); } /** * Set sets the value of the singleton. * * @param obj the object to set * @throws IllegalStateException if next has not been called * or the object has been removed */ public void set(final E obj) { if (!nextCalled || removed) { throw new IllegalStateException(); } this.object = obj; } /** * Reset the iterator back to the start. */ public void reset() { beforeFirst = true; nextCalled = false; } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/UniqueFilterIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/UniqueFilterIte100664 3156 12243235516 31760 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import org.apache.commons.collections4.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 2.1 * @version $Id: UniqueFilterIterator.java 1479385 2013-05-05 20:31:06Z tn $ */ public class UniqueFilterIterator extends FilterIterator { //------------------------------------------------------------------------- /** * Constructs a new UniqueFilterIterator. * * @param iterator the iterator to use */ public UniqueFilterIterator(final Iterator iterator) { super(iterator, UniquePredicate.uniquePredicate()); } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EmptyListIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EmptyListIterat100664 5001 12243235516 31774 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.ListIterator; import org.apache.commons.collections4.ResettableListIterator; /** * Provides an implementation of an empty list iterator. *

      * This class provides an implementation of an empty list iterator. This class * provides for binary compatibility between Commons Collections 2.1.1 and 3.1 * due to issues with IteratorUtils. * * @since 2.1.1 and 3.1 * @version $Id: EmptyListIterator.java 1543955 2013-11-20 21:23:53Z tn $ */ public class EmptyListIterator extends AbstractEmptyIterator implements ResettableListIterator { /** * Singleton instance of the iterator. * @since 3.1 */ @SuppressWarnings("rawtypes") public static final ResettableListIterator RESETTABLE_INSTANCE = new EmptyListIterator(); /** * Singleton instance of the iterator. * @since 2.1.1 and 3.1 */ @SuppressWarnings("rawtypes") public static final ListIterator INSTANCE = RESETTABLE_INSTANCE; /** * Get a typed instance of the iterator. * @param the element type * @return {@link ResettableListIterator} */ @SuppressWarnings("unchecked") public static ResettableListIterator resettableEmptyListIterator() { return (ResettableListIterator) RESETTABLE_INSTANCE; } /** * Get a typed instance of the iterator. * @param the element type * @return {@link ListIterator} */ @SuppressWarnings("unchecked") public static ListIterator emptyListIterator() { return (ListIterator) INSTANCE; } /** * Constructor. */ protected EmptyListIterator() { super(); } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/LoopingListIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/LoopingListIter100664 20620 12243235516 32004 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import org.apache.commons.collections4.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 3.2 * @version $Id: LoopingListIterator.java 1494333 2013-06-18 21:59:21Z sebb $ */ public class LoopingListIterator implements ResettableListIterator { /** The list to base the iterator on */ private final 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(final 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 E 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; } 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 E previous() { if (list.isEmpty()) { throw new NoSuchElementException( "There are no elements for this iterator to loop on"); } if (iterator.hasPrevious() == false) { E result = null; while (iterator.hasNext()) { result = iterator.next(); } iterator.previous(); return result; } 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; } 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(final E 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(final E obj) { iterator.set(obj); } /** * Resets the iterator back to the start of the list. */ public void reset() { _reset(); } private 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(); } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ArrayListIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ArrayListIterat100664 16411 12243235516 32003 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.lang.reflect.Array; import java.util.NoSuchElementException; import org.apache.commons.collections4.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.collections4.iterators.ArrayIterator * @see java.util.Iterator * @see java.util.ListIterator * * @since 3.0 * @version $Id: ArrayListIterator.java 1543955 2013-11-20 21:23:53Z tn $ */ public class ArrayListIterator extends ArrayIterator implements 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. */ private int lastItemIndex = -1; // Constructors // ---------------------------------------------------------------------- /** * 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(final 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(final Object array, final int startIndex) { super(array, 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(final Object array, final int startIndex, final int endIndex) { super(array, startIndex, endIndex); } // 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 */ @SuppressWarnings("unchecked") public E previous() { if (hasPrevious() == false) { throw new NoSuchElementException(); } this.lastItemIndex = --this.index; return (E) Array.get(this.array, this.index); } /** * Gets the next element from the array. * * @return the next element * @throws NoSuchElementException if there is no next element */ @Override @SuppressWarnings("unchecked") public E next() { if (hasNext() == false) { throw new NoSuchElementException(); } this.lastItemIndex = this.index; return (E) Array.get(this.array, this.index++); } /** * Gets the next index to be retrieved. * * @return the index of the item to be retrieved next */ public int nextIndex() { return this.index - this.startIndex; } /** * Gets the index of the item to be retrieved if {@link #previous()} is called. * * @return the index of the item to be retrieved next */ public int previousIndex() { return this.index - this.startIndex - 1; } /** * This iterator does not support modification of its backing collection, and so will * always throw an {@link UnsupportedOperationException} when this method is invoked. * * @param o the element to add * @throws UnsupportedOperationException always thrown. * @see java.util.ListIterator#set */ public void add(final 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. * * @param o the element to set * @throws IllegalStateException if {@link #next()} or {@link #previous()} has not been called * before {@link #set(Object)} * @see java.util.ListIterator#set */ public void set(final 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. */ @Override public void reset() { super.reset(); this.lastItemIndex = -1; } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EmptyMapIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EmptyMapIterato100664 3520 12243235516 31761 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.ResettableIterator; /** * Provides an implementation of an empty map iterator. * * @since 3.1 * @version $Id: EmptyMapIterator.java 1543955 2013-11-20 21:23:53Z tn $ */ public class EmptyMapIterator extends AbstractEmptyMapIterator implements MapIterator, ResettableIterator { /** * Singleton instance of the iterator. * @since 3.1 */ @SuppressWarnings("rawtypes") public static final MapIterator INSTANCE = new EmptyMapIterator(); /** * Get a typed instance of the iterator. * @param the key type * @param the value type * @return {@link MapIterator} */ @SuppressWarnings("unchecked") public static MapIterator emptyMapIterator() { return (MapIterator) INSTANCE; } /** * Constructor. */ protected EmptyMapIterator() { super(); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EmptyIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/EmptyIterator.j100664 4644 12243235516 31745 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import org.apache.commons.collections4.ResettableIterator; /** * Provides an implementation of an empty iterator. *

      * This class provides an implementation of an empty iterator. * This class provides for binary compatibility between Commons Collections * 2.1.1 and 3.1 due to issues with IteratorUtils. * * @since 2.1.1 and 3.1 * @version $Id: EmptyIterator.java 1543955 2013-11-20 21:23:53Z tn $ */ public class EmptyIterator extends AbstractEmptyIterator implements ResettableIterator { /** * Singleton instance of the iterator. * @since 3.1 */ @SuppressWarnings("rawtypes") public static final ResettableIterator RESETTABLE_INSTANCE = new EmptyIterator(); /** * Singleton instance of the iterator. * @since 2.1.1 and 3.1 */ @SuppressWarnings("rawtypes") public static final Iterator INSTANCE = RESETTABLE_INSTANCE; /** * Get a typed resettable empty iterator instance. * @param the element type * @return ResettableIterator */ @SuppressWarnings("unchecked") public static ResettableIterator resettableEmptyIterator() { return (ResettableIterator) RESETTABLE_INSTANCE; } /** * Get a typed empty iterator instance. * @param the element type * @return Iterator */ @SuppressWarnings("unchecked") public static Iterator emptyIterator() { return (Iterator) INSTANCE; } /** * Constructor. */ protected EmptyIterator() { super(); } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ObjectArrayListIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/ObjectArrayList100664 15410 12243235516 31757 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.NoSuchElementException; import org.apache.commons.collections4.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.collections4.iterators.ObjectArrayIterator * @see java.util.Iterator * @see java.util.ListIterator * * @since 3.0 * @version $Id: ObjectArrayListIterator.java 1543928 2013-11-20 20:15:35Z tn $ */ public class ObjectArrayListIterator extends ObjectArrayIterator implements 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. */ private int lastItemIndex = -1; //------------------------------------------------------------------------- /** * 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(final E... array) { super(array); } /** * Constructs an ObjectArrayListIterator that will iterate over the values in the * specified array from a specific start index. * * @param array the array to iterate over * @param start the index to start iterating at * @throws NullPointerException if array is null * @throws IndexOutOfBoundsException if the start index is out of bounds */ public ObjectArrayListIterator(final E[] array, final 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(final E[] array, final int start, final 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 > getStartIndex(); } /** * Gets the previous element from the array. * * @return the previous element * @throws NoSuchElementException if there is no previous element */ public E previous() { if (hasPrevious() == false) { throw new NoSuchElementException(); } this.lastItemIndex = --this.index; return this.array[this.index]; } /** * Gets the next element from the array. * * @return the next element * @throws NoSuchElementException if there is no next element */ @Override public E next() { if (hasNext() == false) { throw new NoSuchElementException(); } this.lastItemIndex = this.index; return this.array[this.index++]; } /** * Gets the next index to be retrieved. * * @return the index of the item to be retrieved next */ public int nextIndex() { return this.index - getStartIndex(); } /** * 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 - getStartIndex() - 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(final E obj) { throw new UnsupportedOperationException("add() method is not supported"); } /** * Sets the element under the cursor. *

      * This method sets the element that was returned by the last call * to {@link #next()} of {@link #previous()}. * * Note: {@link ListIterator} implementations that support add() * and remove() only allow set() to be called once per call * to next() or previous (see the {@link ListIterator} * javadoc for more details). Since this implementation does not support * add() or remove(), set() may be * called as often as desired. * * @param obj the object to set into the array * @throws IllegalStateException if next() has not yet been called. * @throws ClassCastException if the object type is unsuitable for the array */ public void set(final E obj) { if (this.lastItemIndex == -1) { throw new IllegalStateException("must call next() or previous() before a call to set()"); } this.array[this.lastItemIndex] = obj; } /** * Resets the iterator back to the start index. */ @Override public void reset() { super.reset(); this.lastItemIndex = -1; } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/PushbackIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/PushbackIterato100664 7316 12243235516 31774 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import org.apache.commons.collections4.ArrayStack; /** * Decorates an iterator to support pushback of elements. *

      * The decorator stores the pushed back elements in a LIFO manner: the last element * that has been pushed back, will be returned as the next element in a call to {@link #next()}. *

      * The decorator does not support the removal operation. Any call to {@link #remove()} will * result in an {@link UnsupportedOperationException}. * * @since 4.0 * @version $Id: PushbackIterator.java 1479763 2013-05-07 05:28:39Z tn $ */ @SuppressWarnings("deprecation") // replace ArrayStack with ArrayDeque when moving to Java 6 public class PushbackIterator implements Iterator { /** The iterator being decorated. */ private final Iterator iterator; /** The LIFO queue containing the pushed back items. */ private ArrayStack items = new ArrayStack(); //----------------------------------------------------------------------- /** * Decorates the specified iterator to support one-element lookahead. *

      * If the iterator is already a {@link PeekingIterator} it is returned directly. * * @param the element type * @param iterator the iterator to decorate * @return a new peeking iterator * @throws IllegalArgumentException if the iterator is null */ public static PushbackIterator pushbackIterator(final Iterator iterator) { if (iterator == null) { throw new IllegalArgumentException("Iterator must not be null"); } if (iterator instanceof PushbackIterator) { @SuppressWarnings("unchecked") // safe cast final PushbackIterator it = (PushbackIterator) iterator; return it; } return new PushbackIterator(iterator); } //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ public PushbackIterator(final Iterator iterator) { super(); this.iterator = iterator; } /** * Push back the given element to the iterator. *

      * Calling {@link #next()} immediately afterwards will return exactly this element. * * @param item the element to push back to the iterator */ public void pushback(final E item) { items.push(item); } public boolean hasNext() { return !items.isEmpty() ? true : iterator.hasNext(); } public E next() { return !items.isEmpty() ? items.pop() : iterator.next(); } /** * This iterator will always throw an {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException(); } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/PeekingIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/iterators/PeekingIterator100664 12160 12243235516 32011 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.iterators; import java.util.Iterator; import java.util.NoSuchElementException; /** * Decorates an iterator to support one-element lookahead while iterating. *

      * The decorator supports the removal operation, but an {@link IllegalStateException} * will be thrown if {@link #remove()} is called directly after a call to * {@link #peek()} or {@link #element()}. * * @since 4.0 * @version $Id: PeekingIterator.java 1543243 2013-11-19 00:32:29Z ggregory $ */ public class PeekingIterator implements Iterator { /** The iterator being decorated. */ private final Iterator iterator; /** Indicates that the decorated iterator is exhausted. */ private boolean exhausted = false; /** Indicates if the lookahead slot is filled. */ private boolean slotFilled = false; /** The current slot for lookahead. */ private E slot; //----------------------------------------------------------------------- /** * Decorates the specified iterator to support one-element lookahead. *

      * If the iterator is already a {@link PeekingIterator} it is returned directly. * * @param the element type * @param iterator the iterator to decorate * @return a new peeking iterator * @throws IllegalArgumentException if the iterator is null */ public static PeekingIterator peekingIterator(final Iterator iterator) { if (iterator == null) { throw new IllegalArgumentException("Iterator must not be null"); } if (iterator instanceof PeekingIterator) { @SuppressWarnings("unchecked") // safe cast final PeekingIterator it = (PeekingIterator) iterator; return it; } return new PeekingIterator(iterator); } //----------------------------------------------------------------------- /** * Constructor. * * @param iterator the iterator to decorate */ public PeekingIterator(final Iterator iterator) { this.iterator = iterator; } private void fill() { if (exhausted || slotFilled) { return; } if (iterator.hasNext()) { slot = iterator.next(); slotFilled = true; } else { exhausted = true; slot = null; slotFilled = false; } } //----------------------------------------------------------------------- public boolean hasNext() { if (exhausted) { return false; } return slotFilled ? true : iterator.hasNext(); } /** * Returns the next element in iteration without advancing the underlying iterator. * If the iterator is already exhausted, null will be returned. *

      * Note: this method does not throw a {@link NoSuchElementException} if the iterator * is already exhausted. If you want such a behavior, use {@link #element()} instead. *

      * The rationale behind this is to follow the {@link java.util.Queue} interface * which uses the same terminology. * * @return the next element from the iterator */ public E peek() { fill(); return exhausted ? null : slot; } /** * Returns the next element in iteration without advancing the underlying iterator. * If the iterator is already exhausted, null will be returned. * * @return the next element from the iterator * @throws NoSuchElementException if the iterator is already exhausted according to {@link #hasNext()} */ public E element() { fill(); if (exhausted) { throw new NoSuchElementException(); } return slot; } public E next() { if (!hasNext()) { throw new NoSuchElementException(); } final E x = slotFilled ? slot : iterator.next(); // reset the lookahead slot slot = null; slotFilled = false; return x; } /** * {@inheritDoc} * * @throws IllegalStateException if {@link #peek()} or {@link #element()} has been called * prior to the call to {@link #remove()} */ public void remove() { if (slotFilled) { throw new IllegalStateException(); } iterator.remove(); } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/ResettableListIterator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/ResettableListIterator.ja100664 2373 12243235516 31717 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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. * * @param the type to iterate over * @since 3.0 * @version $Id: ResettableListIterator.java 1477779 2013-04-30 18:55:24Z tn $ */ public interface ResettableListIterator extends ListIterator, ResettableIterator, OrderedIterator { } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/IterableSortedMap.java100664 2260 12243235516 31147 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.SortedMap; /** * {@link SortedMap} + {@link OrderedMap}. * * @param the type of the keys in the map * @param the type of the values in the map * * @since 4.0 * @version $Id: IterableSortedMap.java 1469004 2013-04-17 17:37:03Z tn $ */ public interface IterableSortedMap extends SortedMap, OrderedMap { } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/CompositeSet.java100664 41137 12243235516 31040 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.io.Serializable; import java.lang.reflect.Array; 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.collections4.CollectionUtils; import org.apache.commons.collections4.iterators.EmptyIterator; import org.apache.commons.collections4.iterators.IteratorChain; import org.apache.commons.collections4.list.UnmodifiableList; /** * 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. *

      * From version 4.0, this class does not extend * {@link org.apache.commons.collections4.collection.CompositeCollection CompositeCollection} * anymore due to its input restrictions (only accepts Sets). * See COLLECTIONS-424 * for more details. * * @since 3.0 * @version $Id: CompositeSet.java 1543273 2013-11-19 00:52:40Z ggregory $ */ public class CompositeSet implements Set, Serializable { /** Serialization version */ private static final long serialVersionUID = 5185069727540378940L; /** SetMutator to handle changes to the collection */ private SetMutator mutator; /** Sets in the composite */ private final List> all = new ArrayList>(); /** * Create an empty CompositeSet. */ public CompositeSet() { super(); } /** * Create a CompositeSet with just set composited. * * @param set the initial set in the composite */ public CompositeSet(final Set set) { super(); addComposited(set); } /** * Create a composite set with sets as the initial set of composited Sets. * * @param sets the initial sets in the composite */ public CompositeSet(final Set... sets) { super(); addComposited(sets); } //----------------------------------------------------------------------- /** * Gets the size of this composite set. *

      * This implementation calls size() on each set. * * @return total number of elements in all contained containers */ public int size() { int size = 0; for (final Set item : all) { size += item.size(); } return size; } /** * Checks whether this composite set is empty. *

      * This implementation calls isEmpty() on each set. * * @return true if all of the contained sets are empty */ public boolean isEmpty() { for (final Set item : all) { if (item.isEmpty() == false) { return false; } } return true; } /** * Checks whether this composite set contains the object. *

      * This implementation calls contains() on each set. * * @param obj the object to search for * @return true if obj is contained in any of the contained sets */ public boolean contains(final Object obj) { for (final Set item : all) { if (item.contains(obj)) { return true; } } return false; } /** * Gets an iterator over all the sets 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 (all.isEmpty()) { return EmptyIterator.emptyIterator(); } final IteratorChain chain = new IteratorChain(); for (final Set item : all) { chain.addIterator(item.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[size()]; int i = 0; for (final Iterator it = 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 the type of the elements in the collection * @param array the array to use, populating if possible * @return an array of all the elements in the collection */ @SuppressWarnings("unchecked") public T[] toArray(final T[] array) { final int size = size(); Object[] result = null; if (array.length >= size) { result = array; } else { result = (Object[]) Array.newInstance(array.getClass().getComponentType(), size); } int offset = 0; for (final Collection item : all) { for (final E e : item) { result[offset++] = e; } } if (result.length > size) { result[size] = null; } return (T[]) result; } /** * Adds an object to the collection, throwing UnsupportedOperationException * unless a SetMutator strategy is specified. * * @param obj the object to add * @return {@code true} if the collection was modified * @throws UnsupportedOperationException if SetMutator hasn't been set or 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(final E obj) { if (mutator == null) { throw new UnsupportedOperationException( "add() is not supported on CompositeSet without a SetMutator strategy"); } return mutator.add(this, all, obj); } /** * 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(final Object obj) { for (final Set set : getSets()) { if (set.contains(obj)) { return set.remove(obj); } } return false; } /** * 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(final Collection coll) { for (final Object item : coll) { if (contains(item) == false) { return false; } } return true; } /** * Adds a collection of elements to this composite, throwing * UnsupportedOperationException unless a SetMutator strategy is specified. * * @param coll the collection to add * @return true if the composite was modified * @throws UnsupportedOperationException if SetMutator hasn't been set or 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(final Collection coll) { if (mutator == null) { throw new UnsupportedOperationException( "addAll() is not supported on CompositeSet without a SetMutator strategy"); } return mutator.addAll(this, all, coll); } /** * Removes the elements in the specified collection from this composite set. *

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

      * This implementation calls retainAll() on each collection. * * @param coll the collection to remove * @return true if the composite was modified * @throws UnsupportedOperationException if retainAll is unsupported */ public boolean retainAll(final Collection coll) { boolean changed = false; for (final Collection item : all) { changed |= item.retainAll(coll); } return changed; } /** * Removes all of the elements from this composite set. *

      * This implementation calls clear() on each set. * * @throws UnsupportedOperationException if clear is unsupported */ public void clear() { for (final Collection coll : all) { coll.clear(); } } //----------------------------------------------------------------------- /** * Specify a SetMutator strategy instance to handle changes. * * @param mutator the mutator to use */ public void setMutator(final SetMutator mutator) { this.mutator = mutator; } /** * Add a Set to this composite. * * @param set the set to add * @throws IllegalArgumentException if a SetMutator is set, but fails to resolve a collision * @throws UnsupportedOperationException if there is no SetMutator set * @throws NullPointerException if {@code set} is null * @see SetMutator */ public synchronized void addComposited(final Set set) { for (final Set existingSet : getSets()) { final Collection intersects = CollectionUtils.intersection(existingSet, set); if (intersects.size() > 0) { if (this.mutator == null) { throw new UnsupportedOperationException( "Collision adding composited set with no SetMutator set"); } getMutator().resolveCollision(this, existingSet, set, intersects); if (CollectionUtils.intersection(existingSet, set).size() > 0) { throw new IllegalArgumentException( "Attempt to add illegal entry unresolved by SetMutator.resolveCollision()"); } } } all.add(set); } /** * Add these Sets to the list of sets in this composite. * * @param set1 the first Set to be appended to the composite * @param set2 the second Set to be appended to the composite */ public void addComposited(final Set set1, final Set set2) { addComposited(set1); addComposited(set2); } /** * Add these Sets to the list of sets in this composite * * @param sets the Sets to be appended to the composite */ public void addComposited(final Set... sets) { for (Set set : sets) { addComposited(set); } } /** * Removes a set from those being decorated in this composite. * * @param set set to be removed */ public void removeComposited(final Set set) { all.remove(set); } //----------------------------------------------------------------------- /** * Returns a new Set containing all of the elements. * * @return A new HashSet containing all of the elements in this composite. * The new collection is not backed by this composite. */ public Set toSet() { return new HashSet(this); } /** * Gets the sets being decorated. * * @return Unmodifiable list of all sets in this composite. */ public List> getSets() { return UnmodifiableList.unmodifiableList(all); } /** * Get the set mutator to be used for this CompositeSet. * @return the set mutator */ protected SetMutator getMutator() { return mutator; } /** * {@inheritDoc} * @see java.util.Set#equals */ @Override public boolean equals(final Object obj) { if (obj instanceof Set) { final Set set = (Set) obj; return set.size() == this.size() && set.containsAll(this); } return false; } /** * {@inheritDoc} * @see java.util.Set#hashCode */ @Override public int hashCode() { int code = 0; for (final E e : this) { code += e == null ? 0 : e.hashCode(); } return code; } /** * Define callbacks for mutation operations. */ public static interface SetMutator extends Serializable { /** * Called when an object is to be added to the composite. * * @param composite the CompositeSet being changed * @param sets all of the Set instances in this CompositeSet * @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 */ boolean add(CompositeSet composite, List> sets, E obj); /** * Called when a collection is to be added to the composite. * * @param composite the CompositeSet being changed * @param sets all of the Set instances in this CompositeSet * @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 */ boolean addAll(CompositeSet composite, List> sets, Collection coll); /** * 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 the existing and added sets */ void resolveCollision(CompositeSet comp, Set existing, Set added, Collection intersects); } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/TransformedSortedSet.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/TransformedSortedSet.100664 13004 12243235516 31671 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Comparator; import java.util.SortedSet; import org.apache.commons.collections4.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 3.0 * @version $Id: TransformedSortedSet.java 1494280 2013-06-18 20:07:04Z tn $ */ 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. * Contrast this with {@link #transformedSortedSet(SortedSet, Transformer)}. * * @param the element type * @param set the set to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed {@link SortedSet} * @throws IllegalArgumentException if set or transformer is null * @since 4.0 */ public static TransformedSortedSet transformingSortedSet(final SortedSet set, final Transformer transformer) { return new TransformedSortedSet(set, transformer); } /** * Factory method to create a transforming sorted set that will transform * existing contents of the specified sorted set. *

      * If there are any elements already in the set being decorated, they * will be transformed by this method. * Contrast this with {@link #transformingSortedSet(SortedSet, Transformer)}. * * @param the element type * @param set the set to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed {@link SortedSet} * @throws IllegalArgumentException if set or transformer is null * @since 4.0 */ public static TransformedSortedSet transformedSortedSet(final SortedSet set, final Transformer transformer) { final TransformedSortedSet decorated = new TransformedSortedSet(set, transformer); if (transformer != null && set != null && set.size() > 0) { @SuppressWarnings("unchecked") // set is type E final E[] values = (E[]) set.toArray(); // NOPMD - false positive for generics set.clear(); for (final E value : values) { decorated.decorated().add(transformer.transform(value)); } } return decorated; } //----------------------------------------------------------------------- /** * 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(final SortedSet set, final Transformer transformer) { super(set, transformer); } /** * Gets the decorated set. * * @return the decorated set */ protected SortedSet getSortedSet() { return (SortedSet) decorated(); } //----------------------------------------------------------------------- public E first() { return getSortedSet().first(); } public E last() { return getSortedSet().last(); } public Comparator comparator() { return getSortedSet().comparator(); } //----------------------------------------------------------------------- public SortedSet subSet(final E fromElement, final E toElement) { final SortedSet set = getSortedSet().subSet(fromElement, toElement); return new TransformedSortedSet(set, transformer); } public SortedSet headSet(final E toElement) { final SortedSet set = getSortedSet().headSet(toElement); return new TransformedSortedSet(set, transformer); } public SortedSet tailSet(final E fromElement) { final SortedSet set = getSortedSet().tailSet(fromElement); return new TransformedSortedSet(set, transformer); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/TransformedSet.java100664 10332 12243235516 31353 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Set; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.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 3.0 * @version $Id: TransformedSet.java 1479406 2013-05-05 22:02:01Z tn $ */ 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. * Contrast this with {@link #transformedSet(Set, Transformer)}. * * @param the element type * @param set the set to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed set * @throws IllegalArgumentException if set or transformer is null * @since 4.0 */ public static TransformedSet transformingSet(final Set set, final Transformer transformer) { return new TransformedSet(set, transformer); } /** * Factory method to create a transforming set that will transform * existing contents of the specified set. *

      * If there are any elements already in the set being decorated, they * will be transformed by this method. * Contrast this with {@link #transformingSet(Set, Transformer)}. * * @param the element type * @param set the set to decorate, must not be null * @param transformer the transformer to use for conversion, must not be null * @return a new transformed set * @throws IllegalArgumentException if set or transformer is null * @since 4.0 */ public static Set transformedSet(final Set set, final Transformer transformer) { final TransformedSet decorated = new TransformedSet(set, transformer); if (transformer != null && set != null && set.size() > 0) { @SuppressWarnings("unchecked") // set is type E final E[] values = (E[]) set.toArray(); // NOPMD - false positive for generics set.clear(); for (final E value : values) { decorated.decorated().add(transformer.transform(value)); } } return decorated; } //----------------------------------------------------------------------- /** * 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(final Set set, final Transformer transformer) { super(set, transformer); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/UnmodifiableSet.java100664 6724 12243235516 31457 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Collection; import java.util.Iterator; import java.util.Set; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableIterator; /** * Decorates another Set to ensure it can't be altered. *

      * This class is Serializable from Commons Collections 3.1. *

      * Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableSet.java 1533984 2013-10-20 21:12:51Z tn $ */ public final class UnmodifiableSet extends AbstractSerializableSetDecorator implements Unmodifiable { /** Serialization version */ private static final long serialVersionUID = 6499119872185240161L; /** * Factory method to create an unmodifiable set. * * @param the element type * @param set the set to decorate, must not be null * @return a new unmodifiable set * @throws IllegalArgumentException if set is null * @since 4.0 */ public static Set unmodifiableSet(final Set set) { if (set instanceof Unmodifiable) { @SuppressWarnings("unchecked") // safe to upcast final Set tmpSet = (Set) set; return tmpSet; } 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 */ @SuppressWarnings("unchecked") // safe to upcast private UnmodifiableSet(final Set set) { super((Set) set); } //----------------------------------------------------------------------- @Override public Iterator iterator() { return UnmodifiableIterator.unmodifiableIterator(decorated().iterator()); } @Override public boolean add(final E object) { throw new UnsupportedOperationException(); } @Override public boolean addAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException(); } } ././@LongLink100644 0 0 165 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/AbstractSerializableSetDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/AbstractSerializableS100664 4540 12243235516 31674 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.Set; /** * Serializable subclass of AbstractSetDecorator. * * @since 3.1 * @version $Id: AbstractSerializableSetDecorator.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public abstract class AbstractSerializableSetDecorator extends AbstractSetDecorator { /** Serialization version */ private static final long serialVersionUID = 1229469966212206107L; /** * Constructor. * * @param set the list to decorate, must not be null * @throws IllegalArgumentException if set is null */ protected AbstractSerializableSetDecorator(final Set set) { super(set); } //----------------------------------------------------------------------- /** * Write the set out using a custom routine. * * @param out the output stream * @throws IOException */ private void writeObject(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(decorated()); } /** * Read the set in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); setCollection((Collection) in.readObject()); } } ././@LongLink100644 0 0 157 12243235652 10262 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/AbstractSortedSetDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/AbstractSortedSetDeco100664 5327 12243235516 31656 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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. * * @param the type of the elements in the sorted set * @since 3.0 * @version $Id: AbstractSortedSetDecorator.java 1477756 2013-04-30 18:31:13Z tn $ */ public abstract class AbstractSortedSetDecorator extends AbstractSetDecorator implements SortedSet { /** Serialization version */ private static final long serialVersionUID = -3462240946294214398L; /** * Constructor only used in deserialization, do not use otherwise. * @since 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(final Set set) { super(set); } /** * Gets the set being decorated. * * @return the decorated set */ @Override protected SortedSet decorated() { return (SortedSet) super.decorated(); } //----------------------------------------------------------------------- public SortedSet subSet(final E fromElement, final E toElement) { return decorated().subSet(fromElement, toElement); } public SortedSet headSet(final E toElement) { return decorated().headSet(toElement); } public SortedSet tailSet(final E fromElement) { return decorated().tailSet(fromElement); } public E first() { return decorated().first(); } public E last() { return decorated().last(); } public Comparator comparator() { return decorated().comparator(); } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/PredicatedSortedSet.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/PredicatedSortedSet.j100664 10524 12243235516 31627 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Comparator; import java.util.SortedSet; import org.apache.commons.collections4.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 3.0 * @version $Id: PredicatedSortedSet.java 1479406 2013-05-05 22:02:01Z tn $ */ 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 the element type * @param set the set to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @return a new predicated sorted set. * @throws IllegalArgumentException if set or predicate is null * @throws IllegalArgumentException if the set contains invalid elements * @since 4.0 */ public static PredicatedSortedSet predicatedSortedSet(final SortedSet set, final 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(final SortedSet set, final Predicate predicate) { super(set, predicate); } /** * Gets the sorted set being decorated. * * @return the decorated sorted set */ @Override protected SortedSet decorated() { return (SortedSet) super.decorated(); } //----------------------------------------------------------------------- public Comparator comparator() { return decorated().comparator(); } public E first() { return decorated().first(); } public E last() { return decorated().last(); } public SortedSet subSet(final E fromElement, final E toElement) { final SortedSet sub = decorated().subSet(fromElement, toElement); return new PredicatedSortedSet(sub, predicate); } public SortedSet headSet(final E toElement) { final SortedSet sub = decorated().headSet(toElement); return new PredicatedSortedSet(sub, predicate); } public SortedSet tailSet(final E fromElement) { final SortedSet sub = decorated().tailSet(fromElement); return new PredicatedSortedSet(sub, predicate); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/package-info.java100664 3442 12243235516 30723 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This 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: *
        *
      • Unmodifiable - ensures the collection cannot be altered *
      • Predicated - ensures that only elements that are valid according to a predicate can be added *
      • Transformed - transforms each element added *
      • ListOrdered - ensures that insertion order is retained *
      • MapBackedSet - a set formed by decorating a Map *
      * * @version $Id: package-info.java 1469004 2013-04-17 17:37:03Z tn $ */ package org.apache.commons.collections4.set; commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/PredicatedSet.java100664 6514 12243235516 31122 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Set; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.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 3.0 * @version $Id: PredicatedSet.java 1479406 2013-05-05 22:02:01Z tn $ */ 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 the element type * @param set the set to decorate, must not be null * @param predicate the predicate to use for validation, must not be null * @return a decorated set * @throws IllegalArgumentException if set or predicate is null * @throws IllegalArgumentException if the set contains invalid elements * @since 4.0 */ public static PredicatedSet predicatedSet(final Set set, final 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(final Set set, final Predicate predicate) { super(set, predicate); } /** * Gets the set being decorated. * * @return the decorated set */ @Override protected Set decorated() { return (Set) super.decorated(); } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/AbstractSetDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/AbstractSetDecorator.100664 4041 12243235516 31613 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.util.Set; import org.apache.commons.collections4.collection.AbstractCollectionDecorator; /** * Decorates another Set to provide additional behaviour. *

      * Methods are forwarded directly to the decorated set. * * @param the type of the elements in the set * @since 3.0 * @version $Id: AbstractSetDecorator.java 1477756 2013-04-30 18:31:13Z tn $ */ public abstract class AbstractSetDecorator extends AbstractCollectionDecorator implements Set { /** Serialization version */ private static final long serialVersionUID = -4678668309576958546L; /** * Constructor only used in deserialization, do not use otherwise. * @since 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(final Set set) { super(set); } /** * Gets the set being decorated. * * @return the decorated set */ @Override protected Set decorated() { return (Set) super.decorated(); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/ListOrderedSet.java100664 31402 12243235516 31310 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; 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.collections4.OrderedIterator; import org.apache.commons.collections4.iterators.AbstractIteratorDecorator; import org.apache.commons.collections4.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 incompatible with a * set. *

      * This class is Serializable from Commons Collections 3.1. * * @since 3.0 * @version $Id: ListOrderedSet.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public class ListOrderedSet extends AbstractSerializableSetDecorator { /** Serialization version */ private static final long serialVersionUID = -228664372470420141L; /** Internal list to hold the sequence of objects */ private 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 the element type * @param set the set to decorate, must be empty and not null * @param list the list to decorate, must be empty and not null * @return a new ordered set * @throws IllegalArgumentException if set or list is null * @throws IllegalArgumentException if either the set or list is not empty * @since 4.0 */ public static ListOrderedSet listOrderedSet(final Set set, final 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 the element type * @param set the set to decorate, must not be null * @return a new ordered set * @throws IllegalArgumentException if set is null * @since 4.0 */ public static ListOrderedSet listOrderedSet(final 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 the element type * @param list the list to decorate, must not be null * @return a new ordered set * @throws IllegalArgumentException if list is null * @since 4.0 */ public static ListOrderedSet listOrderedSet(final List list) { if (list == null) { throw new IllegalArgumentException("List must not be null"); } final 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 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(final 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(final Set set, final 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.unmodifiableList(setOrder); } // ----------------------------------------------------------------------- @Override public void clear() { decorated().clear(); setOrder.clear(); } @Override public OrderedIterator iterator() { return new OrderedSetIterator(setOrder.listIterator(), decorated()); } @Override public boolean add(final E object) { if (decorated().add(object)) { setOrder.add(object); return true; } return false; } @Override public boolean addAll(final Collection coll) { boolean result = false; for (final E e : coll) { result |= add(e); } return result; } @Override public boolean remove(final Object object) { final boolean result = decorated().remove(object); if (result) { setOrder.remove(object); } return result; } @Override public boolean removeAll(final Collection coll) { boolean result = false; for (final Object name : coll) { result |= remove(name); } return result; } @Override public boolean retainAll(final Collection coll) { final Set collectionRetainAll = new HashSet(); for (final Object next : coll) { if (decorated().contains(next)) { collectionRetainAll.add(next); } } if (collectionRetainAll.size() == decorated().size()) { return false; } if (collectionRetainAll.size() == 0) { clear(); } else { for (final Iterator it = iterator(); it.hasNext();) { if (!collectionRetainAll.contains(it.next())) { it.remove(); } } } return true; } @Override public Object[] toArray() { return setOrder.toArray(); } @Override public T[] toArray(final T a[]) { return setOrder.toArray(a); } // ----------------------------------------------------------------------- // Additional methods that comply to the {@link List} interface // ----------------------------------------------------------------------- /** * Returns the element at the specified position in this ordered set. * * @param index the position of the element in the ordered {@link Set}. * @return the element at position {@code index} * @see List#get(int) */ public E get(final int index) { return setOrder.get(index); } /** * Returns the index of the first occurrence of the specified element in * ordered set. * * @param object the element to search for * @return the index of the first occurrence of the object, or {@code -1} if * this ordered set does not contain this object * @see List#indexOf(Object) */ public int indexOf(final Object object) { return setOrder.indexOf(object); } /** * Inserts the specified element at the specified position if it is not yet * contained in this ordered set (optional operation). Shifts the element * currently at this position and any subsequent elements to the right. * * @param index the index at which the element is to be inserted * @param object the element to be inserted * @see List#add(int, Object) */ public void add(final int index, final E object) { if (!contains(object)) { decorated().add(object); setOrder.add(index, object); } } /** * Inserts all elements in the specified collection not yet contained in the * ordered set at the specified position (optional operation). Shifts the * element currently at the position and all subsequent elements to the * right. * * @param index the position to insert the elements * @param coll the collection containing the elements to be inserted * @return {@code true} if this ordered set changed as a result of the call * @see List#addAll(int, Collection) */ public boolean addAll(final int index, final Collection coll) { boolean changed = false; // collect all elements to be added for performance reasons final List toAdd = new ArrayList(); for (final E e : coll) { if (contains(e)) { continue; } decorated().add(e); toAdd.add(e); changed = true; } if (changed) { setOrder.addAll(index, toAdd); } return changed; } /** * Removes the element at the specified position from the ordered set. * Shifts any subsequent elements to the left. * * @param index the index of the element to be removed * @return the element that has been remove from the ordered set * @see List#remove(int) */ public Object remove(final int index) { final 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. * * @return a string representation of the ordered set */ // Fortunately List.toString and Set.toString look the same @Override public String toString() { return setOrder.toString(); } // ----------------------------------------------------------------------- /** * Internal iterator handle remove. */ static class OrderedSetIterator extends AbstractIteratorDecorator implements OrderedIterator { /** Object we iterate on */ private final Collection set; /** Last object retrieved */ private E last; private OrderedSetIterator(final ListIterator iterator, final Collection set) { super(iterator); this.set = set; } @Override public E next() { last = getIterator().next(); return last; } @Override public void remove() { set.remove(last); getIterator().remove(); last = null; } public boolean hasPrevious() { return ((ListIterator) getIterator()).hasPrevious(); } public E previous() { last = ((ListIterator) getIterator()).previous(); return last; } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/MapBackedSet.java100664 12010 12243235516 30671 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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 3.1 * @version $Id: MapBackedSet.java 1479406 2013-05-05 22:02:01Z tn $ */ public final class MapBackedSet implements Set, Serializable { /** Serialization version */ private static final long serialVersionUID = 6723912213766056587L; /** The map being used as the backing store */ private final Map map; /** The dummyValue to use */ private final V dummyValue; /** * Factory method to create a set from a map. * * @param the element type * @param the dummy value type in the map * @param map the map to decorate, must not be null * @return a new map backed set * @throws IllegalArgumentException if set is null * @since 4.0 */ public static MapBackedSet mapBackedSet(final Map map) { return mapBackedSet(map, null); } /** * Factory method to create a set from a map. * * @param the element type * @param the dummy value type in the map * @param map the map to decorate, must not be null * @param dummyValue the dummy value to use * @return a new map backed set * @throws IllegalArgumentException if map is null * @since 4.0 */ public static MapBackedSet mapBackedSet(final Map map, final V dummyValue) { if (map == null) { throw new IllegalArgumentException("The map must not be null"); } return new MapBackedSet(map, dummyValue); } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param map the map to decorate, must not be null * @param dummyValue the dummy value to use * @throws IllegalArgumentException if map is null */ private MapBackedSet(final Map map, final V dummyValue) { super(); this.map = map; this.dummyValue = dummyValue; } //----------------------------------------------------------------------- public int size() { return map.size(); } public boolean isEmpty() { return map.isEmpty(); } public Iterator iterator() { return map.keySet().iterator(); } public boolean contains(final Object obj) { return map.containsKey(obj); } public boolean containsAll(final Collection coll) { return map.keySet().containsAll(coll); } public boolean add(final E obj) { final int size = map.size(); map.put(obj, dummyValue); return map.size() != size; } public boolean addAll(final Collection coll) { final int size = map.size(); for (final E e : coll) { map.put(e, dummyValue); } return map.size() != size; } public boolean remove(final Object obj) { final int size = map.size(); map.remove(obj); return map.size() != size; } public boolean removeAll(final Collection coll) { return map.keySet().removeAll(coll); } public boolean retainAll(final Collection coll) { return map.keySet().retainAll(coll); } public void clear() { map.clear(); } public Object[] toArray() { return map.keySet().toArray(); } public T[] toArray(final T[] array) { return map.keySet().toArray(array); } @Override public boolean equals(final Object obj) { return map.keySet().equals(obj); } @Override public int hashCode() { return map.keySet().hashCode(); } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/UnmodifiableSortedSet.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/set/UnmodifiableSortedSet100664 11666 12243235516 31741 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.set; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Collection; import java.util.Iterator; import java.util.SortedSet; import org.apache.commons.collections4.Unmodifiable; import org.apache.commons.collections4.iterators.UnmodifiableIterator; /** * Decorates another SortedSet to ensure it can't be altered. *

      * This class is Serializable from Commons Collections 3.1. *

      * Attempts to modify it will result in an UnsupportedOperationException. * * @since 3.0 * @version $Id: UnmodifiableSortedSet.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class UnmodifiableSortedSet extends AbstractSortedSetDecorator implements Unmodifiable { /** Serialization version */ private static final long serialVersionUID = -725356885467962424L; /** * Factory method to create an unmodifiable set. * * @param the element type * @param set the set to decorate, must not be null * @return a new unmodifiable {@link SortedSet} * @throws IllegalArgumentException if set is null * @since 4.0 */ public static SortedSet unmodifiableSortedSet(final 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(final ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeObject(decorated()); } /** * Read the collection in using a custom routine. * * @param in the input stream * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); setCollection((Collection) in.readObject()); // (1) } //----------------------------------------------------------------------- /** * Constructor that wraps (not copies). * * @param set the set to decorate, must not be null * @throws IllegalArgumentException if set is null */ private UnmodifiableSortedSet(final SortedSet set) { super(set); } //----------------------------------------------------------------------- @Override public Iterator iterator() { return UnmodifiableIterator.unmodifiableIterator(decorated().iterator()); } @Override public boolean add(final E object) { throw new UnsupportedOperationException(); } @Override public boolean addAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(final Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(final Collection coll) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(final Collection coll) { throw new UnsupportedOperationException(); } //----------------------------------------------------------------------- @Override public SortedSet subSet(final E fromElement, final E toElement) { final SortedSet sub = decorated().subSet(fromElement, toElement); return new UnmodifiableSortedSet(sub); } @Override public SortedSet headSet(final E toElement) { final SortedSet sub = decorated().headSet(toElement); return new UnmodifiableSortedSet(sub); } @Override public SortedSet tailSet(final E fromElement) { final SortedSet sub = decorated().tailSet(fromElement); return new UnmodifiableSortedSet(sub); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/BoundedCollection.java100664 3271 12243235516 31200 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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 3.0 * @version $Id: BoundedCollection.java 1477779 2013-04-30 18:55:24Z tn $ */ 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(); } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/PrototypeFactory.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/PrototypeFactory100664 16504 12243235517 32110 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.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.collections4.Factory; import org.apache.commons.collections4.FunctorException; /** * Factory implementation that creates a new instance each time based on a prototype. * * @since 3.0 * @version $Id: PrototypeFactory.java 1477798 2013-04-30 19:49:02Z tn $ */ 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 the type the factory creates * @param prototype the object to clone each time in the factory * @return the prototype factory, or a {@link ConstantFactory#NULL_INSTANCE} if * the {@code prototype} is {@code null} * @throws IllegalArgumentException if the prototype cannot be cloned */ @SuppressWarnings("unchecked") public static Factory prototypeFactory(final T prototype) { if (prototype == null) { return ConstantFactory.constantFactory(null); } try { final Method method = prototype.getClass().getMethod("clone", (Class[]) null); return new PrototypeCloneFactory(prototype, method); } catch (final NoSuchMethodException ex) { try { prototype.getClass().getConstructor(new Class[] { prototype.getClass() }); return new InstantiateFactory( (Class) prototype.getClass(), new Class[] { prototype.getClass() }, new Object[] { prototype }); } catch (final NoSuchMethodException ex2) { if (prototype instanceof Serializable) { return (Factory) new PrototypeSerializationFactory((Serializable) prototype); } } } throw new IllegalArgumentException("The prototype must be cloneable via a public clone method"); } /** * Restricted constructor. */ 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 T iPrototype; /** The method used to clone */ private transient Method iCloneMethod; /** * Constructor to store prototype. */ private PrototypeCloneFactory(final T prototype, final 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 (final 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 */ @SuppressWarnings("unchecked") public T create() { // needed for post-serialization if (iCloneMethod == null) { findCloneMethod(); } try { return (T) iCloneMethod.invoke(iPrototype, (Object[]) null); } catch (final IllegalAccessException ex) { throw new FunctorException("PrototypeCloneFactory: Clone method must be public", ex); } catch (final 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 T iPrototype; /** * Constructor to store prototype */ private PrototypeSerializationFactory(final T prototype) { super(); iPrototype = prototype; } /** * Creates an object using serialization. * * @return the new object */ @SuppressWarnings("unchecked") public T create() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(512); ByteArrayInputStream bais = null; try { final ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(iPrototype); bais = new ByteArrayInputStream(baos.toByteArray()); final ObjectInputStream in = new ObjectInputStream(bais); return (T) in.readObject(); } catch (final ClassNotFoundException ex) { throw new FunctorException(ex); } catch (final IOException ex) { throw new FunctorException(ex); } finally { try { if (bais != null) { bais.close(); } } catch (final IOException ex) { // ignore } try { baos.close(); } catch (final IOException ex) { // ignore } } } } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ClosureTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ClosureTransform100664 5316 12243235517 32042 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.Transformer; /** * Transformer implementation that calls a Closure using the input object * and then returns the input. * * @since 3.0 * @version $Id: ClosureTransformer.java 1477798 2013-04-30 19:49:02Z tn $ */ 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 the type of the object to transform * @param closure the closure to call, not null * @return the closure transformer * @throws IllegalArgumentException if the closure is null */ public static Transformer closureTransformer(final Closure closure) { if (closure == null) { throw new IllegalArgumentException("Closure must not be null"); } return new ClosureTransformer(closure); } /** * Constructor that performs no validation. * Use closureTransformer if you want that. * * @param closure the closure to call, not null */ public ClosureTransformer(final Closure closure) { super(); iClosure = closure; } /** * Transforms the input to result by executing a closure. * * @param input the input object to transform * @return the transformed result */ public T transform(final T input) { iClosure.execute(input); return input; } /** * Gets the closure. * * @return the closure * @since 3.1 */ public Closure getClosure() { return iClosure; } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NullIsFalsePredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NullIsFalsePredi100664 5670 12243235517 31702 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns false if the input is null. * * @since 3.0 * @version $Id: NullIsFalsePredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class NullIsFalsePredicate implements 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 the type that the predicate queries * @param predicate the predicate to decorate, not null * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate nullIsFalsePredicate(final Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new NullIsFalsePredicate(predicate); } /** * Constructor that performs no validation. * Use nullIsFalsePredicate if you want that. * * @param predicate the predicate to call after the null check */ public NullIsFalsePredicate(final 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(final T object) { if (object == null) { return false; } return iPredicate.evaluate(object); } /** * Gets the predicate being decorated. * * @return the predicate as the only element in an array * @since 3.1 */ @SuppressWarnings("unchecked") public Predicate[] getPredicates() { return new Predicate[] { iPredicate }; } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ConstantTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ConstantTransfor100664 10017 12243235517 32054 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.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 3.0 * @version $Id: ConstantTransformer.java 1543950 2013-11-20 21:13:35Z tn $ */ public class ConstantTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 6374440726369055124L; /** Returns null each time */ @SuppressWarnings("rawtypes") public static final Transformer NULL_INSTANCE = new ConstantTransformer(null); /** The closures to call in turn */ private final O iConstant; /** * Get a typed null instance. * * @param the input type * @param the output type * @return Transformer that always returns null. */ @SuppressWarnings("unchecked") // The null transformer works for all object types public static Transformer nullTransformer() { return (Transformer) NULL_INSTANCE; } /** * Transformer method that performs validation. * * @param the input type * @param the output type * @param constantToReturn the constant object to return each time in the factory * @return the constant factory. */ public static Transformer constantTransformer(final O constantToReturn) { if (constantToReturn == null) { return nullTransformer(); } return new ConstantTransformer(constantToReturn); } /** * Constructor that performs no validation. * Use constantTransformer if you want that. * * @param constantToReturn the constant to return each time */ public ConstantTransformer(final O 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 O transform(final I input) { return iConstant; } /** * Gets the constant. * * @return the constant * @since 3.1 */ public O getConstant() { return iConstant; } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof ConstantTransformer == false) { return false; } final Object otherConstant = ((ConstantTransformer) obj).getConstant(); return otherConstant == getConstant() || otherConstant != null && otherConstant.equals(getConstant()); } /** * {@inheritDoc} */ @Override public int hashCode() { int result = "ConstantTransformer".hashCode() << 2; if (getConstant() != null) { result |= getConstant().hashCode(); } return result; } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NullPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NullPredicate.ja100664 4164 12243235517 31656 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns true if the input is null. * * @since 3.0 * @version $Id: NullPredicate.java 1543950 2013-11-20 21:13:35Z tn $ */ public final class NullPredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7533784454832764388L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") public static final Predicate INSTANCE = new NullPredicate(); /** * Factory returning the singleton instance. * * @param the type that the predicate queries * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") public static Predicate nullPredicate() { return (Predicate) 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(final T object) { return object == null; } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/TransformedPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/TransformedPredi100664 7440 12243235517 32002 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.Transformer; /** * Predicate implementation that transforms the given object before invoking * another Predicate. * * @since 3.1 * @version $Id: TransformedPredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class TransformedPredicate implements 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 the type that the predicate queries * @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 transformedPredicate(final Transformer transformer, final 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 transformedPredicate if you want that. * * @param transformer the transformer to use * @param predicate the predicate to decorate */ public TransformedPredicate(final Transformer transformer, final 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(final T object) { final T result = iTransformer.transform(object); return iPredicate.evaluate(result); } /** * Gets the predicate being decorated. * * @return the predicate as the only element in an array * @since 3.1 */ @SuppressWarnings("unchecked") public Predicate[] getPredicates() { return new Predicate[] {iPredicate}; } /** * Gets the transformer in use. * * @return the transformer */ public Transformer getTransformer() { return iTransformer; } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/DefaultEquator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/DefaultEquator.j100664 5060 12243235517 31703 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Equator; /** * Default {@link Equator} implementation. * * @param the types of object this {@link Equator} can evaluate. * @since 4.0 * @version $Id: DefaultEquator.java 1543950 2013-11-20 21:13:35Z tn $ */ public class DefaultEquator implements Equator, Serializable { /** Serial version UID */ private static final long serialVersionUID = 825802648423525485L; /** Static instance */ @SuppressWarnings("rawtypes") // the static instance works for all types public static final DefaultEquator INSTANCE = new DefaultEquator(); /** * Hashcode used for null objects. */ public static final int HASHCODE_NULL = -1; /** * Factory returning the typed singleton instance. * * @param the object type * @return the singleton instance */ @SuppressWarnings("unchecked") // the static instance works for all types public static DefaultEquator defaultEquator() { return (DefaultEquator) DefaultEquator.INSTANCE; } /** * Restricted constructor. */ private DefaultEquator() { super(); } /** * {@inheritDoc} Delegates to {@link Object#equals(Object)}. */ public boolean equate(final T o1, final T o2) { return o1 == o2 || o1 != null && o1.equals(o2); } /** * {@inheritDoc} * * @return o.hashCode() if o is non- * null, else {@link #HASHCODE_NULL}. */ public int hash(final T o) { return o == null ? HASHCODE_NULL : o.hashCode(); } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/InstanceofPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/InstanceofPredic100664 5110 12243235517 31742 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns true if the input is an instanceof * the type stored in this predicate. * * @since 3.0 * @version $Id: InstanceofPredicate.java 1476582 2013-04-27 14:13:54Z tn $ */ 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 instanceOfPredicate(final 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 instanceOfPredicate if you want that. * * @param type the type to check for */ public InstanceofPredicate(final 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(final Object object) { return iType.isInstance(object); } /** * Gets the type to compare to. * * @return the type * @since 3.1 */ public Class getType() { return iType; } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NOPTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NOPTransformer.j100664 4140 12243235517 31633 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Transformer; /** * Transformer implementation that does nothing. * * @since 3.0 * @version $Id: NOPTransformer.java 1543950 2013-11-20 21:13:35Z tn $ */ public class NOPTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 2133891748318574490L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") public static final Transformer INSTANCE = new NOPTransformer(); /** * Factory returning the singleton instance. * * @param the input/output type * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") public static Transformer nopTransformer() { return (Transformer) 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 T transform(final T input) { return input; } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NotNullPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NotNullPredicate100664 4225 12243235517 31744 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns true if the input is not null. * * @since 3.0 * @version $Id: NotNullPredicate.java 1543950 2013-11-20 21:13:35Z tn $ */ public final class NotNullPredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7533784454832764388L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") public static final Predicate INSTANCE = new NotNullPredicate(); /** * Factory returning the singleton instance. * * @param the type that the predicate queries * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") public static Predicate notNullPredicate() { return (Predicate) 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(final T object) { return object != null; } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 165 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/AbstractQuantifierPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/AbstractQuantifi100664 3576 12243235517 32004 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Abstract base class for quantification predicates, e.g. All, Any, None. * * @since 4.0 * @version $Id: AbstractQuantifierPredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public abstract class AbstractQuantifierPredicate implements PredicateDecorator, Serializable { /** Serial version UID */ private static final long serialVersionUID = -3094696765038308799L; /** The array of predicates to call */ protected final Predicate[] iPredicates; /** * Constructor that performs no validation. * * @param predicates the predicates to check, not cloned, not null */ public AbstractQuantifierPredicate(final Predicate... predicates) { iPredicates = predicates; } /** * Gets the predicates. * * @return a copy of the predicates * @since 3.1 */ public Predicate[] getPredicates() { return FunctorUtils.copy(iPredicates); } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ExceptionTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ExceptionTransfo100664 4604 12243235517 32024 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.FunctorException; import org.apache.commons.collections4.Transformer; /** * Transformer implementation that always throws an exception. * * @since 3.0 * @version $Id: ExceptionTransformer.java 1543950 2013-11-20 21:13:35Z tn $ */ public final class ExceptionTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7179106032121985545L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") // the static instance works for all types public static final Transformer INSTANCE = new ExceptionTransformer(); /** * Factory returning the singleton instance. * * @param the input type * @param the output type * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") // the static instance works for all types public static Transformer exceptionTransformer() { return (Transformer) INSTANCE; } /** * Restricted constructor. */ private ExceptionTransformer() { super(); } /** * Transforms the input to result by cloning it. * * @param input the input object to transform * @return never * @throws FunctorException always */ public O transform(final I input) { throw new FunctorException("ExceptionTransformer invoked"); } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ComparatorPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ComparatorPredic100664 16350 12243235517 32010 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import java.util.Comparator; import org.apache.commons.collections4.Predicate; /** * Predicate that compares the input object with the one stored in the predicate using a comparator. * In addition, the comparator result can be evaluated in accordance to a supplied criterion value. * * In order to demonstrate the use of the predicate, the following variables are declared: * *
           * Integer ONE = Integer.valueOf(1);
           * Integer TWO = Integer.valueOf(2);
           *
           * Comparator comparator = new Comparator() {
           *
           *     public int compare(Object first, Object second) {
           *         return ((Integer) second) - ((Integer) first);
           *     }
           *
           * };
           * 
          * * Using the declared variables, the ComparatorPredicate can be used used in the * following way: * *
           * ComparatorPredicate.comparatorPredicate(ONE, comparator).evaluate(TWO);
           * 
          * * The input variable TWO in compared to the stored variable ONE using * the supplied comparator. This is the default usage of the predicate and will return * true if the underlying comparator returns 0. In addition to the default * usage of the predicate, it is possible to evaluate the comparator's result in several ways. The * following {@link Criterion} enumeration values are provided by the predicate: *

          * *
            *
          • EQUAL
          • *
          • GREATER
          • *
          • GREATER_OR_EQUAL
          • *
          • LESS
          • *
          • LESS_OR_EQUAL
          • *
          * * The following examples demonstrates how these constants can be used in order to manipulate the * evaluation of a comparator result. * *
           * ComparatorPredicate.comparatorPredicate(ONE, comparator,ComparatorPredicate.Criterion.GREATER).evaluate(TWO);
           * 
          * * The input variable TWO is compared to the stored variable ONE using the supplied comparator * using the GREATER evaluation criterion constant. This instructs the predicate to * return true if the comparator returns a value greater than 0. * * @since 4.0 * @version $Id: ComparatorPredicate.java 1477798 2013-04-30 19:49:02Z tn $ */ public class ComparatorPredicate implements Predicate, Serializable { private static final long serialVersionUID = -1863209236504077399L; public enum Criterion { EQUAL, GREATER, LESS, GREATER_OR_EQUAL, LESS_OR_EQUAL, } // Instance variables: /** The internal object to compare with */ private final T object; /** The comparator to use for comparison */ private final Comparator comparator; /** The comparison evaluation criterion to use */ private final Criterion criterion; /** * Factory to create the comparator predicate * * @param the type that the predicate queries * @param object the object to compare to * @param comparator the comparator to use for comparison * @return the predicate * @throws IllegalArgumentException if comparator is null */ public static Predicate comparatorPredicate(final T object, final Comparator comparator) { return comparatorPredicate(object, comparator, Criterion.EQUAL); } /** * Factory to create the comparator predicate * * @param the type that the predicate queries * @param object the object to compare to * @param comparator the comparator to use for comparison * @param criterion the criterion to use to evaluate comparison * @return the predicate * @throws IllegalArgumentException if comparator is null of criterion is invalid */ public static Predicate comparatorPredicate(final T object, final Comparator comparator, final Criterion criterion) { if (comparator == null) { throw new IllegalArgumentException("Comparator must not be null."); } if (criterion == null) { throw new IllegalArgumentException("Criterion must not be null."); } return new ComparatorPredicate(object, comparator, criterion); } /** * Constructor that performs no validation. * Use comparatorPredicate if you want that. * * @param object the object to compare to * @param comparator the comparator to use for comparison * @param criterion the criterion to use to evaluate comparison */ public ComparatorPredicate(final T object, final Comparator comparator, final Criterion criterion) { super(); this.object = object; this.comparator = comparator; this.criterion = criterion; } /** * Evaluates the predicate. The predicate evaluates to true in the following cases: * *
            *
          • comparator.compare(object, input) == 0 && criterion == EQUAL
          • *
          • comparator.compare(object, input) < 0 && criterion == LESS
          • *
          • comparator.compare(object, input) > 0 && criterion == GREATER
          • *
          • comparator.compare(object, input) >= 0 && criterion == GREATER_OR_EQUAL
          • *
          • comparator.compare(object, input) <= 0 && criterion == LESS_OR_EQUAL
          • *
          * * @see org.apache.commons.collections4.Predicate#evaluate(java.lang.Object) * @see java.util.Comparator#compare(java.lang.Object first, java.lang.Object second) * * @param target the target object to compare to * @return {@code true} if the comparison succeeds according to the selected criterion * @throws IllegalStateException if the criterion is invalid (really not possible) */ public boolean evaluate(final T target) { boolean result = false; final int comparison = comparator.compare(object, target); switch (criterion) { case EQUAL: result = comparison == 0; break; case GREATER: result = comparison > 0; break; case LESS: result = comparison < 0; break; case GREATER_OR_EQUAL: result = comparison >= 0; break; case LESS_OR_EQUAL: result = comparison <= 0; break; default: throw new IllegalStateException("The current criterion '" + criterion + "' is invalid."); } return result; } } ././@LongLink100644 0 0 155 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NullIsTruePredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NullIsTruePredic100664 5650 12243235517 31730 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns true if the input is null. * * @since 3.0 * @version $Id: NullIsTruePredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class NullIsTruePredicate implements 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 the type that the predicate queries * @param predicate the predicate to decorate, not null * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate nullIsTruePredicate(final Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new NullIsTruePredicate(predicate); } /** * Constructor that performs no validation. * Use nullIsTruePredicate if you want that. * * @param predicate the predicate to call after the null check */ public NullIsTruePredicate(final 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(final T object) { if (object == null) { return true; } return iPredicate.evaluate(object); } /** * Gets the predicate being decorated. * * @return the predicate as the only element in an array * @since 3.1 */ @SuppressWarnings("unchecked") public Predicate[] getPredicates() { return new Predicate[] { iPredicate }; } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/PredicateTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/PredicateTransfo100664 5416 12243235517 31770 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.Transformer; /** * Transformer implementation that calls a Predicate using the input object * and then returns the result. * * @since 3.0 * @version $Id: PredicateTransformer.java 1477798 2013-04-30 19:49:02Z tn $ */ 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 the input type * @param predicate the predicate to call, not null * @return the predicate transformer * @throws IllegalArgumentException if the predicate is null */ public static Transformer predicateTransformer(final Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new PredicateTransformer(predicate); } /** * Constructor that performs no validation. * Use predicateTransformer if you want that. * * @param predicate the predicate to call, not null */ public PredicateTransformer(final Predicate predicate) { super(); iPredicate = predicate; } /** * Transforms the input to result by calling a predicate. * * @param input the input object to transform * @return the transformed result */ public Boolean transform(final T input) { return Boolean.valueOf(iPredicate.evaluate(input)); } /** * Gets the predicate. * * @return the predicate * @since 3.1 */ public Predicate getPredicate() { return iPredicate; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ForClosure.java100664 6154 12243235517 31536 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Closure; /** * Closure implementation that calls another closure n times, like a for loop. * * @since 3.0 * @version $Id: ForClosure.java 1477798 2013-04-30 19:49:02Z tn $ */ 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 the type that the closure acts on * @param count the number of times to execute the closure * @param closure the closure to execute, not null * @return the for closure */ @SuppressWarnings("unchecked") public static Closure forClosure(final int count, final Closure closure) { if (count <= 0 || closure == null) { return NOPClosure.nopClosure(); } if (count == 1) { return (Closure) closure; } return new ForClosure(count, closure); } /** * Constructor that performs no validation. * Use forClosure if you want that. * * @param count the number of times to execute the closure * @param closure the closure to execute, not null */ public ForClosure(final int count, final Closure closure) { super(); iCount = count; iClosure = closure; } /** * Executes the closure count times. * * @param input the input object */ public void execute(final E input) { for (int i = 0; i < iCount; i++) { iClosure.execute(input); } } /** * Gets the closure. * * @return the closure * @since 3.1 */ public Closure getClosure() { return iClosure; } /** * Gets the count. * * @return the count * @since 3.1 */ public int getCount() { return iCount; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ExceptionPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ExceptionPredica100664 4465 12243235517 31764 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.FunctorException; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that always throws an exception. * * @since 3.0 * @version $Id: ExceptionPredicate.java 1543950 2013-11-20 21:13:35Z tn $ */ public final class ExceptionPredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7179106032121985545L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") // the static instance works for all types public static final Predicate INSTANCE = new ExceptionPredicate(); /** * Factory returning the singleton instance. * * @param the object type * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") // the static instance works for all types public static Predicate exceptionPredicate() { return (Predicate) 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(final T object) { throw new FunctorException("ExceptionPredicate invoked"); } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/InvokerTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/InvokerTransform100664 13104 12243235517 32055 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.commons.collections4.FunctorException; import org.apache.commons.collections4.Transformer; /** * Transformer implementation that creates a new object instance by reflection. * * @since 3.0 * @version $Id: InvokerTransformer.java 1543247 2013-11-19 00:36:51Z ggregory $ */ 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 the input type * @param the output type * @param methodName the method name to call * @return an invoker transformer * @since 3.1 */ public static Transformer invokerTransformer(final 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 the input type * @param the output type * @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 invokerTransformer(final String methodName, final Class[] paramTypes, final 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); } return new InvokerTransformer(methodName, paramTypes, args); } /** * Constructor for no arg instance. * * @param methodName the method to call */ private InvokerTransformer(final String methodName) { super(); iMethodName = methodName; iParamTypes = null; iArgs = null; } /** * Constructor that performs no validation. * Use invokerTransformer if you want that. *

          * Note: from 4.0, the input parameters will be cloned * * @param methodName the method to call * @param paramTypes the constructor parameter types * @param args the constructor arguments */ public InvokerTransformer(final String methodName, final Class[] paramTypes, final Object[] args) { super(); iMethodName = methodName; iParamTypes = paramTypes != null ? paramTypes.clone() : null; iArgs = args != null ? args.clone() : null; } /** * 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 */ @SuppressWarnings("unchecked") public O transform(final Object input) { if (input == null) { return null; } try { final Class cls = input.getClass(); final Method method = cls.getMethod(iMethodName, iParamTypes); return (O) method.invoke(input, iArgs); } catch (final NoSuchMethodException ex) { throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' does not exist"); } catch (final IllegalAccessException ex) { throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' cannot be accessed"); } catch (final InvocationTargetException ex) { throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' threw an exception", ex); } } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/IfClosure.java100664 12246 12243235517 31365 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.Predicate; /** * Closure implementation acts as an if statement calling one or other closure * based on a predicate. * * @since 3.0 * @version $Id: IfClosure.java 1543950 2013-11-20 21:13:35Z tn $ */ 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 the type that the closure acts on * @param predicate predicate to switch on * @param trueClosure closure used if true * @return the if closure * @throws IllegalArgumentException if either argument is null * @since 3.2 */ public static Closure ifClosure(final Predicate predicate, final Closure trueClosure) { return IfClosure.ifClosure(predicate, trueClosure, NOPClosure.nopClosure()); } /** * Factory method that performs validation. * * @param the type that the closure acts on * @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 ifClosure(final Predicate predicate, final Closure trueClosure, final 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 ifClosure 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 3.2 */ public IfClosure(final Predicate predicate, final Closure trueClosure) { this(predicate, trueClosure, NOPClosure.nopClosure()); } /** * Constructor that performs no validation. * Use ifClosure 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(final Predicate predicate, final Closure trueClosure, final Closure falseClosure) { super(); iPredicate = predicate; iTrueClosure = trueClosure; iFalseClosure = falseClosure; } /** * Executes the true or false closure according to the result of the predicate. * * @param input the input object */ public void execute(final E input) { if (iPredicate.evaluate(input)) { iTrueClosure.execute(input); } else { iFalseClosure.execute(input); } } /** * Gets the predicate. * * @return the predicate * @since 3.1 */ public Predicate getPredicate() { return iPredicate; } /** * Gets the closure called when true. * * @return the closure * @since 3.1 */ public Closure getTrueClosure() { return iTrueClosure; } /** * Gets the closure called when false. * * @return the closure * @since 3.1 */ public Closure getFalseClosure() { return iFalseClosure; } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/CloneTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/CloneTransformer100664 4646 12243235517 32022 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Transformer; /** * Transformer implementation that returns a clone of the input object. *

          * Clone is performed using PrototypeFactory.prototypeFactory(input).create(). * * @since 3.0 * @version $Id: CloneTransformer.java 1543950 2013-11-20 21:13:35Z tn $ */ public class CloneTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = -8188742709499652567L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") // the singleton instance works for all types public static final Transformer INSTANCE = new CloneTransformer(); /** * Factory returning the singleton instance. * * @param the type of the objects to be cloned * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") // the singleton instance works for all types public static Transformer cloneTransformer() { return (Transformer) INSTANCE; } /** * Constructor. */ private CloneTransformer() { super(); } /** * Transforms the input to result by cloning it. * * @param input the input object to transform * @return the transformed result */ public T transform(final T input) { if (input == null) { return null; } return PrototypeFactory.prototypeFactory(input).create(); } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/OnePredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/OnePredicate.jav100664 7551 12243235517 31656 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.util.Collection; import org.apache.commons.collections4.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 3.0 * @version $Id: OnePredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class OnePredicate extends AbstractQuantifierPredicate { /** Serial version UID */ private static final long serialVersionUID = -8125389089924745785L; /** * 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 the type that the predicate queries * @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 */ @SuppressWarnings("unchecked") public static Predicate onePredicate(final Predicate... predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { return FalsePredicate.falsePredicate(); } if (predicates.length == 1) { return (Predicate) predicates[0]; } return new OnePredicate(FunctorUtils.copy(predicates)); } /** * Factory to create the predicate. * * @param the type that the predicate queries * @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 onePredicate(final Collection> predicates) { final Predicate[] preds = FunctorUtils.validate(predicates); return new OnePredicate(preds); } /** * Constructor that performs no validation. * Use onePredicate if you want that. * * @param predicates the predicates to check, not cloned, not null */ public OnePredicate(final Predicate... predicates) { super(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(final T object) { boolean match = false; for (final Predicate iPredicate : iPredicates) { if (iPredicate.evaluate(object)) { if (match) { return false; } match = true; } } return match; } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/StringValueTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/StringValueTrans100664 4354 12243235517 32006 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Transformer; /** * Transformer implementation that returns the result of calling * String.valueOf on the input object. * * @since 3.0 * @version $Id: StringValueTransformer.java 1543964 2013-11-20 21:53:39Z tn $ */ public final class StringValueTransformer implements Transformer, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7511110693171758606L; /** Singleton predicate instance */ private static final Transformer INSTANCE = new StringValueTransformer(); /** * Factory returning the singleton instance. * * @param the input type * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") public static Transformer stringValueTransformer() { return (Transformer) 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 String transform(final T input) { return String.valueOf(input); } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/FactoryTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/FactoryTransform100664 5362 12243235517 32036 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.Transformer; /** * Transformer implementation that calls a Factory and returns the result. * * @since 3.0 * @version $Id: FactoryTransformer.java 1477798 2013-04-30 19:49:02Z tn $ */ 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 the input type * @param the output type * @param factory the factory to call, not null * @return the factory transformer * @throws IllegalArgumentException if the factory is null */ public static Transformer factoryTransformer(final Factory factory) { if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } return new FactoryTransformer(factory); } /** * Constructor that performs no validation. * Use factoryTransformer if you want that. * * @param factory the factory to call, not null */ public FactoryTransformer(final 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 O transform(final I input) { return iFactory.create(); } /** * Gets the factory. * * @return the factory * @since 3.1 */ public Factory getFactory() { return iFactory; } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/WhileClosure.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/WhileClosure.jav100664 7743 12243235517 31724 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.Predicate; /** * Closure implementation that executes a closure repeatedly until a condition is met, * like a do-while or while loop. * * @since 3.0 * @version $Id: WhileClosure.java 1477798 2013-04-30 19:49:02Z tn $ */ 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 the type that the closure acts on * @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 whileClosure(final Predicate predicate, final Closure closure, final 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 whileClosure 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(final Predicate predicate, final Closure closure, final 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(final E input) { if (iDoLoop) { iClosure.execute(input); } while (iPredicate.evaluate(input)) { iClosure.execute(input); } } /** * Gets the predicate in use. * * @return the predicate * @since 3.1 */ public Predicate getPredicate() { return iPredicate; } /** * Gets the closure. * * @return the closure * @since 3.1 */ public Closure getClosure() { return iClosure; } /** * Is the loop a do-while loop. * * @return true is do-while, false if while * @since 3.1 */ public boolean isDoLoop() { return iDoLoop; } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ExceptionClosure.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ExceptionClosure100664 4371 12243235517 32025 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.FunctorException; /** * Closure implementation that always throws an exception. * * @since 3.0 * @version $Id: ExceptionClosure.java 1543950 2013-11-20 21:13:35Z tn $ */ public final class ExceptionClosure implements Closure, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7179106032121985545L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") // the static instance works for all types public static final Closure INSTANCE = new ExceptionClosure(); /** * Factory returning the singleton instance. * * @param the type that the closure acts on * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") // the static instance works for all types public static Closure exceptionClosure() { return (Closure) INSTANCE; } /** * Restricted constructor. */ private ExceptionClosure() { super(); } /** * Always throw an exception. * * @param input the input object * @throws FunctorException always */ public void execute(final E input) { throw new FunctorException("ExceptionClosure invoked"); } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/AllPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/AllPredicate.jav100664 10245 12243235517 31657 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import static org.apache.commons.collections4.functors.FunctorUtils.coerce; import static org.apache.commons.collections4.functors.FunctorUtils.validate; import static org.apache.commons.collections4.functors.TruePredicate.truePredicate; import java.util.Collection; import org.apache.commons.collections4.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 3.0 * @version $Id: AllPredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class AllPredicate extends AbstractQuantifierPredicate { /** Serial version UID */ private static final long serialVersionUID = -3094696765038308799L; /** * 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 the type that the predicate queries * @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 allPredicate(final Predicate... predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { return truePredicate(); } if (predicates.length == 1) { return coerce(predicates[0]); } return new AllPredicate(FunctorUtils.copy(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 the type that the predicate queries * @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 allPredicate(final Collection> predicates) { final Predicate[] preds = validate(predicates); if (preds.length == 0) { return truePredicate(); } if (preds.length == 1) { return preds[0]; } return new AllPredicate(preds); } /** * Constructor that performs no validation. * Use allPredicate if you want that. * * @param predicates the predicates to check, not cloned, not null */ public AllPredicate(final Predicate... predicates) { super(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(final T object) { for (final Predicate iPredicate : iPredicates) { if (!iPredicate.evaluate(object)) { return false; } } return true; } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/InstantiateTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/InstantiateTrans100664 11753 12243235517 32047 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.collections4.FunctorException; import org.apache.commons.collections4.Transformer; /** * Transformer implementation that creates a new object instance by reflection. * * @since 3.0 * @version $Id: InstantiateTransformer.java 1543950 2013-11-20 21:13:35Z tn $ */ public class InstantiateTransformer implements Transformer, T>, Serializable { /** The serial version */ private static final long serialVersionUID = 3786388740793356347L; /** Singleton instance that uses the no arg constructor */ @SuppressWarnings("rawtypes") private static final Transformer NO_ARG_INSTANCE = new InstantiateTransformer(); /** The constructor parameter types */ private final Class[] iParamTypes; /** The constructor arguments */ private final Object[] iArgs; /** * Get a typed no-arg instance. * * @param the type of the objects to be created * @return Transformer, T> */ @SuppressWarnings("unchecked") public static Transformer, T> instantiateTransformer() { return (Transformer, T>) NO_ARG_INSTANCE; } /** * Transformer method that performs validation. * * @param the type of the objects to be created * @param paramTypes the constructor parameter types * @param args the constructor arguments * @return an instantiate transformer */ public static Transformer, T> instantiateTransformer(final Class[] paramTypes, final 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 new InstantiateTransformer(); } return new InstantiateTransformer(paramTypes, args); } /** * Constructor for no arg instance. */ private InstantiateTransformer() { super(); iParamTypes = null; iArgs = null; } /** * Constructor that performs no validation. * Use instantiateTransformer if you want that. *

          * Note: from 4.0, the input parameters will be cloned * * @param paramTypes the constructor parameter types * @param args the constructor arguments */ public InstantiateTransformer(final Class[] paramTypes, final Object[] args) { super(); iParamTypes = paramTypes != null ? paramTypes.clone() : null; iArgs = args != null ? args.clone() : null; } /** * Transforms the input Class object to a result by instantiation. * * @param input the input object to transform * @return the transformed result */ public T transform(final Class input) { try { if (input == null) { throw new FunctorException( "InstantiateTransformer: Input object was not an instanceof Class, it was a null object"); } final Constructor con = input.getConstructor(iParamTypes); return con.newInstance(iArgs); } catch (final NoSuchMethodException ex) { throw new FunctorException("InstantiateTransformer: The constructor must exist and be public "); } catch (final InstantiationException ex) { throw new FunctorException("InstantiateTransformer: InstantiationException", ex); } catch (final IllegalAccessException ex) { throw new FunctorException("InstantiateTransformer: Constructor must be public", ex); } catch (final InvocationTargetException ex) { throw new FunctorException("InstantiateTransformer: Constructor threw an exception", ex); } } } ././@LongLink100644 0 0 152 12243235652 10255 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ExceptionFactory.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ExceptionFactory100664 4323 12243235517 32015 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.FunctorException; /** * Factory implementation that always throws an exception. * * @since 3.0 * @version $Id: ExceptionFactory.java 1543950 2013-11-20 21:13:35Z tn $ */ public final class ExceptionFactory implements Factory, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7179106032121985545L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") // the static instance works for all types public static final Factory INSTANCE = new ExceptionFactory(); /** * Factory returning the singleton instance. * * @param the type the factory creates * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") // the static instance works for all types public static Factory exceptionFactory() { return (Factory) INSTANCE; } /** * Restricted constructor. */ private ExceptionFactory() { super(); } /** * Always throws an exception. * * @return never * @throws FunctorException always */ public T create() { throw new FunctorException("ExceptionFactory invoked"); } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/UniquePredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/UniquePredicate.100664 4334 12243235517 31676 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns true the first time an object is * passed into the predicate. * * @since 3.0 * @version $Id: UniquePredicate.java 1476582 2013-04-27 14:13:54Z tn $ */ 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. * * @param the type that the predicate queries * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate uniquePredicate() { return new UniquePredicate(); } /** * Constructor that performs no validation. * Use uniquePredicate 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(final T object) { return iSet.add(object); } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/TransformerClosure.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/TransformerClosu100664 5320 12243235517 32035 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.Transformer; /** * Closure implementation that calls a Transformer using the input object * and ignore the result. * * @since 3.0 * @version $Id: TransformerClosure.java 1477798 2013-04-30 19:49:02Z tn $ */ 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 the type that the closure acts on * @param transformer the transformer to call, null means nop * @return the transformer closure */ public static Closure transformerClosure(final Transformer transformer) { if (transformer == null) { return NOPClosure.nopClosure(); } return new TransformerClosure(transformer); } /** * Constructor that performs no validation. * Use transformerClosure if you want that. * * @param transformer the transformer to call, not null */ public TransformerClosure(final Transformer transformer) { super(); iTransformer = transformer; } /** * Executes the closure by calling the decorated transformer. * * @param input the input object */ public void execute(final E input) { iTransformer.transform(input); } /** * Gets the transformer. * * @return the transformer * @since 3.1 */ public Transformer getTransformer() { return iTransformer; } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/IdentityPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/IdentityPredicat100664 5106 12243235517 31774 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns true if the input is the same object * as the one stored in this predicate. * * @since 3.0 * @version $Id: IdentityPredicate.java 1476582 2013-04-27 14:13:54Z tn $ */ public final class IdentityPredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = -89901658494523293L; /** The value to compare to */ private final T iValue; /** * Factory to create the identity predicate. * * @param the type that the predicate queries * @param object the object to compare to * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate identityPredicate(final T object) { if (object == null) { return NullPredicate.nullPredicate(); } return new IdentityPredicate(object); } /** * Constructor that performs no validation. * Use identityPredicate if you want that. * * @param object the object to compare to */ public IdentityPredicate(final T object) { super(); iValue = object; } /** * Evaluates the predicate returning true if the input object is identical to * the stored object. * * @param object the input object * @return true if input is the same object as the stored value */ public boolean evaluate(final T object) { return iValue == object; } /** * Gets the value. * * @return the value * @since 3.1 */ public T getValue() { return iValue; } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NonePredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NonePredicate.ja100664 7330 12243235517 31641 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.util.Collection; import org.apache.commons.collections4.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 3.0 * @version $Id: NonePredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class NonePredicate extends AbstractQuantifierPredicate { /** Serial version UID */ private static final long serialVersionUID = 2007613066565892961L; /** * Factory to create the predicate. *

          * If the array is size zero, the predicate always returns true. * * @param the type that the predicate queries * @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 nonePredicate(final Predicate... predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { return TruePredicate.truePredicate(); } return new NonePredicate(FunctorUtils.copy(predicates)); } /** * Factory to create the predicate. *

          * If the collection is size zero, the predicate always returns true. * * @param the type that the predicate queries * @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 nonePredicate(final Collection> predicates) { final Predicate[] preds = FunctorUtils.validate(predicates); if (preds.length == 0) { return TruePredicate.truePredicate(); } return new NonePredicate(preds); } /** * Constructor that performs no validation. * Use nonePredicate if you want that. * * @param predicates the predicates to check, not cloned, not null */ public NonePredicate(final Predicate... predicates) { super(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(final T object) { for (final Predicate iPredicate : iPredicates) { if (iPredicate.evaluate(object)) { return false; } } return true; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ChainedTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ChainedTransform100664 11554 12243235517 32002 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import java.util.Collection; import org.apache.commons.collections4.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 3.0 * @version $Id: ChainedTransformer.java 1479337 2013-05-05 15:20:59Z tn $ */ 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 the object type * @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 chainedTransformer(final Transformer... transformers) { FunctorUtils.validate(transformers); if (transformers.length == 0) { return NOPTransformer.nopTransformer(); } 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 the object type * @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 */ @SuppressWarnings("unchecked") public static Transformer chainedTransformer(final Collection> transformers) { if (transformers == null) { throw new IllegalArgumentException("Transformer collection must not be null"); } if (transformers.size() == 0) { return NOPTransformer.nopTransformer(); } // convert to array like this to guarantee iterator() ordering final Transformer[] cmds = transformers.toArray(new Transformer[transformers.size()]); FunctorUtils.validate(cmds); return new ChainedTransformer(false, cmds); } /** * Hidden constructor for the use by the static factory methods. * * @param clone if {@code true} the input argument will be cloned * @param transformers the transformers to chain, no nulls */ private ChainedTransformer(final boolean clone, final Transformer[] transformers) { super(); iTransformers = clone ? FunctorUtils.copy(transformers) : transformers; } /** * Constructor that performs no validation. * Use chainedTransformer if you want that. * * @param transformers the transformers to chain, copied, no nulls */ public ChainedTransformer(final Transformer... transformers) { this(true, 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 T transform(T object) { for (final Transformer iTransformer : iTransformers) { object = iTransformer.transform(object); } return object; } /** * Gets the transformers. * * @return a copy of the transformers * @since 3.1 */ public Transformer[] getTransformers() { return FunctorUtils.copy(iTransformers); } } ././@LongLink100644 0 0 156 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/TransformerPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/TransformerPredi100664 6233 12243235517 32017 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.FunctorException; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.Transformer; /** * Predicate implementation that returns the result of a transformer. * * @since 3.0 * @version $Id: TransformerPredicate.java 1476582 2013-04-27 14:13:54Z tn $ */ 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 the type that the predicate queries * @param transformer the transformer to decorate * @return the predicate * @throws IllegalArgumentException if the transformer is null */ public static Predicate transformerPredicate(final 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 transformerPredicate if you want that. * * @param transformer the transformer to decorate */ public TransformerPredicate(final 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(final T object) { final Boolean result = iTransformer.transform(object); if (result == null) { throw new FunctorException( "Transformer must return an instanceof Boolean, it was a null object"); } return result.booleanValue(); } /** * Gets the transformer. * * @return the transformer * @since 3.1 */ public Transformer getTransformer() { return iTransformer; } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/TruePredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/TruePredicate.ja100664 4104 12243235517 31655 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that always returns true. * * @since 3.0 * @version $Id: TruePredicate.java 1543950 2013-11-20 21:13:35Z tn $ */ public final class TruePredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = 3374767158756189740L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") public static final Predicate INSTANCE = new TruePredicate(); /** * Factory returning the singleton instance. * * @param the type that the predicate queries * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") public static Predicate truePredicate() { return (Predicate) INSTANCE; } /** * Restricted constructor. */ private TruePredicate() { super(); } /** * Evaluates the predicate returning true always. * * @param object the input object * @return true always */ public boolean evaluate(final T object) { return true; } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/package-info.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/package-info.jav100664 2442 12243235517 31632 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * This package contains implementations of the * {@link org.apache.commons.collections4.Closure Closure}, * {@link org.apache.commons.collections4.Predicate Predicate}, * {@link org.apache.commons.collections4.Transformer Transformer} and * {@link org.apache.commons.collections4.Factory Factory} interfaces. * These provide simple callbacks for processing with collections. * * @version $Id: package-info.java 1477798 2013-04-30 19:49:02Z tn $ */ package org.apache.commons.collections4.functors; ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/InstantiateFactory.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/InstantiateFacto100664 12053 12243235517 32006 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.FunctorException; /** * Factory implementation that creates a new object instance by reflection. * * @since 3.0 * @version $Id: InstantiateFactory.java 1477798 2013-04-30 19:49:02Z tn $ */ 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 the type the factory creates * @param classToInstantiate the class to instantiate, not null * @param paramTypes the constructor parameter types, cloned * @param args the constructor arguments, cloned * @return a new instantiate factory */ public static Factory instantiateFactory(final Class classToInstantiate, final Class[] paramTypes, final 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); } return new InstantiateFactory(classToInstantiate, paramTypes, args); } /** * Constructor that performs no validation. * Use instantiateFactory if you want that. * * @param classToInstantiate the class to instantiate */ public InstantiateFactory(final Class classToInstantiate) { super(); iClassToInstantiate = classToInstantiate; iParamTypes = null; iArgs = null; findConstructor(); } /** * Constructor that performs no validation. * Use instantiateFactory if you want that. * * @param classToInstantiate the class to instantiate * @param paramTypes the constructor parameter types, cloned * @param args the constructor arguments, cloned */ public InstantiateFactory(final Class classToInstantiate, final Class[] paramTypes, final Object[] args) { super(); iClassToInstantiate = classToInstantiate; iParamTypes = paramTypes.clone(); iArgs = args.clone(); findConstructor(); } /** * Find the Constructor for the class specified. */ private void findConstructor() { try { iConstructor = iClassToInstantiate.getConstructor(iParamTypes); } catch (final NoSuchMethodException ex) { throw new IllegalArgumentException("InstantiateFactory: The constructor must exist and be public "); } } /** * Creates an object using the stored constructor. * * @return the new object */ public T create() { // needed for post-serialization if (iConstructor == null) { findConstructor(); } try { return iConstructor.newInstance(iArgs); } catch (final InstantiationException ex) { throw new FunctorException("InstantiateFactory: InstantiationException", ex); } catch (final IllegalAccessException ex) { throw new FunctorException("InstantiateFactory: Constructor must be public", ex); } catch (final InvocationTargetException ex) { throw new FunctorException("InstantiateFactory: Constructor threw an exception", ex); } } } ././@LongLink100644 0 0 145 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/OrPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/OrPredicate.java100664 6364 12243235517 31657 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns true if either of the predicates return true. * * @since 3.0 * @version $Id: OrPredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class OrPredicate implements 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 the type that the predicate queries * @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 orPredicate(final Predicate predicate1, final 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 orPredicate if you want that. * * @param predicate1 the first predicate to check, not null * @param predicate2 the second predicate to check, not null */ public OrPredicate(final Predicate predicate1, final 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(final T object) { return iPredicate1.evaluate(object) || iPredicate2.evaluate(object); } /** * Gets the two predicates being decorated as an array. * * @return the predicates * @since 3.1 */ @SuppressWarnings("unchecked") public Predicate[] getPredicates() { return new Predicate[] {iPredicate1, iPredicate2}; } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ChainedClosure.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ChainedClosure.j100664 10607 12243235517 31671 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import java.util.Collection; import org.apache.commons.collections4.Closure; /** * Closure implementation that chains the specified closures together. * * @since 3.0 * @version $Id: ChainedClosure.java 1479336 2013-05-05 15:06:50Z tn $ */ 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 the type that the closure acts on * @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 chainedClosure(final Closure... closures) { FunctorUtils.validate(closures); if (closures.length == 0) { return NOPClosure.nopClosure(); } 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 the type that the closure acts on * @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 */ @SuppressWarnings("unchecked") public static Closure chainedClosure(final Collection> closures) { if (closures == null) { throw new IllegalArgumentException("Closure collection must not be null"); } if (closures.size() == 0) { return NOPClosure.nopClosure(); } // convert to array like this to guarantee iterator() ordering final Closure[] cmds = new Closure[closures.size()]; int i = 0; for (final Closure closure : closures) { cmds[i++] = closure; } FunctorUtils.validate(cmds); return new ChainedClosure(false, cmds); } /** * Hidden constructor for the use by the static factory methods. * * @param clone if {@code true} the input argument will be cloned * @param closures the closures to chain, no nulls */ private ChainedClosure(final boolean clone, final Closure... closures) { super(); iClosures = clone ? FunctorUtils.copy(closures) : closures; } /** * Constructor that performs no validation. * Use chainedClosure if you want that. * * @param closures the closures to chain, copied, no nulls */ public ChainedClosure(final Closure... closures) { this(true, closures); } /** * Execute a list of closures. * * @param input the input object passed to each closure */ public void execute(final E input) { for (final Closure iClosure : iClosures) { iClosure.execute(input); } } /** * Gets the closures. * * @return a copy of the closures * @since 3.1 */ public Closure[] getClosures() { return FunctorUtils.copy(iClosures); } } ././@LongLink100644 0 0 160 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/CatchAndRethrowClosure.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/CatchAndRethrowC100664 5216 12243235517 31654 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.FunctorException; /** * {@link Closure} that catches any checked exception and re-throws it as a * {@link FunctorException} runtime exception. Example usage: * *
           * // Create a catch and re-throw closure via anonymous subclass
           * CatchAndRethrowClosure<String> writer = new ThrowingClosure() {
           *     private java.io.Writer out = // some writer
           *
           *     protected void executeAndThrow(String input) throws IOException {
           *         out.write(input); // throwing of IOException allowed
           *     }
           * };
           *
           * // use catch and re-throw closure
           * java.util.List strList = // some list
           * try {
           *     CollctionUtils.forAllDo(strList, writer);
           * } catch (FunctorException ex) {
           *     Throwable originalError = ex.getCause();
           *     // handle error
           * }
           * 
          * * @since 4.0 * @version $Id: CatchAndRethrowClosure.java 1477798 2013-04-30 19:49:02Z tn $ */ public abstract class CatchAndRethrowClosure implements Closure { /** * Execute this closure on the specified input object. * * @param input the input to execute on * @throws FunctorException (runtime) if the closure execution resulted in a * checked exception. */ public void execute(final E input) { try { executeAndThrow(input); } catch (final RuntimeException ex) { throw ex; } catch (final Throwable t) { throw new FunctorException(t); } } /** * Execute this closure on the specified input object. * * @param input the input to execute on * @throws Throwable if the closure execution resulted in a checked * exception. */ protected abstract void executeAndThrow(E input) throws Throwable; } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NotPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NotPredicate.jav100664 5403 12243235517 31667 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns the opposite of the decorated predicate. * * @since 3.0 * @version $Id: NotPredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class NotPredicate implements 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 the type that the predicate queries * @param predicate the predicate to decorate, not null * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate notPredicate(final Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new NotPredicate(predicate); } /** * Constructor that performs no validation. * Use notPredicate if you want that. * * @param predicate the predicate to call after the null check */ public NotPredicate(final 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(final T object) { return !iPredicate.evaluate(object); } /** * Gets the predicate being decorated. * * @return the predicate as the only element in an array * @since 3.1 */ @SuppressWarnings("unchecked") public Predicate[] getPredicates() { return new Predicate[] {iPredicate}; } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/MapTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/MapTransformer.j100664 5265 12243235517 31725 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import java.util.Map; import org.apache.commons.collections4.Transformer; /** * Transformer implementation that returns the value held in a specified map * using the input parameter as a key. * * @since 3.0 * @version $Id: MapTransformer.java 1476582 2013-04-27 14:13:54Z tn $ */ 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 the input type * @param the output type * @param map the map, not cloned * @return the transformer */ public static Transformer mapTransformer(final Map map) { if (map == null) { return ConstantTransformer.nullTransformer(); } return new MapTransformer(map); } /** * Constructor that performs no validation. * Use mapTransformer if you want that. * * @param map the map to use for lookup, not cloned */ private MapTransformer(final Map map) { super(); iMap = map; } /** * Transforms the input to result by looking it up in a Map. * * @param input the input object to transform * @return the transformed result */ public O transform(final I input) { return iMap.get(input); } /** * Gets the map to lookup in. * * @return the map * @since 3.1 */ public Map getMap() { return iMap; } } ././@LongLink100644 0 0 153 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/SwitchTransformer.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/SwitchTransforme100664 20464 12243235517 32055 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import java.util.Map; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.Transformer; /** * Transformer implementation calls the transformer whose predicate returns true, * like a switch statement. * * @since 3.0 * @version $Id: SwitchTransformer.java 1479337 2013-05-05 15:20:59Z tn $ */ 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 the input type * @param the output type * @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 */ @SuppressWarnings("unchecked") public static Transformer switchTransformer(final Predicate[] predicates, final Transformer[] transformers, final 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 (Transformer) (defaultTransformer == null ? ConstantTransformer.nullTransformer() : defaultTransformer); } 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 the input type * @param the output type * @param map 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 */ @SuppressWarnings("unchecked") public static Transformer switchTransformer( final Map, ? extends Transformer> map) { if (map == null) { throw new IllegalArgumentException("The predicate and transformer map must not be null"); } if (map.size() == 0) { return ConstantTransformer.nullTransformer(); } // convert to array like this to guarantee iterator() ordering final Transformer defaultTransformer = map.remove(null); final int size = map.size(); if (size == 0) { return (Transformer) (defaultTransformer == null ? ConstantTransformer.nullTransformer() : defaultTransformer); } final Transformer[] transformers = new Transformer[size]; final Predicate[] preds = new Predicate[size]; int i = 0; for (final Map.Entry, ? extends Transformer> entry : map.entrySet()) { preds[i] = entry.getKey(); transformers[i] = entry.getValue(); i++; } return new SwitchTransformer(false, preds, transformers, defaultTransformer); } /** * Hidden constructor for the use by the static factory methods. * * @param clone if {@code true} the input arguments will be cloned * @param predicates array of predicates, no nulls * @param transformers matching array of transformers, no nulls * @param defaultTransformer the transformer to use if no match, null means return null */ @SuppressWarnings("unchecked") private SwitchTransformer(final boolean clone, final Predicate[] predicates, final Transformer[] transformers, final Transformer defaultTransformer) { super(); iPredicates = clone ? FunctorUtils.copy(predicates) : predicates; iTransformers = clone ? FunctorUtils.copy(transformers) : transformers; iDefault = (Transformer) (defaultTransformer == null ? ConstantTransformer.nullTransformer() : defaultTransformer); } /** * Constructor that performs no validation. * Use switchTransformer if you want that. * * @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 */ public SwitchTransformer(final Predicate[] predicates, final Transformer[] transformers, final Transformer defaultTransformer) { this(true, predicates, transformers, defaultTransformer); } /** * Transforms the input to result by calling the transformer whose matching * predicate returns true. * * @param input the input object to transform * @return the transformed result */ public O transform(final I 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. * * @return a copy of the predicates * @since 3.1 */ public Predicate[] getPredicates() { return FunctorUtils.copy(iPredicates); } /** * Gets the transformers. * * @return a copy of the transformers * @since 3.1 */ public Transformer[] getTransformers() { return FunctorUtils.copy(iTransformers); } /** * Gets the default transformer. * * @return the default transformer * @since 3.1 */ public Transformer getDefaultTransformer() { return iDefault; } } ././@LongLink100644 0 0 147 12243235652 10261 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/SwitchClosure.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/SwitchClosure.ja100664 16435 12243235517 31745 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import java.util.Map; import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.Predicate; /** * Closure implementation calls the closure whose predicate returns true, * like a switch statement. * * @since 3.0 * @version $Id: SwitchClosure.java 1479337 2013-05-05 15:20:59Z tn $ */ 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 the type that the closure acts on * @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 */ @SuppressWarnings("unchecked") public static Closure switchClosure(final Predicate[] predicates, final Closure[] closures, final 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 (Closure) (defaultClosure == null ? NOPClosure.nopClosure(): defaultClosure); } 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 the type that the closure acts on * @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 */ @SuppressWarnings("unchecked") public static Closure switchClosure(final Map, Closure> predicatesAndClosures) { if (predicatesAndClosures == null) { throw new IllegalArgumentException("The predicate and closure map must not be null"); } // convert to array like this to guarantee iterator() ordering final Closure defaultClosure = predicatesAndClosures.remove(null); final int size = predicatesAndClosures.size(); if (size == 0) { return (Closure) (defaultClosure == null ? NOPClosure.nopClosure() : defaultClosure); } final Closure[] closures = new Closure[size]; final Predicate[] preds = new Predicate[size]; int i = 0; for (final Map.Entry, Closure> entry : predicatesAndClosures.entrySet()) { preds[i] = entry.getKey(); closures[i] = entry.getValue(); i++; } return new SwitchClosure(false, preds, closures, defaultClosure); } /** * Hidden constructor for the use by the static factory methods. * * @param clone if {@code true} the input arguments will be cloned * @param predicates array of predicates, no nulls * @param closures matching array of closures, no nulls * @param defaultClosure the closure to use if no match, null means nop */ @SuppressWarnings("unchecked") private SwitchClosure(final boolean clone, final Predicate[] predicates, final Closure[] closures, final Closure defaultClosure) { super(); iPredicates = clone ? FunctorUtils.copy(predicates) : predicates; iClosures = clone ? FunctorUtils.copy(closures) : closures; iDefault = (Closure) (defaultClosure == null ? NOPClosure.nopClosure() : defaultClosure); } /** * Constructor that performs no validation. * Use switchClosure if you want that. * * @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 */ public SwitchClosure(final Predicate[] predicates, final Closure[] closures, final Closure defaultClosure) { this(true, predicates, closures, defaultClosure); } /** * Executes the closure whose matching predicate returns true * * @param input the input object */ public void execute(final E 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. * * @return a copy of the predicates * @since 3.1 */ public Predicate[] getPredicates() { return FunctorUtils.copy(iPredicates); } /** * Gets the closures. * * @return a copy of the closures * @since 3.1 */ public Closure[] getClosures() { return FunctorUtils.copy(iClosures); } /** * Gets the default closure. * * @return the default closure * @since 3.1 */ public Closure getDefaultClosure() { return iDefault; } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/FunctorUtils.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/FunctorUtils.jav100664 16172 12243235517 31774 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.util.Collection; import org.apache.commons.collections4.Closure; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.Transformer; /** * Internal utilities for functors. * * @since 3.0 * @version $Id: FunctorUtils.java 1479343 2013-05-05 15:43:38Z tn $ */ class FunctorUtils { /** * Restricted constructor. */ private FunctorUtils() { super(); } /** * Clone the predicates to ensure that the internal reference can't be messed with. * Due to the {@link Predicate#evaluate(T)} method, Predicate is * able to be coerced to Predicate without casting issues. * * @param predicates the predicates to copy * @return the cloned predicates */ @SuppressWarnings("unchecked") static Predicate[] copy(final Predicate... predicates) { if (predicates == null) { return null; } return (Predicate[]) predicates.clone(); } /** * A very simple method that coerces Predicate to Predicate. * Due to the {@link Predicate#evaluate(T)} method, Predicate is * able to be coerced to Predicate without casting issues. *

          This method exists * simply as centralised documentation and atomic unchecked warning * suppression. * * @param the type of object the returned predicate should "accept" * @param predicate the predicate to coerce. * @return the coerced predicate. */ @SuppressWarnings("unchecked") static Predicate coerce(final Predicate predicate){ return (Predicate) predicate; } /** * Validate the predicates to ensure that all is well. * * @param predicates the predicates to validate */ static void validate(final 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(final Collection> predicates) { if (predicates == null) { throw new IllegalArgumentException("The predicate collection must not be null"); } // convert to array like this to guarantee iterator() ordering @SuppressWarnings("unchecked") // OK final Predicate[] preds = new Predicate[predicates.size()]; int i = 0; for (final Predicate predicate : predicates) { preds[i] = predicate; 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 */ @SuppressWarnings("unchecked") static Closure[] copy(final 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(final 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"); } } } /** * A very simple method that coerces Closure to Closure. *

          This method exists * simply as centralised documentation and atomic unchecked warning * suppression. * * @param the type of object the returned closure should "accept" * @param closure the closure to coerce. * @return the coerced closure. */ @SuppressWarnings("unchecked") static Closure coerce(final Closure closure){ return (Closure) closure; } /** * Copy method * * @param transformers the transformers to copy * @return a clone of the transformers */ @SuppressWarnings("unchecked") static Transformer[] copy(final Transformer... transformers) { if (transformers == null) { return null; } return (Transformer[]) transformers.clone(); } /** * Validate method * * @param transformers the transformers to validate */ static void validate(final 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"); } } } /** * A very simple method that coerces Transformer to Transformer. *

          This method exists * simply as centralised documentation and atomic unchecked warning * suppression. * * @param the type of object the returned transformer should "accept" * @param transformer the transformer to coerce. * @return the coerced transformer. */ @SuppressWarnings("unchecked") static Transformer coerce(final Transformer transformer) { return (Transformer) transformer; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NOPClosure.java100664 3722 12243235517 31442 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Closure; /** * Closure implementation that does nothing. * * @since 3.0 * @version $Id: NOPClosure.java 1543950 2013-11-20 21:13:35Z tn $ */ public final class NOPClosure implements Closure, Serializable { /** Serial version UID */ private static final long serialVersionUID = 3518477308466486130L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") public static final Closure INSTANCE = new NOPClosure(); /** * Factory returning the singleton instance. * * @param the type that the closure acts on * @return the singleton instance * @since 3.1 */ @SuppressWarnings("unchecked") public static Closure nopClosure() { return (Closure) INSTANCE; } /** * Constructor. */ private NOPClosure() { super(); } /** * Do nothing. * * @param input the input object */ public void execute(final E input) { // do nothing } private Object readResolve() { return INSTANCE; } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/EqualPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/EqualPredicate.j100664 7666 12243235517 31664 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import static org.apache.commons.collections4.functors.NullPredicate.nullPredicate; import java.io.Serializable; import org.apache.commons.collections4.Equator; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns true if the input is the same object * as the one stored in this predicate by equals. * * @since 3.0 * @version $Id: EqualPredicate.java 1540567 2013-11-10 22:19:29Z tn $ */ public final class EqualPredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = 5633766978029907089L; /** The value to compare to */ private final T iValue; /** The equator to use for comparison */ private final Equator equator; /** * Factory to create the predicate. * * @param the type that the predicate queries * @param object the object to compare to * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate equalPredicate(final T object) { if (object == null) { return nullPredicate(); } return new EqualPredicate(object); } /** * Factory to create the identity predicate. * * @param the type that the predicate queries * @param object the object to compare to * @param equator the equator to use for comparison * @return the predicate * @throws IllegalArgumentException if the predicate is null * @since 4.0 */ public static Predicate equalPredicate(final T object, final Equator equator) { if (object == null) { return nullPredicate(); } return new EqualPredicate(object, equator); } /** * Constructor that performs no validation. * Use equalPredicate if you want that. * * @param object the object to compare to */ public EqualPredicate(final T object) { // do not use the DefaultEquator to keep backwards compatibility // the DefaultEquator returns also true if the two object references are equal this(object, null); } /** * Constructor that performs no validation. * Use equalPredicate if you want that. * * @param object the object to compare to * @param equator the equator to use for comparison * @since 4.0 */ public EqualPredicate(final T object, final Equator equator) { super(); iValue = object; this.equator = equator; } /** * 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(final T object) { if (equator != null) { return equator.equate(iValue, object); } else { return iValue.equals(object); } } /** * Gets the value. * * @return the value * @since 3.1 */ public Object getValue() { return iValue; } } ././@LongLink100644 0 0 154 12243235652 10257 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/PredicateDecorator.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/PredicateDecorat100664 2736 12243235517 31737 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import org.apache.commons.collections4.Predicate; /** * Defines a predicate that decorates one or more other predicates. *

          * This interface enables tools to access the decorated predicates. * * @since 3.1 * @version $Id: PredicateDecorator.java 1477798 2013-04-30 19:49:02Z tn $ */ 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(); } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/AnyPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/AnyPredicate.jav100664 10117 12243235517 31674 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.util.Collection; import org.apache.commons.collections4.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 3.0 * @version $Id: AnyPredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class AnyPredicate extends AbstractQuantifierPredicate { /** Serial version UID */ private static final long serialVersionUID = 7429999530934647542L; /** * 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 the type that the predicate queries * @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 */ @SuppressWarnings("unchecked") public static Predicate anyPredicate(final Predicate... predicates) { FunctorUtils.validate(predicates); if (predicates.length == 0) { return FalsePredicate.falsePredicate(); } if (predicates.length == 1) { return (Predicate) 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 the type that the predicate queries * @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 */ @SuppressWarnings("unchecked") public static Predicate anyPredicate(final Collection> predicates) { final Predicate[] preds = FunctorUtils.validate(predicates); if (preds.length == 0) { return FalsePredicate.falsePredicate(); } if (preds.length == 1) { return (Predicate) preds[0]; } return new AnyPredicate(preds); } /** * Constructor that performs no validation. * Use anyPredicate if you want that. * * @param predicates the predicates to check, not cloned, not null */ public AnyPredicate(final Predicate... predicates) { super(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(final T object) { for (final Predicate iPredicate : iPredicates) { if (iPredicate.evaluate(object)) { return true; } } return false; } } ././@LongLink100644 0 0 146 12243235652 10260 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/AndPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/AndPredicate.jav100664 6361 12243235517 31635 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that returns true if both the predicates return true. * * @since 3.0 * @version $Id: AndPredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class AndPredicate implements 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 the type that the predicate queries * @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 andPredicate(final Predicate predicate1, final 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 andPredicate if you want that. * * @param predicate1 the first predicate to check, not null * @param predicate2 the second predicate to check, not null */ public AndPredicate(final Predicate predicate1, final 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(final T object) { return iPredicate1.evaluate(object) && iPredicate2.evaluate(object); } /** * Gets the two predicates being decorated as an array. * * @return the predicates * @since 3.1 */ @SuppressWarnings("unchecked") public Predicate[] getPredicates() { return new Predicate[] {iPredicate1, iPredicate2}; } } ././@LongLink100644 0 0 151 12243235652 10254 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ConstantFactory.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/ConstantFactory.100664 5546 12243235517 31736 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.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 3.0 * @version $Id: ConstantFactory.java 1543950 2013-11-20 21:13:35Z tn $ */ public class ConstantFactory implements Factory, Serializable { /** Serial version UID */ private static final long serialVersionUID = -3520677225766901240L; /** Returns null each time */ @SuppressWarnings("rawtypes") // The null factory works for all object types public static final Factory NULL_INSTANCE = new ConstantFactory(null); /** The closures to call in turn */ private final T iConstant; /** * Factory method that performs validation. * * @param the type of the constant * @param constantToReturn the constant object to return each time in the factory * @return the constant factory. */ @SuppressWarnings("unchecked") // The null factory works for all object types public static Factory constantFactory(final T constantToReturn) { if (constantToReturn == null) { return (Factory) NULL_INSTANCE; } return new ConstantFactory(constantToReturn); } /** * Constructor that performs no validation. * Use constantFactory if you want that. * * @param constantToReturn the constant to return each time */ public ConstantFactory(final T constantToReturn) { super(); iConstant = constantToReturn; } /** * Always return constant. * * @return the stored constant value */ public T create() { return iConstant; } /** * Gets the constant. * * @return the constant * @since 3.1 */ public T getConstant() { return iConstant; } } ././@LongLink100644 0 0 162 12243235652 10256 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NullIsExceptionPredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/NullIsExceptionP100664 6132 12243235517 31734 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.FunctorException; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that throws an exception if the input is null. * * @since 3.0 * @version $Id: NullIsExceptionPredicate.java 1543167 2013-11-18 21:21:32Z ggregory $ */ public final class NullIsExceptionPredicate implements 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 the type that the predicate queries * @param predicate the predicate to decorate, not null * @return the predicate * @throws IllegalArgumentException if the predicate is null */ public static Predicate nullIsExceptionPredicate(final Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate must not be null"); } return new NullIsExceptionPredicate(predicate); } /** * Constructor that performs no validation. * Use nullIsExceptionPredicate if you want that. * * @param predicate the predicate to call after the null check */ public NullIsExceptionPredicate(final 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(final T object) { if (object == null) { throw new FunctorException("Input Object must not be null"); } return iPredicate.evaluate(object); } /** * Gets the predicate being decorated. * * @return the predicate as the only element in an array * @since 3.1 */ @SuppressWarnings("unchecked") public Predicate[] getPredicates() { return new Predicate[] { iPredicate }; } } ././@LongLink100644 0 0 150 12243235652 10253 Lustar 0 0 commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/FalsePredicate.javacommons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/functors/FalsePredicate.j100664 4217 12243235517 31634 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4.functors; import java.io.Serializable; import org.apache.commons.collections4.Predicate; /** * Predicate implementation that always returns false. * * @since 3.0 * @version $Id: FalsePredicate.java 1543950 2013-11-20 21:13:35Z tn $ */ public final class FalsePredicate implements Predicate, Serializable { /** Serial version UID */ private static final long serialVersionUID = 7533784454832764388L; /** Singleton predicate instance */ @SuppressWarnings("rawtypes") // the static instance works for all types public static final Predicate INSTANCE = new FalsePredicate(); /** * Get a typed instance. * * @param the type that the predicate queries * @return the singleton instance * @since 4.0 */ @SuppressWarnings("unchecked") // the static instance works for all types public static Predicate falsePredicate() { return (Predicate) INSTANCE; } /** * Restricted constructor. */ private FalsePredicate() { super(); } /** * Evaluates the predicate returning false always. * * @param object the input object * @return false always */ public boolean evaluate(final T object) { return false; } private Object readResolve() { return INSTANCE; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/Closure.java100664 3352 12243235517 27221 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * 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 invocation and for/while loops. * * @param the type that the closure acts on * @since 1.0 * @version $Id: Closure.java 1543261 2013-11-19 00:47:34Z ggregory $ */ 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 */ void execute(T input); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/Predicate.java100664 3715 12243235516 27507 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * 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. * * @param the type that the predicate queries * * @since 1.0 * @version $Id: Predicate.java 1543262 2013-11-19 00:47:45Z ggregory $ */ 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 */ boolean evaluate(T object); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/Unmodifiable.java100664 2724 12243235516 30204 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; /** * 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 {@code java.util Collections} * then the interface won't be there. * * @since 3.0 * @version $Id: Unmodifiable.java 1477779 2013-04-30 18:55:24Z tn $ */ public interface Unmodifiable { // marker interface - no methods to implement } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/QueueUtils.java100664 10632 12243235516 27730 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.LinkedList; import java.util.Queue; import org.apache.commons.collections4.queue.PredicatedQueue; import org.apache.commons.collections4.queue.TransformedQueue; import org.apache.commons.collections4.queue.UnmodifiableQueue; /** * Provides utility methods and decorators for {@link Queue} instances. * * @since 4.0 * @version $Id: QueueUtils.java 1543964 2013-11-20 21:53:39Z tn $ */ public class QueueUtils { /** * An empty unmodifiable queue. */ @SuppressWarnings("rawtypes") // OK, empty queue is compatible with any type public static final Queue EMPTY_QUEUE = UnmodifiableQueue.unmodifiableQueue(new LinkedList()); /** * QueueUtils should not normally be instantiated. */ private QueueUtils() {} //----------------------------------------------------------------------- /** * Returns an unmodifiable queue backed by the given queue. * * @param the type of the elements in the queue * @param queue the queue to make unmodifiable, must not be null * @return an unmodifiable queue backed by that queue * @throws IllegalArgumentException if the Queue is null */ public static Queue unmodifiableQueue(final Queue queue) { return UnmodifiableQueue.unmodifiableQueue(queue); } /** * Returns a predicated (validating) queue backed by the given queue. *

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

          * Each object is passed through the transformer as it is added to the * Queue. It is important not to use the original queue after invoking this * method, as it is a backdoor for adding untransformed objects. *

          * Existing entries in the specified queue will not be transformed. * If you want that behaviour, see {@link TransformedQueue#transformedQueue}. * * @param the type of the elements in the queue * @param queue the queue to predicate, must not be null * @param transformer the transformer for the queue, must not be null * @return a transformed queue backed by the given queue * @throws IllegalArgumentException if the Queue or Transformer is null */ public static Queue transformingQueue(final Queue queue, final Transformer transformer) { return TransformedQueue.transformingQueue(queue, transformer); } /** * Get an empty Queue. * * @param the type of the elements in the queue * @return an empty {@link Queue} */ @SuppressWarnings("unchecked") // OK, empty queue is compatible with any type public static Queue emptyQueue() { return (Queue) EMPTY_QUEUE; } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/FactoryUtils.java100664 13476 12243235516 30264 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import org.apache.commons.collections4.functors.ConstantFactory; import org.apache.commons.collections4.functors.ExceptionFactory; import org.apache.commons.collections4.functors.InstantiateFactory; import org.apache.commons.collections4.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 3.0 * @version $Id: FactoryUtils.java 1477779 2013-04-30 18:55:24Z tn $ */ public class FactoryUtils { /** * This class is not normally instantiated. */ private FactoryUtils() {} /** * Gets a Factory that always throws an exception. * This could be useful during testing as a placeholder. * * @see org.apache.commons.collections4.functors.ExceptionFactory * * @param the type that the factory creates * @return the factory */ public static Factory exceptionFactory() { return ExceptionFactory.exceptionFactory(); } /** * 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.collections4.functors.ConstantFactory * @param the "type" of null object the factory should return. * @return the factory */ public static Factory nullFactory() { return ConstantFactory.constantFactory(null); } /** * 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.collections4.functors.ConstantFactory * * @param the type that the factory creates * @param constantToReturn the constant object to return each time in the factory * @return the constant factory. */ public static Factory constantFactory(final T constantToReturn) { return ConstantFactory.constantFactory(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.collections4.functors.PrototypeFactory * * @param the type that the factory creates * @param prototype the object to clone each time in the factory * @return the prototype factory, or a {@link ConstantFactory#NULL_INSTANCE} if * the {@code prototype} is {@code null} * @throws IllegalArgumentException if the prototype cannot be cloned */ public static Factory prototypeFactory(final T prototype) { return PrototypeFactory.prototypeFactory(prototype); } /** * Creates a Factory that can create objects of a specific type using * a no-args constructor. * * @see org.apache.commons.collections4.functors.InstantiateFactory * * @param the type that the factory creates * @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(final Class classToInstantiate) { return InstantiateFactory.instantiateFactory(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.collections4.functors.InstantiateFactory * * @param the type that the factory creates * @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(final Class classToInstantiate, final Class[] paramTypes, final Object[] args) { return InstantiateFactory.instantiateFactory(classToInstantiate, paramTypes, args); } } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/BidiMap.java100664 14257 12243235516 27137 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; import java.util.Set; /** * Defines a map that allows bidirectional lookup between key and values. *

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

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

              * This map enforces the restriction that there is a 1:1 relation between * keys and values, meaning that multiple keys cannot map to the same value. * This is required so that "inverting" the map results in a map without * duplicate keys. See the {@link #put} method description for more information. * * @param the type of the keys in the map * @param the type of the values in the map * * @since 3.0 * @version $Id: BidiMap.java 1521272 2013-09-09 20:10:39Z tn $ */ public interface BidiMap extends IterableMap { /** * Puts the key-value pair into the map, replacing any previous pair. *

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

                   *  BidiMap map1 = new DualHashBidiMap();
                   *  map.put("A","B");  // contains A mapped to B, as per Map
                   *  map.put("A","C");  // contains A mapped to C, as per Map
                   *
                   *  BidiMap map2 = new DualHashBidiMap();
                   *  map.put("A","B");  // contains A mapped to B, as per Map
                   *  map.put("C","B");  // contains C mapped to B, key A is removed
                   * 
              * * @param key the key to store * @param value the value to store * @return the previous value mapped to this key * * @throws UnsupportedOperationException if the put method is not supported * @throws ClassCastException (optional) if the map limits the type of the * value and the specified value is inappropriate * @throws IllegalArgumentException (optional) if the map limits the values * in some way and the value was invalid * @throws NullPointerException (optional) if the map limits the values to * non-null and null was specified */ V put(K key, V value); /** * Gets the key that is currently mapped to the specified value. *

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

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

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

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

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

              * Implementations should seek to avoid creating a new object every time this * method is called. See AbstractMap.values() etc. Calling this * method on the inverse map should return the original. * * @return an inverted bidirectional map */ BidiMap inverseBidiMap(); /** * Returns a {@link Set} view of the values contained in this map. * The set is backed by the map, so changes to the map are reflected * in the set, and vice-versa. If the map is modified while an iteration * over the set is in progress (except through the iterator's own * remove operation), the results of the iteration are undefined. * The set supports element removal, which removes the corresponding * mapping from the map, via the Iterator.remove, * Collection.remove, removeAll, * retainAll and clear operations. It does not * support the add or addAll operations. * * @return a set view of the values contained in this map */ Set values(); } commons-collections4-4.0-src/src/main/java/org/apache/commons/collections4/Bag.java100664 21303 12243235516 26311 0ustartntn 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections4; 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. * * @param the type held in the bag * @since 2.0 * @version $Id: Bag.java 1477779 2013-04-30 18:55:24Z tn $ */ 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 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 1. *

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

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

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

              * According to the {@link Collection#remove(Object)} method, * this method should only remove the first occurrence of the * given object, not all occurrences. * * @param object the object to remove * @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(); } commons-collections4-4.0-src/src/conf/checkstyle-suppressions.xml100664 3004 12243235517 23362 0ustartntn 0 0 commons-collections4-4.0-src/src/conf/findbugs-exclude-filter.xml100664 7014 12243235517 23171 0ustartntn 0 0 commons-collections4-4.0-src/src/conf/checkstyle.xml100664 6526 12243235517 20623 0ustartntn 0 0 commons-collections4-4.0-src/src/changes/release-notes.vm100664 7437 12243235517 21542 0ustartntn 0 0 ## Licensed to the Apache Software Foundation (ASF) under one ## or more contributor license agreements. See the NOTICE file ## distributed with this work for additional information ## regarding copyright ownership. The ASF licenses this file ## to you under the Apache License, Version 2.0 (the ## "License"); you may not use this file except in compliance ## with the License. You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, ## software distributed under the License is distributed on an ## "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ## KIND, either express or implied. See the License for the ## specific language governing permissions and limitations ## under the License. Apache ${project.name} ${version} RELEASE NOTES $introduction.replaceAll("(? Commons Collections Changes Resolved generic parameter inconsistency for various static fields, e.g. BagUtils.EMPTY_BAG, TruePredicate.INSTANCE and many others. All accessible static fields use raw types so that they can be used directly without explicit casting. To avoid compiler warnings about unchecked conversion and/or rawtypes use the corresponding factory methods, e.g. BagUtils.emptyBag(). Renamed methods "V MultiKeyMap#remove(Object, Object, ...)" to "V MultiKeyMap#removeMultiKey(Object, Object, ...)" to avoid future conflicts with a default method of the Map interface in Java 8. Renamed "V MultiMap#remove(K, V)" to "boolean MultiMap#removeMapping(K, V)" to avoid future conflicts with a default method of the Map interface in Java 8. Refactored the test framework for Bag implementations to extend from "AbstractCollectionTest" by decorating the concrete Bag instance with a CollectionBag or CollectionSortedBag. "CollectionBag" will now also respect the contract of the decorated bag in case a null argument is provided to either removeAll or retainAll. Added bag decorator "CollectionSortedBag" which decorates a SortedBag to make it comply with the Collection contract. "UnmodifiableBoundedCollection" does now also implement the marker interface "Unmodifiable" similar as all other unmodifiable decorators. "UnmodifiableTrie#unmodifiableTrie(Trie)" will not decorate again an already unmodifiable Trie. Also the return type has been changed to "Trie" to be consistent with other Unmodifiable decorators. Moved "Equator" interface to base package for consistency. Added "CollectionsUtils#matchesAll(Iterable, Predicate)" to test if all elements of a collection match a given predicate. Accept wildcard input where possible, e.g. in copy-constructors, Unmodifiable* decorators and iterators. No collision detection/resolution was performed when calling "CompositeSet#addComposited(...)" with more than one Set as argument. Additionally use varargs parameters instead of arrays in CompositeSet and CompositeCollection constructor and addComposited method. Narrow return type of "BidiMap#values()" to Set as the values are required to be unique. Fixed conversion of timeout parameters in "PassiveExpiringMap". Exception in "ListOrderedMap#putAll" if map contains null values. Made field "collection" in class "AbstractCollectionDecorator" private and added setter "setCollection(Collection)" with scope protected to set the decorated collection during de-serialization. Improved performance of "AbstractMapBag#containsAll(Collection)" by returning immediately after a difference has been found. Renamed class "TransformedMap" in package "splitmap" to "TransformedSplitMap" to avoid name clash with similar class in package "map". Added bag decorator "CollectionBag" which decorates a bag to make it comply with the Collection contract. Replaced "Collection" with "Iterable" for method arguments where applicable. Added "PushbackIterator" decorator to support pushback of elements during iteration. Added "PeekingIterator" decorator to support one-element lookahead during iteration. Added additional clarification to javadoc of interface "Put" wrt return type of "put(Object, Object)" method. Changed "IteratorChain" to use internally a "Queue" instead of a "List". Iterators are removed from the queue once used and can be garbage collected after being exhausted. Additionally removed the methods "setIterator(Iterator)" and "getIterators()". Removed method "setArray(Object)" in class ArrayIterator and method "setArray(Object[])" in class ObjectArrayIterator and made fields array, startIndex and endIndex final. Removed unused class "AbstractUntypedCollectionDecorator<E, D>". Added methods "ListUtils#longestCommonSubsequence(...)" to get the longest common subsequence of arbitrary lists or CharSequences. Changed scope of fields to private where appropriate. An iterator over a "Flat3Map#entrySet()" will now return independent Map.Entry objects that will not change anymore when the iterator progresses. Several closure and transformer implementations in the functors package will now copy an array as input to their constructor (e.g. ChainedClosure). Change base package to org.apache.commons.collections4. The constructors for all Utils classes are now private to prevent instantiation. Added methods "forAllButLastDo(Collection, Closure)" and "forAllButLastDo(Iterator, Closure)" to class "CollectionUtils". Tree traversal with a TreeListIterator will not be affected anymore by the removal of an element directly after a call to previous(). Added method "CollectionUtils#isEqualCollection(Collection, Collection, Equator)". Adapt and/or ignore several unit tests when run on a IBM J9 VM (specification version 1.6.0) due to a faulty "java.util.TreeMap" implementation. SetUniqueList.set(int, E) now works correctly if the object to be inserted is already placed at the given position. MultiKeyMap.clone() now correctly calls super.clone(). Added "emptyIfNull" methods to classes "CollectionUtils", "ListUtils", "SetUtils" and "MapUtils". Improve performance of "TreeList#addAll" and "TreeList(Collection)" by converting the input collection into an AVL tree and efficiently merge it into the existing tree. Replaced "Buffer" interface with "java.util.Queue". Kept "CircularFifoQueue" as well as "Predicated", "Transformed" and "Unmodifiable" decorators. Added method "CollectionUtils#containsAll(Collection, Collection)" with guaranteed runtime complexity of O(n + m) and space complexity of O(n). This method may yield much better performance than "Collection#containsAll(Collection)" depending on the use-case and type of collection used. Fixed performance issue in "SetUniqueList#retainAll" method for large collections. Fixed performance issue in "ListOrderedSet#retainAll" method for large collections. Improved performance of "ListOrderedMap#remove(Object)" method. "CompositeSet" does not inherit from "CompositeCollection" anymore. The inner class "SetMutator" has been updated accordingly. Added method "CollectionUtils#permutations(Collection)" and class "PermutationIterator" to generate unordered permutations of a collection. Update javadoc for "ListUtils#lazyList()" and "ListUtils#fixedSizeList()". Added clarifying javadoc wrt runtime complexity of "AbstractDualBidiMap#retainAll". Added clarifying javadoc wrt runtime complexity of "AbstractLinkedList#retainAll". Added clarifying javadoc wrt runtime complexity of "AbstractLinkedList#removeAll". Fixed several compilation issues with older Java 1.6 compilers. Improved performance of "removeAll()" method for sets returned by "DualHashBidiMap#entrySet()". Improved performance of "CollectionUtils#subtract" methods. Fixed possible "IndexOutOfBoundsException" in "ListOrderedMap#putAll". Improved performance of "SetUniqueList#addAll" method. Improved performance of "ListOrderedSet#addAll" method. Improved performance of "SetUniqueList#removeAll". Improved performance of "ListOrderedSet#remove(Object)" in case the object is not contained in the Set. Improved performance of "ListUtils#subtract" method. Added "ListUtils#select" and "ListUtils#selectRejected" methods. Added an implementation of Eugene Myers difference algorithm in package o.a.c.c.sequence. Added missing null check in "CollectionUtils#addIgnoreNull(Collection, Object)". Added new method "get(int)" to "CircularFifoQueue". Added "LazyIteratorChain" iterator. Added "ListUtils#partition" method to split a List into consecutive sublists. Fixed javadoc for "MapUtils#toProperties(Map)". Clarified javadoc for "TransformerUtils#mapTransformer" for null input. Clarified javadoc for "FactoryUtils#prototypeFactory" for null input. Fixed inconsistent javadoc for "MapUtils#synchronizedMap(Map)". Added "CollectionUtils#forAllDo" implementation which takes an "Iterator" as input. Change maven coordinates to "org.apache.commons.commons-collections4". Move the project structure to a standard maven layout. Fixed infinite loop when calling "UnmodifiableBoundedCollection#unmodifiableBoundedCollection()". Fixed javadoc for several methods wrt expected NullPointerExceptions. Added method "ListUtils#defaultIfNull(List, List)". TransformingComparator now supports different types for its input/output values. "DualTreeBidiMap" now uses the correct comparator for the reverse map during de-serialization. "TransformedMap" in the package "splitmap" can now be serialized. "CollectionUtils#filter(Iterable, Predicate)" will now return whether the collection has been modified. Add method "CollectionUtils#filterInverse(Iterable, Predicate)". "FilterListIterator#hasNext" does not throw a NullPointerException anymore to comply to the Java iterator specification. "ListUtils#intersection(List, List)" will now also work correctly if there are duplicate elements in the provided lists. "AbstractCollectionDecorator" will now use internally "decorated()" to access the decorated collection. Removed features which are now supported by the JDK. Removed debug output in "MapUtils#getNumber(Map)". Fixed javadoc for all "transformedXXX(XXX)" methods in the respective Utils classes to clarify that existing objects in the list are not transformed. Singleton classes in package "functors" are now correctly de-serialized. "NOPClosure" is now a final class. Removed broken methods "equals(Object)" and "hashCode()" in class "NOPClosure". Simplified exceptions as the cause is available from the parent. Fixed cache assignment for "TreeBidiMap#entrySet". Synchronized access to lock in "StaticBucketMap#size()". Added clarification to javadoc of "ListOrderedMap" that "IdentityMap" and "CaseInsensitiveMap" are not supported. Improve javadoc of "CollatingIterator" wrt the used "Comparator" and throw a NullPointerException in "CollatingIterator#least" if no comparator is set. "LRUMap#keySet()#remove(Object)" will not throw a "ConcurrentModificationException" anymore. Improved performance of "ListUtils#intersection(List, List)". Added serialVersionUID fields for "CompositeCollection", "CompositeSet", "EmptyMapMutator", "EmptySetMutator". Fields transformer and decorated in class "TransformingComparator" are now final. Changed behavior of "CaseInsensitiveMap" constructor to be compliant with "HashMap" in case the initial capacity is set to zero. Added NodeListIterator and convenience methods in IteratorUtils to iterate over a org.w3c.dom.NodeList. Improved performance of "StaticBucketMap#putAll(Map)" by iterating over the entry set. Avoid redundant null check in "IteratorUtils#getIterator(Object)". Use a private method to populate the object in "AbstractHashedMap(Map)". Fixed javadoc of "LRUMap" wrt to the maxSize parameter of the constructor. Added new abstract class "CatchAndRethrowClosure" that re-throws any checked exception as unchecked "FunctorException". Use of final keyword where applicable, minor performance improvements by properly initializing the capacity of newly created collections when known in advance. "SetUniqueList#subList()" will now return an unmodifiable list as changes to it may invalidate the parent list. "SetUniqueList#subList()#contains(Object)" will now correctly check the subList rather than the parent list. Added method "CollectionUtils#subtract(Iterable, Iterable, Predicate)". "SetUniqueList#set(int, Object)" will now correctly enforce the uniqueness constraint. Improved javadoc for "Unmodifiable*" classes wrt behavior when the users tries to modify the collection. Calling "CollectionUtils#sizeIsEmpty(null)" will now return true. Added methods "CollectionUtils#collate(...)" to merge two sorted Collections into a sorted List using the standard O(n) merge algorithm. "CaseInsensitiveMap" will now convert input strings to lower-case in a locale-independant manner. Added support for using custom "Equator" objects in "EqualPredicate". Added method "CollatingIterator#getIteratorIndex()". Fixed javadoc for "ListUtils#transformedList(List)" to clarify that existing objects in the list are not transformed. Added method "CollectionUtils#extractSingleton(Collection)". Added serialization support for "TreeBidiMap". The predicate that rejected an object to be added to a "PredicatedCollection" is now contained in the respective exception message. Added "IndexedCollection" collection decorator which provides a map-like view on an existing collection. Added serialization support for "FixedOrderComparator" and "TransformingComparator". "MultiKey" will now be correctly serialized/de-serialized. "TreeBag" will now only accept "Comparable" objects as input when used with natural ordering. Added methods "MapUtils#populateMap(MultiMap, ...)" to support also "MultiMap" instances as input. Fixed javadoc for methods "firstKey()" and "lastKey()" in class "AbstractLinkedMap". "Flat3Map#remove(Object)" will now return the correct value mapped to the removed key if the size of the map is less or equal 3. Added constructor "TransformingComparator(Transformer)". Added "DualLinkedHashBidiMap" bidi map implementation. Removed unused variables in "TreeBidiMap". The static factory methods have been renamed from "getInstance()" to a camel-case version of the class name, e.g. "truePredicate()" for class "TruePredicate". "SetUniqueList.addAll(int, Collection)" now correctly add the collection at the provided index. Added "Equator" interface. Added "PassiveExpiringMap" map decorator. "MultiValueMap" is now serializable. Added method "MultiValueMap#iterator()" to return a flattened version of "entrySet().iterator()". Clarified javadoc for "entrySet()" that the returned Entry objects are unflattened, i.e. the Entry object for a given key contains all values mapped to this key. Added method "ListUtils#indexOf(List, Predicate)". Fixed several unit tests which were using parameters to "assertEquals(...)" in wrong order. Return concrete class in static factory methods instead of base class interface (except for Unmodifiable decorators). "CollectionUtils#size(Collection)" now returns 0 when called with null as input. Removed deprecated classes and methods. "MultiValueMap#put(Object, Object)" and "MultiValueMap#putAll(Object, Collection)" now correctly return if the map has changed by this operation. Added method "ListOrderedMap#putAll(int, Map)". Added new "Trie" interface with a first concrete implementation "PatriciaTrie" together with decorators "Unmodifiable" and "Synchronized". "CollectionUtils#addAll(...)" methods now return if the collection has been changed by this operation. "CompositeCollection", "CompositeMap" and "CompositeSet" are now serializable. "CollectionUtils#removeAll" wrongly called "ListUtils#retainAll". The "CollectionUtils#select(Collection, Predicate, Collection)" method will now return the output collection. Calling "setValue(Object)" on any Entry returned by a "Flat3Map" will now correctly set the value for the current entry. "MultiKey#toString()" will now use "Arrays#toString(List)". Added support for resettable iterators in "IteratorIterable". Added methods "MapUtils#populateMap(Map, Iterable, Transformer, ...)". "CollectionUtils#forAllDo(Collection, Closure)" now returns the provided closure. Make generic versions of all classes in collections. Added class "ComparatorPredicate".