From 6144a5bb889be4a4d5cda46ecd6b40fe9bfa74d3 Mon Sep 17 00:00:00 2001 From: embeddedt <42941056+embeddedt@users.noreply.github.com> Date: Thu, 4 Jan 2024 12:18:34 -0500 Subject: [PATCH] Backport Gradle scripting from 1.20 to reduce extra repackaging and allow running in dev --- build.gradle | 40 +- glsl-relocated/build.gradle | 42 + settings.gradle | 2 + .../pipeline/transform/TransformPatcher.java | 4 +- src/main/java/org/anarres/cpp/Argument.java | 76 - .../org/anarres/cpp/ChrootFileSystem.java | 84 - src/main/java/org/anarres/cpp/CppReader.java | 153 -- src/main/java/org/anarres/cpp/CppTask.java | 215 -- .../cpp/DefaultPreprocessorListener.java | 98 - src/main/java/org/anarres/cpp/Feature.java | 42 - .../java/org/anarres/cpp/FileLexerSource.java | 99 - .../org/anarres/cpp/FixedTokenSource.java | 59 - .../org/anarres/cpp/InputLexerSource.java | 71 - .../org/anarres/cpp/InternalException.java | 31 - .../java/org/anarres/cpp/JavaFileSystem.java | 84 - src/main/java/org/anarres/cpp/JoinReader.java | 218 -- .../java/org/anarres/cpp/LexerException.java | 33 - .../java/org/anarres/cpp/LexerSource.java | 1060 ------- src/main/java/org/anarres/cpp/Macro.java | 187 -- .../org/anarres/cpp/MacroTokenSource.java | 249 -- .../java/org/anarres/cpp/NumericValue.java | 229 -- .../java/org/anarres/cpp/Preprocessor.java | 2226 --------------- .../org/anarres/cpp/PreprocessorCommand.java | 44 - .../org/anarres/cpp/PreprocessorListener.java | 59 - .../org/anarres/cpp/ResourceFileSystem.java | 82 - src/main/java/org/anarres/cpp/Source.java | 298 -- .../java/org/anarres/cpp/SourceIterator.java | 93 - src/main/java/org/anarres/cpp/State.java | 68 - .../org/anarres/cpp/StringLexerSource.java | 58 - src/main/java/org/anarres/cpp/Token.java | 215 -- .../org/anarres/cpp/TokenSnifferSource.java | 46 - src/main/java/org/anarres/cpp/TokenType.java | 173 -- .../java/org/anarres/cpp/VirtualFile.java | 46 - .../org/anarres/cpp/VirtualFileSystem.java | 31 - src/main/java/org/anarres/cpp/Warning.java | 32 - .../commons/collections4/ArrayStack.java | 165 -- .../commons/collections4/ArrayUtils.java | 131 - .../apache/commons/collections4/Bag.java | 243 -- .../apache/commons/collections4/BagUtils.java | 267 -- .../apache/commons/collections4/BidiMap.java | 155 -- .../collections4/BoundedCollection.java | 51 - .../commons/collections4/BoundedMap.java | 47 - .../apache/commons/collections4/Closure.java | 46 - .../commons/collections4/ClosureUtils.java | 375 --- .../commons/collections4/CollectionUtils.java | 2156 --------------- .../commons/collections4/ComparatorUtils.java | 243 -- .../collections4/EnumerationUtils.java | 112 - .../apache/commons/collections4/Equator.java | 49 - .../apache/commons/collections4/Factory.java | 46 - .../commons/collections4/FactoryUtils.java | 150 - .../commons/collections4/FluentIterable.java | 491 ---- .../collections4/FunctorException.java | 70 - .../apache/commons/collections4/Get.java | 95 - .../commons/collections4/IterableGet.java | 48 - .../commons/collections4/IterableMap.java | 44 - .../collections4/IterableSortedMap.java | 30 - .../commons/collections4/IterableUtils.java | 1043 ------- .../commons/collections4/IteratorUtils.java | 1444 ---------- .../apache/commons/collections4/KeyValue.java | 47 - .../commons/collections4/ListUtils.java | 749 ----- .../commons/collections4/ListValuedMap.java | 69 - .../commons/collections4/MapIterator.java | 112 - .../apache/commons/collections4/MapUtils.java | 2031 -------------- .../apache/commons/collections4/MultiMap.java | 169 -- .../commons/collections4/MultiMapUtils.java | 245 -- .../apache/commons/collections4/MultiSet.java | 272 -- .../commons/collections4/MultiSetUtils.java | 117 - .../commons/collections4/MultiValuedMap.java | 323 --- .../commons/collections4/OrderedBidiMap.java | 52 - .../commons/collections4/OrderedIterator.java | 47 - .../commons/collections4/OrderedMap.java | 73 - .../collections4/OrderedMapIterator.java | 48 - .../commons/collections4/Predicate.java | 51 - .../commons/collections4/PredicateUtils.java | 526 ---- .../apache/commons/collections4/Put.java | 65 - .../commons/collections4/QueueUtils.java | 138 - .../collections4/ResettableIterator.java | 38 - .../collections4/ResettableListIterator.java | 32 - .../apache/commons/collections4/SetUtils.java | 657 ----- .../commons/collections4/SetValuedMap.java | 67 - .../commons/collections4/SortedBag.java | 52 - .../commons/collections4/SortedBidiMap.java | 59 - .../commons/collections4/SplitMapUtils.java | 266 -- .../commons/collections4/Transformer.java | 53 - .../collections4/TransformerUtils.java | 485 ---- .../apache/commons/collections4/Trie.java | 48 - .../commons/collections4/TrieUtils.java | 48 - .../commons/collections4/Unmodifiable.java | 38 - .../bag/AbstractBagDecorator.java | 97 - .../collections4/bag/AbstractMapBag.java | 604 ---- .../bag/AbstractSortedBagDecorator.java | 81 - .../collections4/bag/CollectionBag.java | 227 -- .../collections4/bag/CollectionSortedBag.java | 151 - .../commons/collections4/bag/HashBag.java | 85 - .../collections4/bag/PredicatedBag.java | 126 - .../collections4/bag/PredicatedSortedBag.java | 108 - .../collections4/bag/SynchronizedBag.java | 150 - .../bag/SynchronizedSortedBag.java | 108 - .../collections4/bag/TransformedBag.java | 147 - .../bag/TransformedSortedBag.java | 131 - .../commons/collections4/bag/TreeBag.java | 145 - .../collections4/bag/UnmodifiableBag.java | 165 -- .../bag/UnmodifiableSortedBag.java | 162 -- .../collections4/bag/package-info.java | 38 - .../bidimap/AbstractBidiMapDecorator.java | 91 - .../bidimap/AbstractDualBidiMap.java | 815 ------ .../AbstractOrderedBidiMapDecorator.java | 94 - .../AbstractSortedBidiMapDecorator.java | 95 - .../collections4/bidimap/DualHashBidiMap.java | 110 - .../bidimap/DualLinkedHashBidiMap.java | 103 - .../collections4/bidimap/DualTreeBidiMap.java | 412 --- .../collections4/bidimap/TreeBidiMap.java | 2237 --------------- .../bidimap/UnmodifiableBidiMap.java | 135 - .../bidimap/UnmodifiableOrderedBidiMap.java | 145 - .../bidimap/UnmodifiableSortedBidiMap.java | 155 -- .../collections4/bidimap/package-info.java | 40 - .../bloomfilter/ArrayCountingBloomFilter.java | 258 -- .../bloomfilter/BitCountProducer.java | 126 - .../collections4/bloomfilter/BitMap.java | 116 - .../bloomfilter/BitMapProducer.java | 155 -- .../collections4/bloomfilter/BloomFilter.java | 260 -- .../bloomfilter/CountingBloomFilter.java | 284 -- .../bloomfilter/CountingLongPredicate.java | 68 - .../bloomfilter/EnhancedDoubleHasher.java | 227 -- .../collections4/bloomfilter/Hasher.java | 64 - .../collections4/bloomfilter/IndexFilter.java | 133 - .../bloomfilter/IndexProducer.java | 127 - .../bloomfilter/LongBiPredicate.java | 37 - .../bloomfilter/SetOperations.java | 191 -- .../collections4/bloomfilter/Shape.java | 440 --- .../bloomfilter/SimpleBloomFilter.java | 195 -- .../bloomfilter/SparseBloomFilter.java | 197 -- .../bloomfilter/package-info.java | 102 - .../AbstractCollectionDecorator.java | 185 -- .../collection/CompositeCollection.java | 509 ---- .../collection/IndexedCollection.java | 285 -- .../collection/PredicatedCollection.java | 428 --- .../collection/SynchronizedCollection.java | 234 -- .../collection/TransformedCollection.java | 152 - .../UnmodifiableBoundedCollection.java | 175 -- .../collection/UnmodifiableCollection.java | 119 - .../collections4/collection/package-info.java | 35 - .../comparators/BooleanComparator.java | 189 -- .../comparators/ComparableComparator.java | 126 - .../comparators/ComparatorChain.java | 348 --- .../comparators/FixedOrderComparator.java | 286 -- .../comparators/NullComparator.java | 184 -- .../comparators/ReverseComparator.java | 120 - .../comparators/TransformingComparator.java | 131 - .../comparators/package-info.java | 27 - .../functors/AbstractQuantifierPredicate.java | 56 - .../collections4/functors/AllPredicate.java | 116 - .../collections4/functors/AndPredicate.java | 89 - .../collections4/functors/AnyPredicate.java | 113 - .../functors/CatchAndRethrowClosure.java | 76 - .../collections4/functors/ChainedClosure.java | 124 - .../functors/ChainedTransformer.java | 128 - .../functors/CloneTransformer.java | 72 - .../functors/ClosureTransformer.java | 83 - .../functors/ComparatorPredicate.java | 186 -- .../functors/ConstantFactory.java | 89 - .../functors/ConstantTransformer.java | 128 - .../collections4/functors/DefaultEquator.java | 83 - .../collections4/functors/EqualPredicate.java | 120 - .../functors/ExceptionClosure.java | 70 - .../functors/ExceptionFactory.java | 70 - .../functors/ExceptionPredicate.java | 71 - .../functors/ExceptionTransformer.java | 72 - .../functors/FactoryTransformer.java | 83 - .../collections4/functors/FalsePredicate.java | 69 - .../collections4/functors/ForClosure.java | 105 - .../collections4/functors/FunctorUtils.java | 195 -- .../functors/IdentityPredicate.java | 83 - .../collections4/functors/IfClosure.java | 152 - .../collections4/functors/IfTransformer.java | 141 - .../functors/InstanceofPredicate.java | 80 - .../functors/InstantiateFactory.java | 137 - .../functors/InstantiateTransformer.java | 128 - .../functors/InvokerTransformer.java | 141 - .../collections4/functors/MapTransformer.java | 86 - .../collections4/functors/NOPClosure.java | 68 - .../collections4/functors/NOPTransformer.java | 69 - .../collections4/functors/NonePredicate.java | 103 - .../functors/NotNullPredicate.java | 69 - .../collections4/functors/NotPredicate.java | 82 - .../functors/NullIsExceptionPredicate.java | 88 - .../functors/NullIsFalsePredicate.java | 86 - .../functors/NullIsTruePredicate.java | 86 - .../collections4/functors/NullPredicate.java | 69 - .../collections4/functors/OnePredicate.java | 108 - .../collections4/functors/OrPredicate.java | 89 - .../functors/PredicateDecorator.java | 41 - .../functors/PredicateTransformer.java | 84 - .../functors/PrototypeFactory.java | 202 -- .../functors/StringValueTransformer.java | 70 - .../collections4/functors/SwitchClosure.java | 184 -- .../functors/SwitchTransformer.java | 198 -- .../functors/TransformedPredicate.java | 104 - .../functors/TransformerClosure.java | 84 - .../functors/TransformerPredicate.java | 88 - .../collections4/functors/TruePredicate.java | 69 - .../functors/UniquePredicate.java | 69 - .../collections4/functors/WhileClosure.java | 120 - .../collections4/functors/package-info.java | 42 - .../iterators/AbstractEmptyIterator.java | 74 - .../iterators/AbstractEmptyMapIterator.java | 46 - .../iterators/AbstractIteratorDecorator.java | 46 - .../AbstractListIteratorDecorator.java | 108 - .../AbstractMapIteratorDecorator.java | 93 - .../AbstractOrderedMapIteratorDecorator.java | 105 - .../AbstractUntypedIteratorDecorator.java | 64 - .../collections4/iterators/ArrayIterator.java | 198 -- .../iterators/ArrayListIterator.java | 207 -- .../iterators/BoundedIterator.java | 136 - .../iterators/CollatingIterator.java | 387 --- .../collections4/iterators/EmptyIterator.java | 73 - .../iterators/EmptyListIterator.java | 74 - .../iterators/EmptyMapIterator.java | 55 - .../iterators/EmptyOrderedIterator.java | 53 - .../iterators/EmptyOrderedMapIterator.java | 55 - .../iterators/EntrySetMapIterator.java | 172 -- .../iterators/EnumerationIterator.java | 135 - .../iterators/FilterIterator.java | 178 -- .../iterators/FilterListIterator.java | 277 -- .../collections4/iterators/IteratorChain.java | 270 -- .../iterators/IteratorEnumeration.java | 91 - .../iterators/IteratorIterable.java | 138 - .../iterators/LazyIteratorChain.java | 150 - .../iterators/ListIteratorWrapper.java | 263 -- .../iterators/LoopingIterator.java | 127 - .../iterators/LoopingListIterator.java | 262 -- .../iterators/NodeListIterator.java | 87 - .../iterators/ObjectArrayIterator.java | 170 -- .../iterators/ObjectArrayListIterator.java | 196 -- .../iterators/ObjectGraphIterator.java | 250 -- .../iterators/PeekingIterator.java | 157 -- .../iterators/PermutationIterator.java | 156 -- .../iterators/PushbackIterator.java | 105 - .../iterators/ReverseListIterator.java | 183 -- .../iterators/SingletonIterator.java | 124 - .../iterators/SingletonListIterator.java | 181 -- .../iterators/SkippingIterator.java | 98 - .../iterators/TransformIterator.java | 138 - .../iterators/UniqueFilterIterator.java | 42 - .../iterators/UnmodifiableIterator.java | 82 - .../iterators/UnmodifiableListIterator.java | 124 - .../iterators/UnmodifiableMapIterator.java | 98 - .../UnmodifiableOrderedMapIterator.java | 109 - .../iterators/ZippingIterator.java | 154 -- .../collections4/iterators/package-info.java | 27 - .../keyvalue/AbstractKeyValue.java | 93 - .../keyvalue/AbstractMapEntry.java | 90 - .../keyvalue/AbstractMapEntryDecorator.java | 90 - .../keyvalue/DefaultKeyValue.java | 153 -- .../keyvalue/DefaultMapEntry.java | 63 - .../collections4/keyvalue/MultiKey.java | 332 --- .../collections4/keyvalue/TiedMapEntry.java | 139 - .../keyvalue/UnmodifiableMapEntry.java | 76 - .../collections4/keyvalue/package-info.java | 29 - .../collections4/list/AbstractLinkedList.java | 1080 -------- .../list/AbstractListDecorator.java | 128 - .../AbstractSerializableListDecorator.java | 70 - .../list/CursorableLinkedList.java | 613 ----- .../collections4/list/FixedSizeList.java | 203 -- .../commons/collections4/list/GrowthList.java | 190 -- .../commons/collections4/list/LazyList.java | 190 -- .../list/NodeCachingLinkedList.java | 248 -- .../collections4/list/PredicatedList.java | 193 -- .../collections4/list/SetUniqueList.java | 429 --- .../collections4/list/TransformedList.java | 210 -- .../commons/collections4/list/TreeList.java | 1125 -------- .../collections4/list/UnmodifiableList.java | 155 -- .../collections4/list/package-info.java | 39 - .../collections4/map/AbstractHashedMap.java | 1398 ---------- .../map/AbstractInputCheckedMapDecorator.java | 207 -- .../collections4/map/AbstractIterableMap.java | 38 - .../collections4/map/AbstractLinkedMap.java | 616 ----- .../map/AbstractMapDecorator.java | 152 - .../map/AbstractOrderedMapDecorator.java | 95 - .../map/AbstractReferenceMap.java | 1122 -------- .../map/AbstractSortedMapDecorator.java | 172 -- .../collections4/map/CaseInsensitiveMap.java | 177 -- .../collections4/map/CompositeMap.java | 567 ---- .../collections4/map/DefaultedMap.java | 205 -- .../map/EntrySetToMapIteratorAdapter.java | 122 - .../collections4/map/FixedSizeMap.java | 174 -- .../collections4/map/FixedSizeSortedMap.java | 192 -- .../commons/collections4/map/Flat3Map.java | 1280 --------- .../commons/collections4/map/HashedMap.java | 124 - .../commons/collections4/map/LRUMap.java | 528 ---- .../commons/collections4/map/LazyMap.java | 173 -- .../collections4/map/LazySortedMap.java | 167 -- .../commons/collections4/map/LinkedMap.java | 324 --- .../collections4/map/ListOrderedMap.java | 791 ------ .../commons/collections4/map/MultiKeyMap.java | 904 ------ .../collections4/map/MultiValueMap.java | 573 ---- .../collections4/map/PassiveExpiringMap.java | 535 ---- .../collections4/map/PredicatedMap.java | 187 -- .../collections4/map/PredicatedSortedMap.java | 136 - .../map/ReferenceIdentityMap.java | 253 -- .../collections4/map/ReferenceMap.java | 199 -- .../collections4/map/SingletonMap.java | 594 ---- .../collections4/map/StaticBucketMap.java | 728 ----- .../collections4/map/TransformedMap.java | 246 -- .../map/TransformedSortedMap.java | 166 -- .../map/UnmodifiableEntrySet.java | 190 -- .../collections4/map/UnmodifiableMap.java | 159 -- .../map/UnmodifiableOrderedMap.java | 153 -- .../map/UnmodifiableSortedMap.java | 174 -- .../collections4/map/package-info.java | 54 - .../multimap/AbstractListValuedMap.java | 287 -- .../multimap/AbstractMultiValuedMap.java | 921 ------- .../AbstractMultiValuedMapDecorator.java | 184 -- .../multimap/AbstractSetValuedMap.java | 132 - .../multimap/ArrayListValuedHashMap.java | 142 - .../multimap/HashSetValuedHashMap.java | 131 - .../multimap/TransformedMultiValuedMap.java | 188 -- .../multimap/UnmodifiableMultiValuedMap.java | 152 - .../collections4/multimap/package-info.java | 34 - .../multiset/AbstractMapMultiSet.java | 553 ---- .../multiset/AbstractMultiSet.java | 489 ---- .../multiset/AbstractMultiSetDecorator.java | 106 - .../collections4/multiset/HashMultiSet.java | 84 - .../multiset/PredicatedMultiSet.java | 137 - .../multiset/SynchronizedMultiSet.java | 162 -- .../multiset/UnmodifiableMultiSet.java | 172 -- .../collections4/multiset/package-info.java | 35 - .../apache/commons/collections4/overview.html | 112 - .../commons/collections4/package-info.java | 26 - .../properties/AbstractPropertiesFactory.java | 216 -- .../properties/PropertiesFactory.java | 348 --- .../properties/SortedProperties.java | 58 - .../properties/SortedPropertiesFactory.java | 50 - .../collections4/properties/package-info.java | 26 - .../queue/AbstractQueueDecorator.java | 97 - .../collections4/queue/CircularFifoQueue.java | 428 --- .../collections4/queue/PredicatedQueue.java | 123 - .../collections4/queue/SynchronizedQueue.java | 141 - .../collections4/queue/TransformedQueue.java | 138 - .../collections4/queue/UnmodifiableQueue.java | 159 -- .../collections4/queue/package-info.java | 33 - .../collections4/sequence/CommandVisitor.java | 146 - .../collections4/sequence/DeleteCommand.java | 55 - .../collections4/sequence/EditCommand.java | 83 - .../collections4/sequence/EditScript.java | 134 - .../collections4/sequence/InsertCommand.java | 57 - .../collections4/sequence/KeepCommand.java | 57 - .../sequence/ReplacementsFinder.java | 113 - .../sequence/ReplacementsHandler.java | 52 - .../sequence/SequencesComparator.java | 346 --- .../collections4/sequence/package-info.java | 76 - .../set/AbstractNavigableSetDecorator.java | 121 - .../set/AbstractSerializableSetDecorator.java | 71 - .../set/AbstractSetDecorator.java | 75 - .../set/AbstractSortedSetDecorator.java | 96 - .../collections4/set/CompositeSet.java | 529 ---- .../collections4/set/ListOrderedSet.java | 410 --- .../collections4/set/MapBackedSet.java | 186 -- .../set/PredicatedNavigableSet.java | 153 -- .../collections4/set/PredicatedSet.java | 101 - .../collections4/set/PredicatedSortedSet.java | 129 - .../set/TransformedNavigableSet.java | 173 -- .../collections4/set/TransformedSet.java | 115 - .../set/TransformedSortedSet.java | 149 - .../set/UnmodifiableNavigableSet.java | 204 -- .../collections4/set/UnmodifiableSet.java | 118 - .../set/UnmodifiableSortedSet.java | 160 -- .../collections4/set/package-info.java | 40 - .../AbstractIterableGetMapDecorator.java | 137 - .../splitmap/TransformedSplitMap.java | 214 -- .../collections4/splitmap/package-info.java | 38 - .../trie/AbstractBitwiseTrie.java | 215 -- .../trie/AbstractPatriciaTrie.java | 2441 ----------------- .../collections4/trie/KeyAnalyzer.java | 151 - .../collections4/trie/PatriciaTrie.java | 77 - .../collections4/trie/UnmodifiableTrie.java | 204 -- .../trie/analyzer/StringKeyAnalyzer.java | 135 - .../trie/analyzer/package-info.java | 21 - .../collections4/trie/package-info.java | 36 - 379 files changed, 77 insertions(+), 79449 deletions(-) create mode 100644 glsl-relocated/build.gradle delete mode 100644 src/main/java/org/anarres/cpp/Argument.java delete mode 100644 src/main/java/org/anarres/cpp/ChrootFileSystem.java delete mode 100644 src/main/java/org/anarres/cpp/CppReader.java delete mode 100644 src/main/java/org/anarres/cpp/CppTask.java delete mode 100644 src/main/java/org/anarres/cpp/DefaultPreprocessorListener.java delete mode 100644 src/main/java/org/anarres/cpp/Feature.java delete mode 100644 src/main/java/org/anarres/cpp/FileLexerSource.java delete mode 100644 src/main/java/org/anarres/cpp/FixedTokenSource.java delete mode 100644 src/main/java/org/anarres/cpp/InputLexerSource.java delete mode 100644 src/main/java/org/anarres/cpp/InternalException.java delete mode 100644 src/main/java/org/anarres/cpp/JavaFileSystem.java delete mode 100644 src/main/java/org/anarres/cpp/JoinReader.java delete mode 100644 src/main/java/org/anarres/cpp/LexerException.java delete mode 100644 src/main/java/org/anarres/cpp/LexerSource.java delete mode 100644 src/main/java/org/anarres/cpp/Macro.java delete mode 100644 src/main/java/org/anarres/cpp/MacroTokenSource.java delete mode 100644 src/main/java/org/anarres/cpp/NumericValue.java delete mode 100644 src/main/java/org/anarres/cpp/Preprocessor.java delete mode 100644 src/main/java/org/anarres/cpp/PreprocessorCommand.java delete mode 100644 src/main/java/org/anarres/cpp/PreprocessorListener.java delete mode 100644 src/main/java/org/anarres/cpp/ResourceFileSystem.java delete mode 100644 src/main/java/org/anarres/cpp/Source.java delete mode 100644 src/main/java/org/anarres/cpp/SourceIterator.java delete mode 100644 src/main/java/org/anarres/cpp/State.java delete mode 100644 src/main/java/org/anarres/cpp/StringLexerSource.java delete mode 100644 src/main/java/org/anarres/cpp/Token.java delete mode 100644 src/main/java/org/anarres/cpp/TokenSnifferSource.java delete mode 100644 src/main/java/org/anarres/cpp/TokenType.java delete mode 100644 src/main/java/org/anarres/cpp/VirtualFile.java delete mode 100644 src/main/java/org/anarres/cpp/VirtualFileSystem.java delete mode 100644 src/main/java/org/anarres/cpp/Warning.java delete mode 100644 src/main/java/repack/apache/commons/collections4/ArrayStack.java delete mode 100644 src/main/java/repack/apache/commons/collections4/ArrayUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/Bag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/BagUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/BidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/BoundedCollection.java delete mode 100644 src/main/java/repack/apache/commons/collections4/BoundedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/Closure.java delete mode 100644 src/main/java/repack/apache/commons/collections4/ClosureUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/CollectionUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/ComparatorUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/EnumerationUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/Equator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/Factory.java delete mode 100644 src/main/java/repack/apache/commons/collections4/FactoryUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/FluentIterable.java delete mode 100644 src/main/java/repack/apache/commons/collections4/FunctorException.java delete mode 100644 src/main/java/repack/apache/commons/collections4/Get.java delete mode 100644 src/main/java/repack/apache/commons/collections4/IterableGet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/IterableMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/IterableSortedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/IterableUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/IteratorUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/KeyValue.java delete mode 100644 src/main/java/repack/apache/commons/collections4/ListUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/ListValuedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/MapIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/MapUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/MultiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/MultiMapUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/MultiSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/MultiSetUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/MultiValuedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/OrderedBidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/OrderedIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/OrderedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/OrderedMapIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/Predicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/PredicateUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/Put.java delete mode 100644 src/main/java/repack/apache/commons/collections4/QueueUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/ResettableIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/ResettableListIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/SetUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/SetValuedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/SortedBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/SortedBidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/SplitMapUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/Transformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/TransformerUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/Trie.java delete mode 100644 src/main/java/repack/apache/commons/collections4/TrieUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/Unmodifiable.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/AbstractBagDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/AbstractMapBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/AbstractSortedBagDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/CollectionBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/CollectionSortedBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/HashBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/PredicatedBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/PredicatedSortedBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/SynchronizedBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/SynchronizedSortedBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/TransformedBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/TransformedSortedBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/TreeBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/UnmodifiableBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/UnmodifiableSortedBag.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bag/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/AbstractBidiMapDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/AbstractDualBidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/AbstractOrderedBidiMapDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/AbstractSortedBidiMapDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/DualHashBidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/DualLinkedHashBidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/DualTreeBidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/TreeBidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableBidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableOrderedBidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableSortedBidiMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bidimap/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/ArrayCountingBloomFilter.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/BitCountProducer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/BitMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/BitMapProducer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/BloomFilter.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/CountingBloomFilter.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/CountingLongPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/EnhancedDoubleHasher.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/Hasher.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/IndexFilter.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/IndexProducer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/LongBiPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/SetOperations.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/Shape.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/SimpleBloomFilter.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/SparseBloomFilter.java delete mode 100644 src/main/java/repack/apache/commons/collections4/bloomfilter/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/collection/AbstractCollectionDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/collection/CompositeCollection.java delete mode 100644 src/main/java/repack/apache/commons/collections4/collection/IndexedCollection.java delete mode 100644 src/main/java/repack/apache/commons/collections4/collection/PredicatedCollection.java delete mode 100644 src/main/java/repack/apache/commons/collections4/collection/SynchronizedCollection.java delete mode 100644 src/main/java/repack/apache/commons/collections4/collection/TransformedCollection.java delete mode 100644 src/main/java/repack/apache/commons/collections4/collection/UnmodifiableBoundedCollection.java delete mode 100644 src/main/java/repack/apache/commons/collections4/collection/UnmodifiableCollection.java delete mode 100644 src/main/java/repack/apache/commons/collections4/collection/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/comparators/BooleanComparator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/comparators/ComparableComparator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/comparators/ComparatorChain.java delete mode 100644 src/main/java/repack/apache/commons/collections4/comparators/FixedOrderComparator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/comparators/NullComparator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/comparators/ReverseComparator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/comparators/TransformingComparator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/comparators/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/AbstractQuantifierPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/AllPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/AndPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/AnyPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/CatchAndRethrowClosure.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ChainedClosure.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ChainedTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/CloneTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ClosureTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ComparatorPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ConstantFactory.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ConstantTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/DefaultEquator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/EqualPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ExceptionClosure.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ExceptionFactory.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ExceptionPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ExceptionTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/FactoryTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/FalsePredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/ForClosure.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/FunctorUtils.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/IdentityPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/IfClosure.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/IfTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/InstanceofPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/InstantiateFactory.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/InstantiateTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/InvokerTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/MapTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/NOPClosure.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/NOPTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/NonePredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/NotNullPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/NotPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/NullIsExceptionPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/NullIsFalsePredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/NullIsTruePredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/NullPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/OnePredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/OrPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/PredicateDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/PredicateTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/PrototypeFactory.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/StringValueTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/SwitchClosure.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/SwitchTransformer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/TransformedPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/TransformerClosure.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/TransformerPredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/TruePredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/UniquePredicate.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/WhileClosure.java delete mode 100644 src/main/java/repack/apache/commons/collections4/functors/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/AbstractEmptyIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/AbstractEmptyMapIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/AbstractIteratorDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/AbstractListIteratorDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/AbstractMapIteratorDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/AbstractOrderedMapIteratorDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/AbstractUntypedIteratorDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/ArrayIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/ArrayListIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/BoundedIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/CollatingIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/EmptyIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/EmptyListIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/EmptyMapIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/EmptyOrderedIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/EmptyOrderedMapIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/EntrySetMapIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/EnumerationIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/FilterIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/FilterListIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/IteratorChain.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/IteratorEnumeration.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/IteratorIterable.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/LazyIteratorChain.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/ListIteratorWrapper.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/LoopingIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/LoopingListIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/NodeListIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/ObjectArrayIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/ObjectArrayListIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/ObjectGraphIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/PeekingIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/PermutationIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/PushbackIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/ReverseListIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/SingletonIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/SingletonListIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/SkippingIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/TransformIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/UniqueFilterIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableListIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableMapIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableOrderedMapIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/ZippingIterator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/iterators/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/keyvalue/AbstractKeyValue.java delete mode 100644 src/main/java/repack/apache/commons/collections4/keyvalue/AbstractMapEntry.java delete mode 100644 src/main/java/repack/apache/commons/collections4/keyvalue/AbstractMapEntryDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/keyvalue/DefaultKeyValue.java delete mode 100644 src/main/java/repack/apache/commons/collections4/keyvalue/DefaultMapEntry.java delete mode 100644 src/main/java/repack/apache/commons/collections4/keyvalue/MultiKey.java delete mode 100644 src/main/java/repack/apache/commons/collections4/keyvalue/TiedMapEntry.java delete mode 100644 src/main/java/repack/apache/commons/collections4/keyvalue/UnmodifiableMapEntry.java delete mode 100644 src/main/java/repack/apache/commons/collections4/keyvalue/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/AbstractLinkedList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/AbstractListDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/AbstractSerializableListDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/CursorableLinkedList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/FixedSizeList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/GrowthList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/LazyList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/NodeCachingLinkedList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/PredicatedList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/SetUniqueList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/TransformedList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/TreeList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/UnmodifiableList.java delete mode 100644 src/main/java/repack/apache/commons/collections4/list/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/AbstractHashedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/AbstractInputCheckedMapDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/AbstractIterableMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/AbstractLinkedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/AbstractMapDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/AbstractOrderedMapDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/AbstractReferenceMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/AbstractSortedMapDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/CaseInsensitiveMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/CompositeMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/DefaultedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/EntrySetToMapIteratorAdapter.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/FixedSizeMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/FixedSizeSortedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/Flat3Map.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/HashedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/LRUMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/LazyMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/LazySortedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/LinkedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/ListOrderedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/MultiKeyMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/MultiValueMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/PassiveExpiringMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/PredicatedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/PredicatedSortedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/ReferenceIdentityMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/ReferenceMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/SingletonMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/StaticBucketMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/TransformedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/TransformedSortedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/UnmodifiableEntrySet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/UnmodifiableMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/UnmodifiableOrderedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/UnmodifiableSortedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/map/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multimap/AbstractListValuedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multimap/AbstractMultiValuedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multimap/AbstractMultiValuedMapDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multimap/AbstractSetValuedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multimap/ArrayListValuedHashMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multimap/HashSetValuedHashMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multimap/TransformedMultiValuedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multimap/UnmodifiableMultiValuedMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multimap/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multiset/AbstractMapMultiSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multiset/AbstractMultiSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multiset/AbstractMultiSetDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multiset/HashMultiSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multiset/PredicatedMultiSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multiset/SynchronizedMultiSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multiset/UnmodifiableMultiSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/multiset/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/overview.html delete mode 100644 src/main/java/repack/apache/commons/collections4/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/properties/AbstractPropertiesFactory.java delete mode 100644 src/main/java/repack/apache/commons/collections4/properties/PropertiesFactory.java delete mode 100644 src/main/java/repack/apache/commons/collections4/properties/SortedProperties.java delete mode 100644 src/main/java/repack/apache/commons/collections4/properties/SortedPropertiesFactory.java delete mode 100644 src/main/java/repack/apache/commons/collections4/properties/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/queue/AbstractQueueDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/queue/CircularFifoQueue.java delete mode 100644 src/main/java/repack/apache/commons/collections4/queue/PredicatedQueue.java delete mode 100644 src/main/java/repack/apache/commons/collections4/queue/SynchronizedQueue.java delete mode 100644 src/main/java/repack/apache/commons/collections4/queue/TransformedQueue.java delete mode 100644 src/main/java/repack/apache/commons/collections4/queue/UnmodifiableQueue.java delete mode 100644 src/main/java/repack/apache/commons/collections4/queue/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/sequence/CommandVisitor.java delete mode 100644 src/main/java/repack/apache/commons/collections4/sequence/DeleteCommand.java delete mode 100644 src/main/java/repack/apache/commons/collections4/sequence/EditCommand.java delete mode 100644 src/main/java/repack/apache/commons/collections4/sequence/EditScript.java delete mode 100644 src/main/java/repack/apache/commons/collections4/sequence/InsertCommand.java delete mode 100644 src/main/java/repack/apache/commons/collections4/sequence/KeepCommand.java delete mode 100644 src/main/java/repack/apache/commons/collections4/sequence/ReplacementsFinder.java delete mode 100644 src/main/java/repack/apache/commons/collections4/sequence/ReplacementsHandler.java delete mode 100644 src/main/java/repack/apache/commons/collections4/sequence/SequencesComparator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/sequence/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/AbstractNavigableSetDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/AbstractSerializableSetDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/AbstractSetDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/AbstractSortedSetDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/CompositeSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/ListOrderedSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/MapBackedSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/PredicatedNavigableSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/PredicatedSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/PredicatedSortedSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/TransformedNavigableSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/TransformedSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/TransformedSortedSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/UnmodifiableNavigableSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/UnmodifiableSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/UnmodifiableSortedSet.java delete mode 100644 src/main/java/repack/apache/commons/collections4/set/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/splitmap/AbstractIterableGetMapDecorator.java delete mode 100644 src/main/java/repack/apache/commons/collections4/splitmap/TransformedSplitMap.java delete mode 100644 src/main/java/repack/apache/commons/collections4/splitmap/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/trie/AbstractBitwiseTrie.java delete mode 100644 src/main/java/repack/apache/commons/collections4/trie/AbstractPatriciaTrie.java delete mode 100644 src/main/java/repack/apache/commons/collections4/trie/KeyAnalyzer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/trie/PatriciaTrie.java delete mode 100644 src/main/java/repack/apache/commons/collections4/trie/UnmodifiableTrie.java delete mode 100644 src/main/java/repack/apache/commons/collections4/trie/analyzer/StringKeyAnalyzer.java delete mode 100644 src/main/java/repack/apache/commons/collections4/trie/analyzer/package-info.java delete mode 100644 src/main/java/repack/apache/commons/collections4/trie/package-info.java diff --git a/build.gradle b/build.gradle index 5a1d03678c..8127d9874a 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,6 @@ plugins { id 'dev.architectury.loom' version '0.10.0-SNAPSHOT' + id 'com.github.johnrengelman.shadow' version '7.1.2' id 'maven-publish' } @@ -47,22 +48,24 @@ repositories { } } -configurations { - toJar -} - dependencies { minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings loom.officialMojangMappings() forge "net.minecraftforge:forge:${minecraft_version}-${forge_version}" - compileOnly "org.apache.ant:ant:1.8.2" modCompileOnly "maven.modrinth:rubidium:0.2.13" //modCompileOnly "me.jellysquid.mods:Rubidium:0.2.13" modCompileOnly "curse.maven:epic-fight-mod-405076:4029362" - implementation fileTree(include: ['*.jar'], dir: 'libs') - toJar fileTree(include: ['antlr4-runtime-4.10.1.jar', 'glsl-transformer-1.0.0-pre21.2.jar'], dir: 'libs') + modRuntimeOnly "curse.maven:lazydfu-460819:3249059" + + implementation(shadow(project(path: ":glsl-relocated", configuration: "bundledJar"))) { + transitive = false + } + implementation(shadow("org.anarres:jcpp:1.4.14")) { + transitive = false + } + shadow("org.slf4j:slf4j-api:1.7.12") // for jcpp } processResources { @@ -86,8 +89,27 @@ java { withSourcesJar() } -jar { - from { configurations.toJar.collect { it.isDirectory() ? it : zipTree(it) } } +shadowJar { + configurations = [project.configurations.shadow] + + from jar.archiveFile + + relocate 'org.apache.commons.collections4', 'oculus.org.apache.commons.collections4' + relocate 'org.anarres.cpp', 'oculus.org.anarres.cpp' + relocate 'org.slf4j', 'oculus.org.slf4j' + + archiveClassifier.set "shadow" + + manifest { + attributes( + 'Main-Class': 'net.coderbot.iris.LaunchWarn' + ) + } +} + +remapJar { + input.set shadowJar.archiveFile + dependsOn shadowJar } publishing { diff --git a/glsl-relocated/build.gradle b/glsl-relocated/build.gradle new file mode 100644 index 0000000000..694f5ce974 --- /dev/null +++ b/glsl-relocated/build.gradle @@ -0,0 +1,42 @@ +plugins { + id 'java-library' + id 'com.github.johnrengelman.shadow' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation(shadow("io.github.douira:glsl-transformer:1.0.1")) { + exclude module: "antlr4" // we only want to shadow the runtime module + } + implementation shadow("org.antlr:antlr4-runtime:4.10.1") +} + +shadowJar { + configurations = [project.configurations.shadow] + + from jar.archiveFile + + relocate 'org.antlr', 'oculus.org.antlr' + + archiveClassifier.set "shadow" +} + + + +configurations { + bundledJar { + canBeConsumed = true + canBeResolved = false + // If you want this configuration to share the same dependencies, otherwise omit this line + extendsFrom implementation, runtimeOnly + } +} + + + +artifacts { + bundledJar(shadowJar) +} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index f825d35668..791921254c 100644 --- a/settings.gradle +++ b/settings.gradle @@ -9,3 +9,5 @@ pluginManagement { gradlePluginPortal() } } + +include("glsl-relocated") \ No newline at end of file diff --git a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java index fa2b7c9951..aa1dfb6043 100644 --- a/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java +++ b/src/main/java/net/coderbot/iris/pipeline/transform/TransformPatcher.java @@ -6,8 +6,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.antlr.v4.runtime.RecognitionException; -import org.antlr.v4.runtime.Token; +import oculus.org.antlr.v4.runtime.RecognitionException; +import oculus.org.antlr.v4.runtime.Token; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/src/main/java/org/anarres/cpp/Argument.java b/src/main/java/org/anarres/cpp/Argument.java deleted file mode 100644 index f574dcd1a5..0000000000 --- a/src/main/java/org/anarres/cpp/Argument.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.annotation.Nonnull; - -/** - * A macro argument. - * - * This encapsulates a raw and preprocessed token stream. - */ -/* pp */ class Argument extends ArrayList { - - private List expansion; - - public Argument() { - this.expansion = null; - } - - public void addToken(@Nonnull Token tok) { - add(tok); - } - - /* pp */ void expand(@Nonnull Preprocessor p) - throws IOException, - LexerException { - /* Cache expansion. */ - if (expansion == null) { - this.expansion = p.expand(this); - // System.out.println("Expanded arg " + this); - } - } - - @Nonnull - public Iterator expansion() { - return expansion.iterator(); - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("Argument("); - // buf.append(super.toString()); - buf.append("raw=[ "); - for (int i = 0; i < size(); i++) - buf.append(get(i).getText()); - buf.append(" ];expansion=[ "); - if (expansion == null) - buf.append("null"); - else - for (Token token : expansion) - buf.append(token.getText()); - buf.append(" ])"); - return buf.toString(); - } - -} diff --git a/src/main/java/org/anarres/cpp/ChrootFileSystem.java b/src/main/java/org/anarres/cpp/ChrootFileSystem.java deleted file mode 100644 index 5abf2f86fe..0000000000 --- a/src/main/java/org/anarres/cpp/ChrootFileSystem.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.io.File; -import java.io.IOException; - -/** - * A virtual filesystem implementation using java.io in a virtual - * chroot. - */ -public class ChrootFileSystem implements VirtualFileSystem { - - private File root; - - public ChrootFileSystem(File root) { - this.root = root; - } - - @Override - public VirtualFile getFile(String path) { - return new ChrootFile(path); - } - - @Override - public VirtualFile getFile(String dir, String name) { - return new ChrootFile(dir, name); - } - - private class ChrootFile extends File implements VirtualFile { - - private File rfile; - - public ChrootFile(String path) { - super(path); - } - - public ChrootFile(String dir, String name) { - super(dir, name); - } - - /* private */ - public ChrootFile(File dir, String name) { - super(dir, name); - } - - @Override - public ChrootFile getParentFile() { - return new ChrootFile(getParent()); - } - - @Override - public ChrootFile getChildFile(String name) { - return new ChrootFile(this, name); - } - - @Override - public boolean isFile() { - File real = new File(root, getPath()); - return real.isFile(); - } - - @Override - public Source getSource() throws IOException { - return new FileLexerSource(new File(root, getPath()), - getPath()); - } - } - -} diff --git a/src/main/java/org/anarres/cpp/CppReader.java b/src/main/java/org/anarres/cpp/CppReader.java deleted file mode 100644 index 04bc8e899f..0000000000 --- a/src/main/java/org/anarres/cpp/CppReader.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import static org.anarres.cpp.Token.CCOMMENT; -import static org.anarres.cpp.Token.CPPCOMMENT; -import static org.anarres.cpp.Token.EOF; - -import java.io.Closeable; -import java.io.IOException; -import java.io.Reader; - -import javax.annotation.Nonnull; - -/** - * A Reader wrapper around the Preprocessor. - * - * This is a utility class to provide a transparent {@link Reader} - * which preprocesses the input text. - * - * @see Preprocessor - * @see Reader - */ -public class CppReader extends Reader implements Closeable { - - private final Preprocessor cpp; - private String token; - private int idx; - - public CppReader(@Nonnull final Reader r) { - cpp = new Preprocessor(new LexerSource(r, true) { - @Override - public String getName() { - return ""; - } - }); - token = ""; - idx = 0; - } - - public CppReader(@Nonnull Preprocessor p) { - cpp = p; - token = ""; - idx = 0; - } - - /** - * Returns the Preprocessor used by this CppReader. - */ - @Nonnull - public Preprocessor getPreprocessor() { - return cpp; - } - - /** - * Defines the given name as a macro. - * - * This is a convnience method. - */ - public void addMacro(@Nonnull String name) - throws LexerException { - cpp.addMacro(name); - } - - /** - * Defines the given name as a macro. - * - * This is a convnience method. - */ - public void addMacro(@Nonnull String name, @Nonnull String value) - throws LexerException { - cpp.addMacro(name, value); - } - - private boolean refill() - throws IOException { - try { - assert cpp != null : "cpp is null : was it closed?"; - if (token == null) - return false; - while (idx >= token.length()) { - Token tok = cpp.token(); - switch (tok.getType()) { - case EOF: - token = null; - return false; - case CCOMMENT: - case CPPCOMMENT: - if (!cpp.getFeature(Feature.KEEPCOMMENTS)) { - token = " "; - break; - } - default: - token = tok.getText(); - break; - } - idx = 0; - } - return true; - } catch (LexerException e) { - // new IOException(String, Throwable) is since 1.6 - IOException _e = new IOException(String.valueOf(e)); - _e.initCause(e); - throw _e; - } - } - - @Override - public int read() - throws IOException { - if (!refill()) - return -1; - return token.charAt(idx++); - } - - @Override - /* XXX Very slow and inefficient. */ - public int read(char cbuf[], int off, int len) - throws IOException { - if (token == null) - return -1; - for (int i = 0; i < len; i++) { - int ch = read(); - if (ch == -1) - return i; - cbuf[off + i] = (char) ch; - } - return len; - } - - @Override - public void close() - throws IOException { - cpp.close(); - token = null; - } - -} diff --git a/src/main/java/org/anarres/cpp/CppTask.java b/src/main/java/org/anarres/cpp/CppTask.java deleted file mode 100644 index 9874cdf847..0000000000 --- a/src/main/java/org/anarres/cpp/CppTask.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.List; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.taskdefs.Copy; -import org.apache.tools.ant.types.Path; -/** - * An ant task for jcpp. - */ -public class CppTask extends Copy { - - private class Listener extends DefaultPreprocessorListener { - - @Override - protected void print(String msg) { - log(msg); - } - } - - public static class Macro { - - private String name; - private String value; - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setValue(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - } - - private final Listener listener = new Listener(); - private final List macros = new ArrayList(); - private Path systemincludepath; - private Path localincludepath; - - public void addMacro(Macro macro) { - macros.add(macro); - } - - public void addSystemincludepath(Path path) { - if (systemincludepath == null) - systemincludepath = new Path(getProject()); - systemincludepath.add(path); - } - - public void addLocalincludepath(Path path) { - if (localincludepath == null) - localincludepath = new Path(getProject()); - localincludepath.add(path); - } - - /* - public void execute() { - FileWriter writer = null; - try { - if (input == null) - throw new BuildException("Input not specified"); - if (output == null) - throw new BuildException("Output not specified"); - cpp.addInput(this.input); - writer = new FileWriter(this.output); - for (;;) { - Token tok = cpp.token(); - if (tok != null && tok.getType() == Token.EOF) - break; - writer.write(tok.getText()); - } - } - catch (Exception e) { - throw new BuildException(e); - } - finally { - if (writer != null) { - try { - writer.close(); - } - catch (IOException e) { - } - } - } - } - */ - private void preprocess(File input, File output) throws Exception { - if (input == null) - throw new BuildException("Input not specified"); - if (output == null) - throw new BuildException("Output not specified"); - - Preprocessor cpp = new Preprocessor(); - cpp.setListener(listener); - for (Macro macro : macros) - cpp.addMacro(macro.getName(), macro.getValue()); - if (systemincludepath != null) - cpp.setSystemIncludePath(Arrays.asList(systemincludepath.list())); - if (localincludepath != null) - cpp.setQuoteIncludePath(Arrays.asList(localincludepath.list())); - - File dir = output.getParentFile(); - if (!dir.exists()) { - if (!dir.mkdirs()) - throw new BuildException("Failed to make parent directory " + dir); - } else if (!dir.isDirectory()) { - throw new BuildException("Parent directory of output file " + output + " exists, but is not a directory."); - } - FileWriter writer = null; - try { - cpp.addInput(input); - writer = new FileWriter(output); - for (;;) { - Token tok = cpp.token(); - if (tok == null) - break; - if (tok.getType() == Token.EOF) - break; - writer.write(tok.getText()); - } - } finally { - if (writer != null) { - try { - writer.close(); - } catch (IOException e) { - } - } - } - } - - @Override - protected void doFileOperations() { - if (fileCopyMap.size() > 0) { - log("Copying " + fileCopyMap.size() - + " file" + (fileCopyMap.size() == 1 ? "" : "s") - + " to " + destDir.getAbsolutePath()); - - Enumeration e = fileCopyMap.keys(); - - while (e.hasMoreElements()) { - String fromFile = e.nextElement(); - String[] toFiles = (String[]) fileCopyMap.get(fromFile); - - for (String toFile : toFiles) { - if (fromFile.equals(toFile)) { - log("Skipping self-copy of " + fromFile, verbosity); - continue; - } - - try { - log("Copying " + fromFile + " to " + toFile, verbosity); - - /* - FilterSetCollection executionFilters - = new FilterSetCollection(); - if (filtering) { - executionFilters - .addFilterSet(getProject().getGlobalFilterSet()); - } - for (Enumeration filterEnum = getFilterSets().elements(); - filterEnum.hasMoreElements();) { - executionFilters - .addFilterSet((FilterSet) filterEnum.nextElement()); - } - */ - File srcFile = new File(fromFile); - File dstFile = new File(toFile); - preprocess(srcFile, dstFile); - } catch (Exception ioe) { - // ioe.printStackTrace(); - String msg = "Failed to copy " + fromFile + " to " + toFile - + " due to " + ioe.getMessage(); - File targetFile = new File(toFile); - if (targetFile.exists() && !targetFile.delete()) { - msg += " and I couldn't delete the corrupt " + toFile; - } - throw new BuildException(msg, ioe, getLocation()); - } - } - } - } - - } - -} diff --git a/src/main/java/org/anarres/cpp/DefaultPreprocessorListener.java b/src/main/java/org/anarres/cpp/DefaultPreprocessorListener.java deleted file mode 100644 index b86e09205a..0000000000 --- a/src/main/java/org/anarres/cpp/DefaultPreprocessorListener.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.anarres.cpp; - -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * A handler for preprocessor events, primarily errors and warnings. - * - * If no PreprocessorListener is installed in a Preprocessor, all - * error and warning events will throw an exception. Installing a - * listener allows more intelligent handling of these events. - */ -public class DefaultPreprocessorListener implements PreprocessorListener { - - private static final Logger LOG = LogManager.getLogger(DefaultPreprocessorListener.class); - - private int errors; - private int warnings; - - public DefaultPreprocessorListener() { - clear(); - } - - public void clear() { - errors = 0; - warnings = 0; - } - - @Nonnegative - public int getErrors() { - return errors; - } - - @Nonnegative - public int getWarnings() { - return warnings; - } - - protected void print(@Nonnull String msg) { - LOG.info(msg); - } - - /** - * Handles a warning. - * - * The behaviour of this method is defined by the - * implementation. It may simply record the error message, or - * it may throw an exception. - */ - @Override - public void handleWarning(Source source, int line, int column, - String msg) - throws LexerException { - warnings++; - print(source.getName() + ":" + line + ":" + column - + ": warning: " + msg); - } - - /** - * Handles an error. - * - * The behaviour of this method is defined by the - * implementation. It may simply record the error message, or - * it may throw an exception. - */ - @Override - public void handleError(Source source, int line, int column, - String msg) - throws LexerException { - errors++; - print(source.getName() + ":" + line + ":" + column - + ": error: " + msg); - } - - @Override - public void handleSourceChange(Source source, SourceChangeEvent event) { - } - -} diff --git a/src/main/java/org/anarres/cpp/Feature.java b/src/main/java/org/anarres/cpp/Feature.java deleted file mode 100644 index a514269673..0000000000 --- a/src/main/java/org/anarres/cpp/Feature.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -/** - * Features of the Preprocessor, which may be enabled or disabled. - */ -public enum Feature { - - /** Supports ANSI digraphs. */ - DIGRAPHS, - /** Supports ANSI trigraphs. */ - TRIGRAPHS, - /** Outputs linemarker tokens. */ - LINEMARKERS, - /** Reports tokens of type INVALID as errors. */ - CSYNTAX, - /** Preserves comments in the lexed output. Like cpp -C */ - KEEPCOMMENTS, - /** Preserves comments in the lexed output, even when inactive. */ - KEEPALLCOMMENTS, - DEBUG, - /** Supports lexing of objective-C. */ - OBJCSYNTAX, - INCLUDENEXT, - /** Random extensions. */ - PRAGMA_ONCE -} diff --git a/src/main/java/org/anarres/cpp/FileLexerSource.java b/src/main/java/org/anarres/cpp/FileLexerSource.java deleted file mode 100644 index 15b718e226..0000000000 --- a/src/main/java/org/anarres/cpp/FileLexerSource.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.charset.Charset; - -import javax.annotation.Nonnull; - -/** - * A {@link Source} which lexes a file. - * - * The input is buffered. - * - * @see Source - */ -public class FileLexerSource extends InputLexerSource { - - private final String path; - private final File file; - - /** - * Creates a new Source for lexing the given File. - * - * Preprocessor directives are honoured within the file. - */ - public FileLexerSource(@Nonnull File file, @Nonnull Charset charset, @Nonnull String path) - throws IOException { - super(new FileInputStream(file), charset); - this.file = file; - this.path = path; - } - - public FileLexerSource(@Nonnull File file, @Nonnull String path) - throws IOException { - this(file, Charset.defaultCharset(), path); - } - - public FileLexerSource(@Nonnull File file, @Nonnull Charset charset) - throws IOException { - this(file, charset, file.getPath()); - } - - @Deprecated - public FileLexerSource(@Nonnull File file) - throws IOException { - this(file, Charset.defaultCharset()); - } - - public FileLexerSource(@Nonnull String path, @Nonnull Charset charset) - throws IOException { - this(new File(path), charset, path); - } - - @Deprecated - public FileLexerSource(@Nonnull String path) - throws IOException { - this(path, Charset.defaultCharset()); - } - - @Nonnull - public File getFile() { - return file; - } - - /** - * This is not necessarily the same as getFile().getPath() in case we are in a chroot. - */ - @Override - public String getPath() { - return path; - } - - @Override - public String getName() { - return getPath(); - } - - @Override - public String toString() { - return "file " + getPath(); - } -} diff --git a/src/main/java/org/anarres/cpp/FixedTokenSource.java b/src/main/java/org/anarres/cpp/FixedTokenSource.java deleted file mode 100644 index fdfd3284f0..0000000000 --- a/src/main/java/org/anarres/cpp/FixedTokenSource.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -/* pp */ class FixedTokenSource extends Source { - - private static final Token EOF - = new Token(Token.EOF, ""); - - private final List tokens; - private int idx; - - /* pp */ FixedTokenSource(Token... tokens) { - this.tokens = Arrays.asList(tokens); - this.idx = 0; - } - - /* pp */ FixedTokenSource(List tokens) { - this.tokens = tokens; - this.idx = 0; - } - - @Override - public Token token() - throws IOException, - LexerException { - if (idx >= tokens.size()) - return EOF; - return tokens.get(idx++); - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("constant token stream ").append(tokens); - Source parent = getParent(); - if (parent != null) - buf.append(" in ").append(String.valueOf(parent)); - return buf.toString(); - } -} diff --git a/src/main/java/org/anarres/cpp/InputLexerSource.java b/src/main/java/org/anarres/cpp/InputLexerSource.java deleted file mode 100644 index 559b294dce..0000000000 --- a/src/main/java/org/anarres/cpp/InputLexerSource.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.charset.Charset; - -import javax.annotation.Nonnull; - -/** - * A {@link Source} which lexes an {@link InputStream}. - * - * The input is buffered. - * - * @see Source - */ -public class InputLexerSource extends LexerSource { - - @Deprecated - public InputLexerSource(@Nonnull InputStream input) { - this(input, Charset.defaultCharset()); - } - - /** - * Creates a new Source for lexing the given Reader. - * - * Preprocessor directives are honoured within the file. - */ - public InputLexerSource(@Nonnull InputStream input, Charset charset) { - this(new InputStreamReader(input, charset)); - } - - public InputLexerSource(@Nonnull Reader input, boolean ppvalid) { - super(input, true); - } - - public InputLexerSource(@Nonnull Reader input) { - this(input, true); - } - - @Override - public String getPath() { - return ""; - } - - @Override - public String getName() { - return "standard input"; - } - - @Override - public String toString() { - return String.valueOf(getPath()); - } -} diff --git a/src/main/java/org/anarres/cpp/InternalException.java b/src/main/java/org/anarres/cpp/InternalException.java deleted file mode 100644 index e3a7a6efa4..0000000000 --- a/src/main/java/org/anarres/cpp/InternalException.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -/** - * An internal exception. - * - * This exception is thrown when an internal state violation is - * encountered. This should never happen. If it ever happens, please - * report it as a bug. - */ -public class InternalException extends RuntimeException { - - public InternalException(String msg) { - super(msg); - } -} diff --git a/src/main/java/org/anarres/cpp/JavaFileSystem.java b/src/main/java/org/anarres/cpp/JavaFileSystem.java deleted file mode 100644 index 39ae72c492..0000000000 --- a/src/main/java/org/anarres/cpp/JavaFileSystem.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.io.File; -import java.io.IOException; - -/** - * A virtual filesystem implementation using java.io. - */ -public class JavaFileSystem implements VirtualFileSystem { - - @Override - public VirtualFile getFile(String path) { - return new JavaFile(path); - } - - @Override - public VirtualFile getFile(String dir, String name) { - return new JavaFile(dir, name); - } - - private class JavaFile extends File implements VirtualFile { - - public JavaFile(String path) { - super(path); - } - - public JavaFile(String dir, String name) { - super(dir, name); - } - - /* private */ - public JavaFile(File dir, String name) { - super(dir, name); - } - - /* - @Override - public String getPath() { - return getCanonicalPath(); - } - */ - @Override - public JavaFile getParentFile() { - String parent = getParent(); - if (parent != null) - return new JavaFile(parent); - File absolute = getAbsoluteFile(); - parent = absolute.getParent(); - /* - if (parent == null) - return null; - */ - return new JavaFile(parent); - } - - @Override - public JavaFile getChildFile(String name) { - return new JavaFile(this, name); - } - - @Override - public Source getSource() throws IOException { - return new FileLexerSource(this); - } - - } - -} diff --git a/src/main/java/org/anarres/cpp/JoinReader.java b/src/main/java/org/anarres/cpp/JoinReader.java deleted file mode 100644 index 5ce08ea5d1..0000000000 --- a/src/main/java/org/anarres/cpp/JoinReader.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.io.Closeable; -import java.io.IOException; -import java.io.Reader; - -/* pp */ class JoinReader /* extends Reader */ implements Closeable { - - private final Reader in; - - private PreprocessorListener listener; - private LexerSource source; - private boolean trigraphs; - private boolean warnings; - - private int newlines; - private boolean flushnl; - private int[] unget; - private int uptr; - - public JoinReader(Reader in, boolean trigraphs) { - this.in = in; - this.trigraphs = trigraphs; - this.newlines = 0; - this.flushnl = false; - this.unget = new int[2]; - this.uptr = 0; - } - - public JoinReader(Reader in) { - this(in, false); - } - - public void setTrigraphs(boolean enable, boolean warnings) { - this.trigraphs = enable; - this.warnings = warnings; - } - - /* pp */ void init(Preprocessor pp, LexerSource s) { - this.listener = pp.getListener(); - this.source = s; - setTrigraphs(pp.getFeature(Feature.TRIGRAPHS), - pp.getWarning(Warning.TRIGRAPHS)); - } - - private int __read() throws IOException { - if (uptr > 0) - return unget[--uptr]; - return in.read(); - } - - private void _unread(int c) { - if (c != -1) - unget[uptr++] = c; - assert uptr <= unget.length : - "JoinReader ungets too many characters"; - } - - protected void warning(String msg) - throws LexerException { - if (source != null) - source.warning(msg); - else - throw new LexerException(msg); - } - - private char trigraph(char raw, char repl) - throws IOException, LexerException { - if (trigraphs) { - if (warnings) - warning("trigraph ??" + raw + " converted to " + repl); - return repl; - } else { - if (warnings) - warning("trigraph ??" + raw + " ignored"); - _unread(raw); - _unread('?'); - return '?'; - } - } - - private int _read() - throws IOException, LexerException { - int c = __read(); - if (c == '?' && (trigraphs || warnings)) { - int d = __read(); - if (d == '?') { - int e = __read(); - switch (e) { - case '(': - return trigraph('(', '['); - case ')': - return trigraph(')', ']'); - case '<': - return trigraph('<', '{'); - case '>': - return trigraph('>', '}'); - case '=': - return trigraph('=', '#'); - case '/': - return trigraph('/', '\\'); - case '\'': - return trigraph('\'', '^'); - case '!': - return trigraph('!', '|'); - case '-': - return trigraph('-', '~'); - } - _unread(e); - } - _unread(d); - } - return c; - } - - public int read() - throws IOException, LexerException { - if (flushnl) { - if (newlines > 0) { - newlines--; - return '\n'; - } - flushnl = false; - } - - for (;;) { - int c = _read(); - switch (c) { - case '\\': - int d = _read(); - switch (d) { - case '\n': - newlines++; - continue; - case '\r': - newlines++; - int e = _read(); - if (e != '\n') - _unread(e); - continue; - default: - _unread(d); - return c; - } - case '\r': - case '\n': - case '\u2028': - case '\u2029': - case '\u000B': - case '\u000C': - case '\u0085': - flushnl = true; - return c; - case -1: - if (newlines > 0) { - newlines--; - return '\n'; - } - default: - return c; - } - } - } - - public int read(char cbuf[], int off, int len) - throws IOException, LexerException { - for (int i = 0; i < len; i++) { - int ch = read(); - if (ch == -1) - return i; - cbuf[off + i] = (char) ch; - } - return len; - } - - @Override - public void close() - throws IOException { - in.close(); - } - - @Override - public String toString() { - return "JoinReader(nl=" + newlines + ")"; - } - - /* - public static void main(String[] args) throws IOException { - FileReader f = new FileReader(new File(args[0])); - BufferedReader b = new BufferedReader(f); - JoinReader r = new JoinReader(b); - BufferedWriter w = new BufferedWriter( - new java.io.OutputStreamWriter(System.out) - ); - int c; - while ((c = r.read()) != -1) { - w.write((char)c); - } - w.close(); - } - */ -} diff --git a/src/main/java/org/anarres/cpp/LexerException.java b/src/main/java/org/anarres/cpp/LexerException.java deleted file mode 100644 index b5a18006dd..0000000000 --- a/src/main/java/org/anarres/cpp/LexerException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -/** - * A preprocessor exception. - * - * Note to users: I don't really like the name of this class. S. - */ -public class LexerException extends Exception { - - public LexerException(String msg) { - super(msg); - } - - public LexerException(Throwable cause) { - super(cause); - } -} diff --git a/src/main/java/org/anarres/cpp/LexerSource.java b/src/main/java/org/anarres/cpp/LexerSource.java deleted file mode 100644 index 8091c6b347..0000000000 --- a/src/main/java/org/anarres/cpp/LexerSource.java +++ /dev/null @@ -1,1060 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import static org.anarres.cpp.Token.AND_EQ; -import static org.anarres.cpp.Token.ARROW; -import static org.anarres.cpp.Token.CCOMMENT; -import static org.anarres.cpp.Token.CHARACTER; -import static org.anarres.cpp.Token.CPPCOMMENT; -import static org.anarres.cpp.Token.DEC; -import static org.anarres.cpp.Token.DIV_EQ; -import static org.anarres.cpp.Token.ELLIPSIS; -import static org.anarres.cpp.Token.EOF; -import static org.anarres.cpp.Token.EQ; -import static org.anarres.cpp.Token.GE; -import static org.anarres.cpp.Token.HASH; -import static org.anarres.cpp.Token.HEADER; -import static org.anarres.cpp.Token.IDENTIFIER; -import static org.anarres.cpp.Token.INC; -import static org.anarres.cpp.Token.INVALID; -import static org.anarres.cpp.Token.LAND; -import static org.anarres.cpp.Token.LAND_EQ; -import static org.anarres.cpp.Token.LE; -import static org.anarres.cpp.Token.LOR; -import static org.anarres.cpp.Token.LOR_EQ; -import static org.anarres.cpp.Token.LSH; -import static org.anarres.cpp.Token.LSH_EQ; -import static org.anarres.cpp.Token.MOD_EQ; -import static org.anarres.cpp.Token.MULT_EQ; -import static org.anarres.cpp.Token.NE; -import static org.anarres.cpp.Token.NL; -import static org.anarres.cpp.Token.NUMBER; -import static org.anarres.cpp.Token.OR_EQ; -import static org.anarres.cpp.Token.PASTE; -import static org.anarres.cpp.Token.PLUS_EQ; -import static org.anarres.cpp.Token.RANGE; -import static org.anarres.cpp.Token.RSH; -import static org.anarres.cpp.Token.RSH_EQ; -import static org.anarres.cpp.Token.SQSTRING; -import static org.anarres.cpp.Token.STRING; -import static org.anarres.cpp.Token.SUB_EQ; -import static org.anarres.cpp.Token.WHITESPACE; -import static org.anarres.cpp.Token.XOR_EQ; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; - -import javax.annotation.Nonnull; - -/** Does not handle digraphs. */ -public class LexerSource extends Source { - - @Nonnull - protected static BufferedReader toBufferedReader(@Nonnull Reader r) { - if (r instanceof BufferedReader) - return (BufferedReader) r; - return new BufferedReader(r); - } - - private static final boolean DEBUG = false; - - private JoinReader reader; - private final boolean ppvalid; - private boolean bol; - private boolean include; - - private boolean digraphs; - - /* Unread. */ - private int u0, u1; - private int ucount; - - private int line; - private int column; - private int lastcolumn; - private boolean cr; - - /* ppvalid is: - * false in StringLexerSource, - * true in FileLexerSource */ - public LexerSource(Reader r, boolean ppvalid) { - this.reader = new JoinReader(r); - this.ppvalid = ppvalid; - this.bol = true; - this.include = false; - - this.digraphs = true; - - this.ucount = 0; - - this.line = 1; - this.column = 0; - this.lastcolumn = -1; - this.cr = false; - } - - @Override - /* pp */ void init(Preprocessor pp) { - super.init(pp); - this.digraphs = pp.getFeature(Feature.DIGRAPHS); - this.reader.init(pp, this); - } - - /** - * Returns the line number of the last read character in this source. - * - * Lines are numbered from 1. - * - * @return the line number of the last read character in this source. - */ - @Override - public int getLine() { - return line; - } - - /** - * Returns the column number of the last read character in this source. - * - * Columns are numbered from 0. - * - * @return the column number of the last read character in this source. - */ - @Override - public int getColumn() { - return column; - } - - @Override - /* pp */ boolean isNumbered() { - return true; - } - - /* Error handling. */ - private void _error(String msg, boolean error) - throws LexerException { - int _l = line; - int _c = column; - if (_c == 0) { - _c = lastcolumn; - _l--; - } else { - _c--; - } - if (error) - super.error(_l, _c, msg); - else - super.warning(_l, _c, msg); - } - - /* Allow JoinReader to call this. */ - /* pp */ final void error(String msg) - throws LexerException { - _error(msg, true); - } - - /* Allow JoinReader to call this. */ - /* pp */ final void warning(String msg) - throws LexerException { - _error(msg, false); - } - - /* A flag for string handling. */ - - /* pp */ void setInclude(boolean b) { - this.include = b; - } - - /* - * private boolean _isLineSeparator(int c) { - * return Character.getType(c) == Character.LINE_SEPARATOR - * || c == -1; - * } - */ - - /* XXX Move to JoinReader and canonicalise newlines. */ - private static boolean isLineSeparator(int c) { - switch ((char) c) { - case '\r': - case '\n': - case '\u2028': - case '\u2029': - case '\u000B': - case '\u000C': - case '\u0085': - return true; - default: - return (c == -1); - } - } - - private int read() - throws IOException, - LexerException { - int c; - assert ucount <= 2 : "Illegal ucount: " + ucount; - switch (ucount) { - case 2: - ucount = 1; - c = u1; - break; - case 1: - ucount = 0; - c = u0; - break; - default: - if (reader == null) - c = -1; - else - c = reader.read(); - break; - } - - switch (c) { - case '\r': - cr = true; - line++; - lastcolumn = column; - column = 0; - break; - case '\n': - if (cr) { - cr = false; - break; - } - /* fallthrough */ - case '\u2028': - case '\u2029': - case '\u000B': - case '\u000C': - case '\u0085': - cr = false; - line++; - lastcolumn = column; - column = 0; - break; - case -1: - cr = false; - break; - default: - cr = false; - column++; - break; - } - - /* - * if (isLineSeparator(c)) { - * line++; - * lastcolumn = column; - * column = 0; - * } - * else { - * column++; - * } - */ - return c; - } - - /* You can unget AT MOST one newline. */ - private void unread(int c) - throws IOException { - /* XXX Must unread newlines. */ - if (c != -1) { - if (isLineSeparator(c)) { - line--; - column = lastcolumn; - cr = false; - } else { - column--; - } - switch (ucount) { - case 0: - u0 = c; - ucount = 1; - break; - case 1: - u1 = c; - ucount = 2; - break; - default: - throw new IllegalStateException( - "Cannot unget another character!" - ); - } - // reader.unread(c); - } - } - - /* Consumes the rest of the current line into an invalid. */ - @Nonnull - private Token invalid(StringBuilder text, String reason) - throws IOException, - LexerException { - int d = read(); - while (!isLineSeparator(d)) { - text.append((char) d); - d = read(); - } - unread(d); - return new Token(INVALID, text.toString(), reason); - } - - @Nonnull - private Token ccomment() - throws IOException, - LexerException { - StringBuilder text = new StringBuilder("/*"); - int d; - do { - do { - d = read(); - if (d == -1) - return new Token(INVALID, text.toString(), - "Unterminated comment"); - text.append((char) d); - } while (d != '*'); - do { - d = read(); - if (d == -1) - return new Token(INVALID, text.toString(), - "Unterminated comment"); - text.append((char) d); - } while (d == '*'); - } while (d != '/'); - return new Token(CCOMMENT, text.toString()); - } - - @Nonnull - private Token cppcomment() - throws IOException, - LexerException { - StringBuilder text = new StringBuilder("//"); - int d = read(); - while (!isLineSeparator(d)) { - text.append((char) d); - d = read(); - } - unread(d); - return new Token(CPPCOMMENT, text.toString()); - } - - /** - * Lexes an escaped character, appends the lexed escape sequence to 'text' and returns the parsed character value. - * - * @param text The buffer to which the literal escape sequence is appended. - * @return The new parsed character value. - * @throws IOException if it goes badly wrong. - * @throws LexerException if it goes wrong. - */ - private int escape(StringBuilder text) - throws IOException, - LexerException { - int d = read(); - switch (d) { - case 'a': - text.append('a'); - return 0x07; - case 'b': - text.append('b'); - return '\b'; - case 'f': - text.append('f'); - return '\f'; - case 'n': - text.append('n'); - return '\n'; - case 'r': - text.append('r'); - return '\r'; - case 't': - text.append('t'); - return '\t'; - case 'v': - text.append('v'); - return 0x0b; - case '\\': - text.append('\\'); - return '\\'; - - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - int len = 0; - int val = 0; - do { - val = (val << 3) + Character.digit(d, 8); - text.append((char) d); - d = read(); - } while (++len < 3 && Character.digit(d, 8) != -1); - unread(d); - return val; - - case 'x': - text.append((char) d); - len = 0; - val = 0; - while (len++ < 2) { - d = read(); - if (Character.digit(d, 16) == -1) { - unread(d); - break; - } - val = (val << 4) + Character.digit(d, 16); - text.append((char) d); - } - return val; - - /* Exclude two cases from the warning. */ - case '"': - text.append('"'); - return '"'; - case '\'': - text.append('\''); - return '\''; - - default: - warning("Unnecessary escape character " + (char) d); - text.append((char) d); - return d; - } - } - - @Nonnull - private Token character() - throws IOException, - LexerException { - StringBuilder text = new StringBuilder("'"); - int d = read(); - if (d == '\\') { - text.append('\\'); - d = escape(text); - } else if (isLineSeparator(d)) { - unread(d); - return new Token(INVALID, text.toString(), - "Unterminated character literal"); - } else if (d == '\'') { - text.append('\''); - return new Token(INVALID, text.toString(), - "Empty character literal"); - } else if (!Character.isDefined(d)) { - text.append('?'); - return invalid(text, "Illegal unicode character literal"); - } else { - text.append((char) d); - } - - int e = read(); - if (e != '\'') { - // error("Illegal character constant"); - /* We consume up to the next ' or the rest of the line. */ - for (;;) { - if (isLineSeparator(e)) { - unread(e); - break; - } - text.append((char) e); - if (e == '\'') - break; - e = read(); - } - return new Token(INVALID, text.toString(), - "Illegal character constant " + text); - } - text.append('\''); - /* XXX It this a bad cast? */ - return new Token(CHARACTER, - text.toString(), Character.valueOf((char) d)); - } - - @Nonnull - private Token string(char open, char close) - throws IOException, - LexerException { - StringBuilder text = new StringBuilder(); - text.append(open); - - StringBuilder buf = new StringBuilder(); - - for (;;) { - int c = read(); - if (c == close) { - break; - } else if (c == '\\') { - text.append('\\'); - if (!include) { - char d = (char) escape(text); - buf.append(d); - } - } else if (c == -1) { - unread(c); - // error("End of file in string literal after " + buf); - return new Token(INVALID, text.toString(), - "End of file in string literal after " + buf); - } else if (isLineSeparator(c)) { - unread(c); - // error("Unterminated string literal after " + buf); - return new Token(INVALID, text.toString(), - "Unterminated string literal after " + buf); - } else { - text.append((char) c); - buf.append((char) c); - } - } - text.append(close); - switch (close) { - case '"': - return new Token(STRING, - text.toString(), buf.toString()); - case '>': - return new Token(HEADER, - text.toString(), buf.toString()); - case '\'': - if (buf.length() == 1) - return new Token(CHARACTER, - text.toString(), buf.toString()); - return new Token(SQSTRING, - text.toString(), buf.toString()); - default: - throw new IllegalStateException( - "Unknown closing character " + String.valueOf(close)); - } - } - - @Nonnull - private Token _number_suffix(StringBuilder text, NumericValue value, int d) - throws IOException, - LexerException { - int flags = 0; // U, I, L, LL, F, D, MSB - for (;;) { - if (d == 'U' || d == 'u') { - if ((flags & NumericValue.F_UNSIGNED) != 0) - warning("Duplicate unsigned suffix " + d); - flags |= NumericValue.F_UNSIGNED; - text.append((char) d); - d = read(); - } else if (d == 'L' || d == 'l') { - if ((flags & NumericValue.FF_SIZE) != 0) - warning("Multiple length suffixes after " + text); - text.append((char) d); - int e = read(); - if (e == d) { // Case must match. Ll is Welsh. - flags |= NumericValue.F_LONGLONG; - text.append((char) e); - d = read(); - } else { - flags |= NumericValue.F_LONG; - d = e; - } - } else if (d == 'I' || d == 'i') { - if ((flags & NumericValue.FF_SIZE) != 0) - warning("Multiple length suffixes after " + text); - flags |= NumericValue.F_INT; - text.append((char) d); - d = read(); - } else if (d == 'F' || d == 'f') { - if ((flags & NumericValue.FF_SIZE) != 0) - warning("Multiple length suffixes after " + text); - flags |= NumericValue.F_FLOAT; - text.append((char) d); - d = read(); - } else if (d == 'D' || d == 'd') { - if ((flags & NumericValue.FF_SIZE) != 0) - warning("Multiple length suffixes after " + text); - flags |= NumericValue.F_DOUBLE; - text.append((char) d); - d = read(); - } else if (Character.isUnicodeIdentifierPart(d)) { - String reason = "Invalid suffix \"" + (char) d + "\" on numeric constant"; - // We've encountered something initially identified as a number. - // Read in the rest of this token as an identifer but return it as an invalid. - while (Character.isUnicodeIdentifierPart(d)) { - text.append((char) d); - d = read(); - } - unread(d); - return new Token(INVALID, text.toString(), reason); - } else { - unread(d); - value.setFlags(flags); - return new Token(NUMBER, - text.toString(), value); - } - } - } - - /* Either a decimal part, or a hex exponent. */ - @Nonnull - private String _number_part(StringBuilder text, int base, boolean sign) - throws IOException, - LexerException { - StringBuilder part = new StringBuilder(); - int d = read(); - if (sign && (d == '+' || d == '-')) { - text.append((char) d); - part.append((char) d); - d = read(); - } - while (Character.digit(d, base) != -1) { - text.append((char) d); - part.append((char) d); - d = read(); - } - unread(d); - return part.toString(); - } - - /* We do not know whether know the first digit is valid. */ - @Nonnull - private Token number_hex(char x) - throws IOException, - LexerException { - StringBuilder text = new StringBuilder("0"); - text.append(x); - String integer = _number_part(text, 16, false); - NumericValue value = new NumericValue(16, integer); - int d = read(); - if (d == '.') { - text.append((char) d); - String fraction = _number_part(text, 16, false); - value.setFractionalPart(fraction); - d = read(); - } - if (d == 'P' || d == 'p') { - text.append((char) d); - String exponent = _number_part(text, 10, true); - value.setExponent(2, exponent); - d = read(); - } - // XXX Make sure it's got enough parts - return _number_suffix(text, value, d); - } - - private static boolean is_octal(@Nonnull String text) { - if (!text.startsWith("0")) - return false; - for (int i = 0; i < text.length(); i++) - if (Character.digit(text.charAt(i), 8) == -1) - return false; - return true; - } - - /* We know we have at least one valid digit, but empty is not - * fine. */ - @Nonnull - private Token number_decimal() - throws IOException, - LexerException { - StringBuilder text = new StringBuilder(); - String integer = _number_part(text, 10, false); - String fraction = null; - String exponent = null; - int d = read(); - if (d == '.') { - text.append((char) d); - fraction = _number_part(text, 10, false); - d = read(); - } - if (d == 'E' || d == 'e') { - text.append((char) d); - exponent = _number_part(text, 10, true); - d = read(); - } - int base = 10; - if (fraction == null && exponent == null && integer.startsWith("0")) { - if (!is_octal(integer)) - warning("Decimal constant starts with 0, but not octal: " + integer); - else - base = 8; - } - NumericValue value = new NumericValue(base, integer); - if (fraction != null) - value.setFractionalPart(fraction); - if (exponent != null) - value.setExponent(10, exponent); - // XXX Make sure it's got enough parts - return _number_suffix(text, value, d); - } - - /** - * Section 6.4.4.1 of C99 - * - * (Not pasted here, but says that the initial negation is a separate token.) - * - * Section 6.4.4.2 of C99 - * - * A floating constant has a significand part that may be followed - * by an exponent part and a suffix that specifies its type. The - * components of the significand part may include a digit sequence - * representing the whole-number part, followed by a period (.), - * followed by a digit sequence representing the fraction part. - * - * The components of the exponent part are an e, E, p, or P - * followed by an exponent consisting of an optionally signed digit - * sequence. Either the whole-number part or the fraction part has to - * be present; for decimal floating constants, either the period or - * the exponent part has to be present. - * - * The significand part is interpreted as a (decimal or hexadecimal) - * rational number; the digit sequence in the exponent part is - * interpreted as a decimal integer. For decimal floating constants, - * the exponent indicates the power of 10 by which the significand - * part is to be scaled. For hexadecimal floating constants, the - * exponent indicates the power of 2 by which the significand part is - * to be scaled. - * - * For decimal floating constants, and also for hexadecimal - * floating constants when FLT_RADIX is not a power of 2, the result - * is either the nearest representable value, or the larger or smaller - * representable value immediately adjacent to the nearest representable - * value, chosen in an implementation-defined manner. For hexadecimal - * floating constants when FLT_RADIX is a power of 2, the result is - * correctly rounded. - */ - @Nonnull - private Token number() - throws IOException, - LexerException { - Token tok; - int c = read(); - if (c == '0') { - int d = read(); - if (d == 'x' || d == 'X') { - tok = number_hex((char) d); - } else { - unread(d); - unread(c); - tok = number_decimal(); - } - } else if (Character.isDigit(c) || c == '.') { - unread(c); - tok = number_decimal(); - } else { - throw new LexerException("Asked to parse something as a number which isn't: " + (char) c); - } - return tok; - } - - @Nonnull - private Token identifier(int c) - throws IOException, - LexerException { - StringBuilder text = new StringBuilder(); - int d; - text.append((char) c); - for (;;) { - d = read(); - if (Character.isIdentifierIgnorable(d)) - ; else if (Character.isJavaIdentifierPart(d)) - text.append((char) d); - else - break; - } - unread(d); - return new Token(IDENTIFIER, text.toString()); - } - - @Nonnull - private Token whitespace(int c) - throws IOException, - LexerException { - StringBuilder text = new StringBuilder(); - int d; - text.append((char) c); - for (;;) { - d = read(); - if (ppvalid && isLineSeparator(d)) /* XXX Ugly. */ - break; - if (Character.isWhitespace(d)) - text.append((char) d); - else - break; - } - unread(d); - return new Token(WHITESPACE, text.toString()); - } - - /* No token processed by cond() contains a newline. */ - @Nonnull - private Token cond(char c, int yes, int no) - throws IOException, - LexerException { - int d = read(); - if (c == d) - return new Token(yes); - unread(d); - return new Token(no); - } - - @Override - public Token token() - throws IOException, - LexerException { - Token tok = null; - - int _l = line; - int _c = column; - - int c = read(); - int d; - - switch (c) { - case '\n': - if (ppvalid) { - bol = true; - if (include) { - tok = new Token(NL, _l, _c, "\n"); - } else { - int nls = 0; - do { - nls++; - d = read(); - } while (d == '\n'); - unread(d); - char[] text = new char[nls]; - for (int i = 0; i < text.length; i++) - text[i] = '\n'; - // Skip the bol = false below. - tok = new Token(NL, _l, _c, new String(text)); - } - if (DEBUG) - System.out.println("lx: Returning NL: " + tok); - return tok; - } - /* Let it be handled as whitespace. */ - break; - - case '!': - tok = cond('=', NE, '!'); - break; - - case '#': - if (bol) - tok = new Token(HASH); - else - tok = cond('#', PASTE, '#'); - break; - - case '+': - d = read(); - if (d == '+') - tok = new Token(INC); - else if (d == '=') - tok = new Token(PLUS_EQ); - else - unread(d); - break; - case '-': - d = read(); - if (d == '-') - tok = new Token(DEC); - else if (d == '=') - tok = new Token(SUB_EQ); - else if (d == '>') - tok = new Token(ARROW); - else - unread(d); - break; - - case '*': - tok = cond('=', MULT_EQ, '*'); - break; - case '/': - d = read(); - if (d == '*') - tok = ccomment(); - else if (d == '/') - tok = cppcomment(); - else if (d == '=') - tok = new Token(DIV_EQ); - else - unread(d); - break; - - case '%': - d = read(); - if (d == '=') - tok = new Token(MOD_EQ); - else if (digraphs && d == '>') - tok = new Token('}'); // digraph - else if (digraphs && d == ':') - PASTE: - { - d = read(); - if (d != '%') { - unread(d); - tok = new Token('#'); // digraph - break PASTE; - } - d = read(); - if (d != ':') { - unread(d); // Unread 2 chars here. - unread('%'); - tok = new Token('#'); // digraph - break PASTE; - } - tok = new Token(PASTE); // digraph - } - else - unread(d); - break; - - case ':': - /* :: */ - d = read(); - if (digraphs && d == '>') - tok = new Token(']'); // digraph - else - unread(d); - break; - - case '<': - if (include) { - tok = string('<', '>'); - } else { - d = read(); - if (d == '=') - tok = new Token(LE); - else if (d == '<') - tok = cond('=', LSH_EQ, LSH); - else if (digraphs && d == ':') - tok = new Token('['); // digraph - else if (digraphs && d == '%') - tok = new Token('{'); // digraph - else - unread(d); - } - break; - - case '=': - tok = cond('=', EQ, '='); - break; - - case '>': - d = read(); - if (d == '=') - tok = new Token(GE); - else if (d == '>') - tok = cond('=', RSH_EQ, RSH); - else - unread(d); - break; - - case '^': - tok = cond('=', XOR_EQ, '^'); - break; - - case '|': - d = read(); - if (d == '=') - tok = new Token(OR_EQ); - else if (d == '|') - tok = cond('=', LOR_EQ, LOR); - else - unread(d); - break; - case '&': - d = read(); - if (d == '&') - tok = cond('=', LAND_EQ, LAND); - else if (d == '=') - tok = new Token(AND_EQ); - else - unread(d); - break; - - case '.': - d = read(); - if (d == '.') - tok = cond('.', ELLIPSIS, RANGE); - else - unread(d); - if (Character.isDigit(d)) { - unread('.'); - tok = number(); - } - /* XXX decimal fraction */ - break; - - case '\'': - tok = string('\'', '\''); - break; - - case '"': - tok = string('"', '"'); - break; - - case -1: - close(); - tok = new Token(EOF, _l, _c, ""); - break; - } - - if (tok == null) { - if (Character.isWhitespace(c)) { - tok = whitespace(c); - } else if (Character.isDigit(c)) { - unread(c); - tok = number(); - } else if (Character.isJavaIdentifierStart(c)) { - tok = identifier(c); - } else { - String text = TokenType.getTokenText(c); - if (text == null) { - if ((c >>> 16) == 0) // Character.isBmpCodePoint() is new in 1.7 - text = Character.toString((char) c); - else - text = new String(Character.toChars(c)); - } - tok = new Token(c, text); - } - } - - if (bol) { - switch (tok.getType()) { - case WHITESPACE: - case CCOMMENT: - break; - default: - bol = false; - break; - } - } - - tok.setLocation(_l, _c); - if (DEBUG) - System.out.println("lx: Returning " + tok); - // (new Exception("here")).printStackTrace(System.out); - return tok; - } - - @Override - public void close() - throws IOException { - if (reader != null) { - reader.close(); - reader = null; - } - super.close(); - } - -} diff --git a/src/main/java/org/anarres/cpp/Macro.java b/src/main/java/org/anarres/cpp/Macro.java deleted file mode 100644 index 62b0532267..0000000000 --- a/src/main/java/org/anarres/cpp/Macro.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * A macro object. - * - * This encapsulates a name, an argument count, and a token stream - * for replacement. The replacement token stream may contain the - * extra tokens {@link Token#M_ARG} and {@link Token#M_STRING}. - */ -public class Macro { - - private Source source; - private String name; - /* It's an explicit decision to keep these around here. We don't - * need to; the argument token type is M_ARG and the value - * is the index. The strings themselves are only used in - * stringification of the macro, for debugging. */ - private List args; - private boolean variadic; - private List tokens; - - public Macro(Source source, String name) { - this.source = source; - this.name = name; - this.args = null; - this.variadic = false; - this.tokens = new ArrayList(); - } - - public Macro(String name) { - this(null, name); - } - - /** - * Sets the Source from which this macro was parsed. - */ - public void setSource(Source s) { - this.source = s; - } - - /** - * Returns the Source from which this macro was parsed. - * - * This method may return null if the macro was not parsed - * from a regular file. - */ - public Source getSource() { - return source; - } - - /** - * Returns the name of this macro. - */ - public String getName() { - return name; - } - - /** - * Sets the arguments to this macro. - */ - public void setArgs(List args) { - this.args = args; - } - - /** - * Returns true if this is a function-like macro. - */ - public boolean isFunctionLike() { - return args != null; - } - - /** - * Returns the number of arguments to this macro. - */ - public int getArgs() { - return args.size(); - } - - /** - * Sets the variadic flag on this Macro. - */ - public void setVariadic(boolean b) { - this.variadic = b; - } - - /** - * Returns true if this is a variadic function-like macro. - */ - public boolean isVariadic() { - return variadic; - } - - /** - * Adds a token to the expansion of this macro. - */ - public void addToken(Token tok) { - this.tokens.add(tok); - } - - /** - * Adds a "paste" operator to the expansion of this macro. - * - * A paste operator causes the next token added to be pasted - * to the previous token when the macro is expanded. - * It is an error for a macro to end with a paste token. - */ - public void addPaste(Token tok) { - /* - * Given: tok0 ## tok1 - * We generate: M_PASTE, tok0, tok1 - * This extends as per a stack language: - * tok0 ## tok1 ## tok2 -> - * M_PASTE, tok0, M_PASTE, tok1, tok2 - */ - this.tokens.add(tokens.size() - 1, tok); - } - - /* pp */ List getTokens() { - return tokens; - } - - /* Paste tokens are inserted before the first of the two pasted - * tokens, so it's a kind of bytecode notation. This method - * swaps them around again. We know that there will never be two - * sequential paste tokens, so a boolean is sufficient. */ - public String getText() { - StringBuilder buf = new StringBuilder(); - boolean paste = false; - for (Token tok : tokens) { - if (tok.getType() == Token.M_PASTE) { - assert paste == false : "Two sequential pastes."; - paste = true; - continue; - } else { - buf.append(tok.getText()); - } - if (paste) { - buf.append(" #" + "# "); - paste = false; - } - // buf.append(tokens.get(i)); - } - return buf.toString(); - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(name); - if (args != null) { - buf.append('('); - Iterator it = args.iterator(); - while (it.hasNext()) { - buf.append(it.next()); - if (it.hasNext()) - buf.append(", "); - else if (isVariadic()) - buf.append("..."); - } - buf.append(')'); - } - if (!tokens.isEmpty()) { - buf.append(" => ").append(getText()); - } - return buf.toString(); - } - -} diff --git a/src/main/java/org/anarres/cpp/MacroTokenSource.java b/src/main/java/org/anarres/cpp/MacroTokenSource.java deleted file mode 100644 index bf81477528..0000000000 --- a/src/main/java/org/anarres/cpp/MacroTokenSource.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import static org.anarres.cpp.Token.CCOMMENT; -import static org.anarres.cpp.Token.CPPCOMMENT; -import static org.anarres.cpp.Token.EOF; -import static org.anarres.cpp.Token.M_ARG; -import static org.anarres.cpp.Token.M_PASTE; -import static org.anarres.cpp.Token.M_STRING; -import static org.anarres.cpp.Token.STRING; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/* This source should always be active, since we don't expand macros - * in any inactive context. */ -/* pp */ class MacroTokenSource extends Source { - - private static final Logger LOG = LogManager.getLogger(MacroTokenSource.class); - private final Macro macro; - private final Iterator tokens; /* Pointer into the macro. */ - - private final List args; /* { unexpanded, expanded } */ - - private Iterator arg; /* "current expansion" */ - - /* pp */ MacroTokenSource(@Nonnull Macro m, @Nonnull List args) { - this.macro = m; - this.tokens = m.getTokens().iterator(); - this.args = args; - this.arg = null; - } - - @Override - /* pp */ boolean isExpanding(@Nonnull Macro m) { - /* When we are expanding an arg, 'this' macro is not - * being expanded, and thus we may re-expand it. */ - if (/* XXX this.arg == null && */this.macro == m) - return true; - return super.isExpanding(m); - } - - /* XXX Called from Preprocessor [ugly]. */ - /* pp */ static void escape(@Nonnull StringBuilder buf, @Nonnull CharSequence cs) { - if (buf == null) - throw new NullPointerException("Buffer was null."); - if (cs == null) - throw new NullPointerException("CharSequence was null."); - for (int i = 0; i < cs.length(); i++) { - char c = cs.charAt(i); - switch (c) { - case '\\': - buf.append("\\\\"); - break; - case '"': - buf.append("\\\""); - break; - case '\n': - buf.append("\\n"); - break; - case '\r': - buf.append("\\r"); - break; - default: - buf.append(c); - } - } - } - - private void concat(@Nonnull StringBuilder buf, @Nonnull Argument arg) { - for (Token tok : arg) { - buf.append(tok.getText()); - } - } - - @Nonnull - private Token stringify(@Nonnull Token pos, @Nonnull Argument arg) { - StringBuilder buf = new StringBuilder(); - concat(buf, arg); - // System.out.println("Concat: " + arg + " -> " + buf); - StringBuilder str = new StringBuilder("\""); - escape(str, buf); - str.append("\""); - // System.out.println("Escape: " + buf + " -> " + str); - return new Token(STRING, - pos.getLine(), pos.getColumn(), - str.toString(), buf.toString()); - } - - /** - * Returns true if the given argumentIndex is the last argument of a variadic macro. - * - * @param argumentIndex The index of the argument to inspect. - * @return true if the given argumentIndex is the last argument of a variadic macro. - */ - private boolean isVariadicArgument(@Nonnegative int argumentIndex) { - if (!macro.isVariadic()) - return false; - return argumentIndex == args.size() - 1; - } - - /* At this point, we have consumed the first M_PASTE. - * @see Macro#addPaste(Token) */ - private void paste(@Nonnull Token ptok) - throws IOException, - LexerException { - // List out = new ArrayList(); - StringBuilder buf = new StringBuilder(); - // Token err = null; - /* We know here that arg is null or expired, - * since we cannot paste an expanded arg. */ - - int count = 2; - // While I hate auxiliary booleans, this does actually seem to be the simplest solution, - // as it avoids duplicating all the logic around hasNext() in case COMMA. - boolean comma = false; - TOKEN: - for (int i = 0; i < count; i++) { - if (!tokens.hasNext()) { - /* XXX This one really should throw. */ - error(ptok.getLine(), ptok.getColumn(), - "Paste at end of expansion"); - buf.append(' ').append(ptok.getText()); - break; - } - Token tok = tokens.next(); - // System.out.println("Paste " + tok); - switch (tok.getType()) { - case M_PASTE: - /* One extra to paste, plus one because the - * paste token didn't count. */ - count += 2; - ptok = tok; - break; - case M_ARG: - int idx = ((Integer) tok.getValue()).intValue(); - Argument arg = args.get(idx); - if (comma && isVariadicArgument(idx) && arg.isEmpty()) { - // Ugly way to strip the comma. - buf.setLength(buf.length() - 1); - } else { - concat(buf, arg); - } - break; - /* XXX Test this. */ - case CCOMMENT: - case CPPCOMMENT: - // TODO: In cpp, -CC keeps these comments too, - // but turns all C++ comments into C comments. - break; - case ',': - comma = true; - buf.append(tok.getText()); - continue TOKEN; - default: - buf.append(tok.getText()); - break; - } - comma = false; - } - - /* Push and re-lex. */ - /* - StringBuilder src = new StringBuilder(); - escape(src, buf); - StringLexerSource sl = new StringLexerSource(src.toString()); - */ - StringLexerSource sl = new StringLexerSource(buf.toString()); - - /* XXX Check that concatenation produces a valid token. */ - arg = new SourceIterator(sl); - } - - @Override - public Token token() - throws IOException, - LexerException { - for (;;) { - /* Deal with lexed tokens first. */ - - if (arg != null) { - if (arg.hasNext()) { - Token tok = arg.next(); - /* XXX PASTE -> INVALID. */ - assert tok.getType() != M_PASTE : - "Unexpected paste token"; - return tok; - } - arg = null; - } - - if (!tokens.hasNext()) - return new Token(EOF, -1, -1, ""); /* End of macro. */ - - Token tok = tokens.next(); - int idx; - switch (tok.getType()) { - case M_STRING: - /* Use the nonexpanded arg. */ - idx = ((Integer) tok.getValue()).intValue(); - return stringify(tok, args.get(idx)); - case M_ARG: - /* Expand the arg. */ - idx = ((Integer) tok.getValue()).intValue(); - // System.out.println("Pushing arg " + args.get(idx)); - arg = args.get(idx).expansion(); - break; - case M_PASTE: - paste(tok); - break; - default: - return tok; - } - } /* for */ - - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append("expansion of ").append(macro.getName()); - Source parent = getParent(); - if (parent != null) - buf.append(" in ").append(String.valueOf(parent)); - return buf.toString(); - } -} diff --git a/src/main/java/org/anarres/cpp/NumericValue.java b/src/main/java/org/anarres/cpp/NumericValue.java deleted file mode 100644 index dc4c277518..0000000000 --- a/src/main/java/org/anarres/cpp/NumericValue.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import javax.annotation.CheckForNull; -import javax.annotation.CheckForSigned; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; - -public class NumericValue extends Number { - - public static final int F_UNSIGNED = 1; - public static final int F_INT = 2; - public static final int F_LONG = 4; - public static final int F_LONGLONG = 8; - public static final int F_FLOAT = 16; - public static final int F_DOUBLE = 32; - - public static final int FF_SIZE = F_INT | F_LONG | F_LONGLONG | F_FLOAT | F_DOUBLE; - - private final int base; - private final String integer; - private String fraction; - private int expbase = 0; - private String exponent; - private int flags; - - public NumericValue(@Nonnegative int base, @Nonnull String integer) { - this.base = base; - this.integer = integer; - } - - @Nonnegative - public int getBase() { - return base; - } - - @Nonnull - public String getIntegerPart() { - return integer; - } - - @CheckForNull - public String getFractionalPart() { - return fraction; - } - - /* pp */ void setFractionalPart(@Nonnull String fraction) { - this.fraction = fraction; - } - - @CheckForSigned - public int getExponentBase() { - return expbase; - } - - @CheckForNull - public String getExponent() { - return exponent; - } - - /* pp */ void setExponent(@Nonnegative int expbase, @Nonnull String exponent) { - this.expbase = expbase; - this.exponent = exponent; - } - - public int getFlags() { - return flags; - } - - /* pp */ void setFlags(int flags) { - this.flags = flags; - } - - /** - * So, it turns out that parsing arbitrary bases into arbitrary - * precision numbers is nontrivial, and this routine gets it wrong - * in many important cases. - */ - @Nonnull - public BigDecimal toBigDecimal() { - int scale = 0; - String text = getIntegerPart(); - String t_fraction = getFractionalPart(); - if (t_fraction != null) { - text += getFractionalPart(); - // XXX Wrong for anything but base 10. - scale += t_fraction.length(); - } - String t_exponent = getExponent(); - if (t_exponent != null) - scale -= Integer.parseInt(t_exponent); - BigInteger unscaled = new BigInteger(text, getBase()); - return new BigDecimal(unscaled, scale); - } - - // We could construct a heuristic for when an 'int' is large enough. - // private static final int S_MAXLEN_LONG = String.valueOf(Long.MAX_VALUE).length(); - // private static final int S_MAXLEN_INT = String.valueOf(Integer.MAX_VALUE).length(); - - @Nonnull - public Number toJavaLangNumber() { - int flags = getFlags(); - if ((flags & F_DOUBLE) != 0) - return doubleValue(); - else if ((flags & F_FLOAT) != 0) - return floatValue(); - else if ((flags & (F_LONG | F_LONGLONG)) != 0) - return longValue(); - else if ((flags & F_INT) != 0) - return intValue(); - else if (getFractionalPart() != null) - return doubleValue(); // .1 is a double in Java. - else if (getExponent() != null) - return doubleValue(); - else { - // This is an attempt to avoid overflowing on over-long integers. - // However, now we just overflow on over-long longs. - // We should really use BigInteger. - long value = longValue(); - if (value <= Integer.MAX_VALUE && value >= Integer.MIN_VALUE) - return (int) value; - return value; - } - } - - private int exponentValue() { - return Integer.parseInt(exponent, 10); - } - - @Override - public int intValue() { - // String.isEmpty() is since 1.6 - int v = integer.length() == 0 ? 0 : Integer.parseInt(integer, base); - if (expbase == 2) - v = v << exponentValue(); - else if (expbase != 0) - v = (int) (v * Math.pow(expbase, exponentValue())); - return v; - } - - @Override - public long longValue() { - // String.isEmpty() is since 1.6 - long v = integer.length() == 0 ? 0 : Long.parseLong(integer, base); - if (expbase == 2) - v = v << exponentValue(); - else if (expbase != 0) - v = (long) (v * Math.pow(expbase, exponentValue())); - return v; - } - - @Override - public float floatValue() { - if (getBase() != 10) - return longValue(); - return Float.parseFloat(toString()); - } - - @Override - public double doubleValue() { - if (getBase() != 10) - return longValue(); - return Double.parseDouble(toString()); - } - - private boolean appendFlags(StringBuilder buf, String suffix, int flag) { - if ((getFlags() & flag) != flag) - return false; - buf.append(suffix); - return true; - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - switch (base) { - case 8: - buf.append('0'); - break; - case 10: - break; - case 16: - buf.append("0x"); - break; - case 2: - buf.append('b'); - break; - default: - buf.append("[base-").append(base).append("]"); - break; - } - buf.append(getIntegerPart()); - if (getFractionalPart() != null) - buf.append('.').append(getFractionalPart()); - if (getExponent() != null) { - buf.append(base > 10 ? 'p' : 'e'); - buf.append(getExponent()); - } - /* - if (appendFlags(buf, "ui", F_UNSIGNED | F_INT)); - else if (appendFlags(buf, "ul", F_UNSIGNED | F_LONG)); - else if (appendFlags(buf, "ull", F_UNSIGNED | F_LONGLONG)); - else if (appendFlags(buf, "i", F_INT)); - else if (appendFlags(buf, "l", F_LONG)); - else if (appendFlags(buf, "ll", F_LONGLONG)); - else if (appendFlags(buf, "f", F_FLOAT)); - else if (appendFlags(buf, "d", F_DOUBLE)); - */ - return buf.toString(); - } -} diff --git a/src/main/java/org/anarres/cpp/Preprocessor.java b/src/main/java/org/anarres/cpp/Preprocessor.java deleted file mode 100644 index 884e7f7558..0000000000 --- a/src/main/java/org/anarres/cpp/Preprocessor.java +++ /dev/null @@ -1,2226 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import static org.anarres.cpp.PreprocessorCommand.PP_ERROR; -import static org.anarres.cpp.Token.AND_EQ; -import static org.anarres.cpp.Token.ARROW; -import static org.anarres.cpp.Token.CCOMMENT; -import static org.anarres.cpp.Token.CHARACTER; -import static org.anarres.cpp.Token.CPPCOMMENT; -import static org.anarres.cpp.Token.DEC; -import static org.anarres.cpp.Token.DIV_EQ; -import static org.anarres.cpp.Token.ELLIPSIS; -import static org.anarres.cpp.Token.EOF; -import static org.anarres.cpp.Token.EQ; -import static org.anarres.cpp.Token.GE; -import static org.anarres.cpp.Token.HASH; -import static org.anarres.cpp.Token.HEADER; -import static org.anarres.cpp.Token.IDENTIFIER; -import static org.anarres.cpp.Token.INC; -import static org.anarres.cpp.Token.INVALID; -import static org.anarres.cpp.Token.LAND; -import static org.anarres.cpp.Token.LE; -import static org.anarres.cpp.Token.LOR; -import static org.anarres.cpp.Token.LSH; -import static org.anarres.cpp.Token.LSH_EQ; -import static org.anarres.cpp.Token.MOD_EQ; -import static org.anarres.cpp.Token.MULT_EQ; -import static org.anarres.cpp.Token.M_ARG; -import static org.anarres.cpp.Token.M_PASTE; -import static org.anarres.cpp.Token.M_STRING; -import static org.anarres.cpp.Token.NE; -import static org.anarres.cpp.Token.NL; -import static org.anarres.cpp.Token.NUMBER; -import static org.anarres.cpp.Token.OR_EQ; -import static org.anarres.cpp.Token.PASTE; -import static org.anarres.cpp.Token.PLUS_EQ; -import static org.anarres.cpp.Token.P_LINE; -import static org.anarres.cpp.Token.RANGE; -import static org.anarres.cpp.Token.RSH; -import static org.anarres.cpp.Token.RSH_EQ; -import static org.anarres.cpp.Token.SQSTRING; -import static org.anarres.cpp.Token.STRING; -import static org.anarres.cpp.Token.SUB_EQ; -import static org.anarres.cpp.Token.WHITESPACE; -import static org.anarres.cpp.Token.XOR_EQ; - -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; -import java.util.TreeMap; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; - -import org.anarres.cpp.PreprocessorListener.SourceChangeEvent; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * A C Preprocessor. - * The Preprocessor outputs a token stream which does not need - * re-lexing for C or C++. Alternatively, the output text may be - * reconstructed by concatenating the {@link Token#getText() text} - * values of the returned {@link Token Tokens}. (See - * {@link CppReader}, which does this.) - */ -/* - * Source file name and line number information is conveyed by lines of the form - * - * # linenum filename flags - * - * These are called linemarkers. They are inserted as needed into - * the output (but never within a string or character constant). They - * mean that the following line originated in file filename at line - * linenum. filename will never contain any non-printing characters; - * they are replaced with octal escape sequences. - * - * After the file name comes zero or more flags, which are `1', `2', - * `3', or `4'. If there are multiple flags, spaces separate them. Here - * is what the flags mean: - * - * `1' - * This indicates the start of a new file. - * `2' - * This indicates returning to a file (after having included another - * file). - * `3' - * This indicates that the following text comes from a system header - * file, so certain warnings should be suppressed. - * `4' - * This indicates that the following text should be treated as being - * wrapped in an implicit extern "C" block. - */ -public class Preprocessor implements Closeable { - - private static final Logger LOG = LogManager.getLogger(Preprocessor.class); - - private static final Source INTERNAL = new Source() { - @Override - public Token token() - throws IOException, - LexerException { - throw new LexerException("Cannot read from " + getName()); - } - - @Override - public String getPath() { - return ""; - } - - @Override - public String getName() { - return "internal data"; - } - }; - private static final Macro __LINE__ = new Macro(INTERNAL, "__LINE__"); - private static final Macro __FILE__ = new Macro(INTERNAL, "__FILE__"); - private static final Macro __COUNTER__ = new Macro(INTERNAL, "__COUNTER__"); - - private final List inputs; - - /* The fundamental engine. */ - private final Map macros; - private final Stack states; - private Source source; - - /* Miscellaneous support. */ - private int counter; - private final Set onceseenpaths = new HashSet(); - private final List includes = new ArrayList(); - - /* Support junk to make it work like cpp */ - private List quoteincludepath; /* -iquote */ - - private List sysincludepath; /* -I */ - - private List frameworkspath; - private final Set features; - private final Set warnings; - private VirtualFileSystem filesystem; - private PreprocessorListener listener; - - public Preprocessor() { - this.inputs = new ArrayList(); - - this.macros = new HashMap(); - macros.put(__LINE__.getName(), __LINE__); - macros.put(__FILE__.getName(), __FILE__); - macros.put(__COUNTER__.getName(), __COUNTER__); - this.states = new Stack(); - states.push(new State()); - this.source = null; - - this.counter = 0; - - this.quoteincludepath = new ArrayList(); - this.sysincludepath = new ArrayList(); - this.frameworkspath = new ArrayList(); - this.features = EnumSet.noneOf(Feature.class); - this.warnings = EnumSet.noneOf(Warning.class); - this.filesystem = new JavaFileSystem(); - this.listener = null; - } - - public Preprocessor(@Nonnull Source initial) { - this(); - addInput(initial); - } - - /** Equivalent to - * 'new Preprocessor(new {@link FileLexerSource}(file))' - */ - public Preprocessor(@Nonnull File file) - throws IOException { - this(new FileLexerSource(file)); - } - - /** - * Sets the VirtualFileSystem used by this Preprocessor. - */ - public void setFileSystem(@Nonnull VirtualFileSystem filesystem) { - this.filesystem = filesystem; - } - - /** - * Returns the VirtualFileSystem used by this Preprocessor. - */ - @Nonnull - public VirtualFileSystem getFileSystem() { - return filesystem; - } - - /** - * Sets the PreprocessorListener which handles events for - * this Preprocessor. - * - * The listener is notified of warnings, errors and source - * changes, amongst other things. - */ - public void setListener(@Nonnull PreprocessorListener listener) { - this.listener = listener; - Source s = source; - while (s != null) { - // s.setListener(listener); - s.init(this); - s = s.getParent(); - } - } - - /** - * Returns the PreprocessorListener which handles events for - * this Preprocessor. - */ - @Nonnull - public PreprocessorListener getListener() { - return listener; - } - - /** - * Returns the feature-set for this Preprocessor. - * - * This set may be freely modified by user code. - */ - @Nonnull - public Set getFeatures() { - return features; - } - - /** - * Adds a feature to the feature-set of this Preprocessor. - */ - public void addFeature(@Nonnull Feature f) { - features.add(f); - } - - /** - * Adds features to the feature-set of this Preprocessor. - */ - public void addFeatures(@Nonnull Collection f) { - features.addAll(f); - } - - /** - * Adds features to the feature-set of this Preprocessor. - */ - public void addFeatures(Feature... f) { - addFeatures(Arrays.asList(f)); - } - - /** - * Returns true if the given feature is in - * the feature-set of this Preprocessor. - */ - public boolean getFeature(@Nonnull Feature f) { - return features.contains(f); - } - - /** - * Returns the warning-set for this Preprocessor. - * - * This set may be freely modified by user code. - */ - @Nonnull - public Set getWarnings() { - return warnings; - } - - /** - * Adds a warning to the warning-set of this Preprocessor. - */ - public void addWarning(@Nonnull Warning w) { - warnings.add(w); - } - - /** - * Adds warnings to the warning-set of this Preprocessor. - */ - public void addWarnings(@Nonnull Collection w) { - warnings.addAll(w); - } - - /** - * Returns true if the given warning is in - * the warning-set of this Preprocessor. - */ - public boolean getWarning(@Nonnull Warning w) { - return warnings.contains(w); - } - - /** - * Adds input for the Preprocessor. - * - * Inputs are processed in the order in which they are added. - */ - public void addInput(@Nonnull Source source) { - source.init(this); - inputs.add(source); - } - - /** - * Adds input for the Preprocessor. - * - * @see #addInput(Source) - */ - public void addInput(@Nonnull File file) - throws IOException { - addInput(new FileLexerSource(file)); - } - - /** - * Handles an error. - * - * If a PreprocessorListener is installed, it receives the - * error. Otherwise, an exception is thrown. - */ - protected void error(int line, int column, @Nonnull String msg) - throws LexerException { - if (listener != null) - listener.handleError(source, line, column, msg); - else - throw new LexerException("Error at " + line + ":" + column + ": " + msg); - } - - /** - * Handles an error. - * - * If a PreprocessorListener is installed, it receives the - * error. Otherwise, an exception is thrown. - * - * @see #error(int, int, String) - */ - protected void error(@Nonnull Token tok, @Nonnull String msg) - throws LexerException { - error(tok.getLine(), tok.getColumn(), msg); - } - - /** - * Handles a warning. - * - * If a PreprocessorListener is installed, it receives the - * warning. Otherwise, an exception is thrown. - */ - protected void warning(int line, int column, @Nonnull String msg) - throws LexerException { - if (warnings.contains(Warning.ERROR)) - error(line, column, msg); - else if (listener != null) - listener.handleWarning(source, line, column, msg); - else - throw new LexerException("Warning at " + line + ":" + column + ": " + msg); - } - - /** - * Handles a warning. - * - * If a PreprocessorListener is installed, it receives the - * warning. Otherwise, an exception is thrown. - * - * @see #warning(int, int, String) - */ - protected void warning(@Nonnull Token tok, @Nonnull String msg) - throws LexerException { - warning(tok.getLine(), tok.getColumn(), msg); - } - - /** - * Adds a Macro to this Preprocessor. - * - * The given {@link Macro} object encapsulates both the name - * and the expansion. - * - * @throws LexerException if the definition fails or is otherwise illegal. - */ - public void addMacro(@Nonnull Macro m) throws LexerException { - // System.out.println("Macro " + m); - String name = m.getName(); - /* Already handled as a source error in macro(). */ - if ("defined".equals(name)) - throw new LexerException("Cannot redefine name 'defined'"); - macros.put(m.getName(), m); - } - - /** - * Defines the given name as a macro. - * - * The String value is lexed into a token stream, which is - * used as the macro expansion. - * - * @throws LexerException if the definition fails or is otherwise illegal. - */ - public void addMacro(@Nonnull String name, @Nonnull String value) - throws LexerException { - try { - Macro m = new Macro(name); - StringLexerSource s = new StringLexerSource(value); - for (;;) { - Token tok = s.token(); - if (tok.getType() == EOF) - break; - m.addToken(tok); - } - addMacro(m); - } catch (IOException e) { - throw new LexerException(e); - } - } - - /** - * Defines the given name as a macro, with the value 1. - * - * This is a convnience method, and is equivalent to - * addMacro(name, "1"). - * - * @throws LexerException if the definition fails or is otherwise illegal. - */ - public void addMacro(@Nonnull String name) - throws LexerException { - addMacro(name, "1"); - } - - /** - * Sets the user include path used by this Preprocessor. - */ - /* Note for future: Create an IncludeHandler? */ - public void setQuoteIncludePath(@Nonnull List path) { - this.quoteincludepath = path; - } - - /** - * Returns the user include-path of this Preprocessor. - * - * This list may be freely modified by user code. - */ - @Nonnull - public List getQuoteIncludePath() { - return quoteincludepath; - } - - /** - * Sets the system include path used by this Preprocessor. - */ - /* Note for future: Create an IncludeHandler? */ - public void setSystemIncludePath(@Nonnull List path) { - this.sysincludepath = path; - } - - /** - * Returns the system include-path of this Preprocessor. - * - * This list may be freely modified by user code. - */ - @Nonnull - public List getSystemIncludePath() { - return sysincludepath; - } - - /** - * Sets the Objective-C frameworks path used by this Preprocessor. - */ - /* Note for future: Create an IncludeHandler? */ - public void setFrameworksPath(@Nonnull List path) { - this.frameworkspath = path; - } - - /** - * Returns the Objective-C frameworks path used by this - * Preprocessor. - * - * This list may be freely modified by user code. - */ - @Nonnull - public List getFrameworksPath() { - return frameworkspath; - } - - /** - * Returns the Map of Macros parsed during the run of this - * Preprocessor. - * - * @return The {@link Map} of macros currently defined. - */ - @Nonnull - public Map getMacros() { - return macros; - } - - /** - * Returns the named macro. - * - * While you can modify the returned object, unexpected things - * might happen if you do. - * - * @return the Macro object, or null if not found. - */ - @CheckForNull - public Macro getMacro(@Nonnull String name) { - return macros.get(name); - } - - /** - * Returns the list of {@link VirtualFile VirtualFiles} which have been - * included by this Preprocessor. - * - * This does not include any {@link Source} provided to the constructor - * or {@link #addInput(java.io.File)} or {@link #addInput(Source)}. - */ - @Nonnull - public List getIncludes() { - return includes; - } - - /* States */ - private void push_state() { - State top = states.peek(); - states.push(new State(top)); - } - - private void pop_state() - throws LexerException { - State s = states.pop(); - if (states.isEmpty()) { - error(0, 0, "#" + "endif without #" + "if"); - states.push(s); - } - } - - private boolean isActive() { - State state = states.peek(); - return state.isParentActive() && state.isActive(); - } - - - /* Sources */ - /** - * Returns the top Source on the input stack. - * - * @see Source - * @see #push_source(Source,boolean) - * @see #pop_source() - * - * @return the top Source on the input stack. - */ - // @CheckForNull - protected Source getSource() { - return source; - } - - /** - * Pushes a Source onto the input stack. - * - * @param source the new Source to push onto the top of the input stack. - * @param autopop if true, the Source is automatically removed from the input stack at EOF. - * @see #getSource() - * @see #pop_source() - */ - protected void push_source(@Nonnull Source source, boolean autopop) { - source.init(this); - source.setParent(this.source, autopop); - // source.setListener(listener); - if (listener != null) - listener.handleSourceChange(this.source, SourceChangeEvent.SUSPEND); - this.source = source; - if (listener != null) - listener.handleSourceChange(this.source, SourceChangeEvent.PUSH); - } - - /** - * Pops a Source from the input stack. - * - * @see #getSource() - * @see #push_source(Source,boolean) - * - * @param linemarker TODO: currently ignored, might be a bug? - * @throws IOException if an I/O error occurs. - */ - @CheckForNull - protected Token pop_source(boolean linemarker) - throws IOException { - if (listener != null) - listener.handleSourceChange(this.source, SourceChangeEvent.POP); - Source s = this.source; - this.source = s.getParent(); - /* Always a noop unless called externally. */ - s.close(); - if (listener != null && this.source != null) - listener.handleSourceChange(this.source, SourceChangeEvent.RESUME); - - Source t = getSource(); - if (getFeature(Feature.LINEMARKERS) - && s.isNumbered() - && t != null) { - /* We actually want 'did the nested source - * contain a newline token', which isNumbered() - * approximates. This is not perfect, but works. */ - return line_token(t.getLine(), t.getName(), " 2"); - } - - return null; - } - - protected void pop_source() - throws IOException { - pop_source(false); - } - - @Nonnull - private Token next_source() { - if (inputs.isEmpty()) - return new Token(EOF); - Source s = inputs.remove(0); - push_source(s, true); - return line_token(s.getLine(), s.getName(), " 1"); - } - - /* Source tokens */ - private Token source_token; - - /* XXX Make this include the NL, and make all cpp directives eat - * their own NL. */ - @Nonnull - private Token line_token(int line, @CheckForNull String name, @Nonnull String extra) { - StringBuilder buf = new StringBuilder(); - buf.append("#line ").append(line) - .append(" \""); - /* XXX This call to escape(name) is correct but ugly. */ - if (name == null) - buf.append(""); - else - MacroTokenSource.escape(buf, name); - buf.append("\"").append(extra).append("\n"); - return new Token(P_LINE, line, 0, buf.toString(), null); - } - - @Nonnull - private Token source_token() - throws IOException, - LexerException { - if (source_token != null) { - Token tok = source_token; - source_token = null; - if (getFeature(Feature.DEBUG)) - LOG.debug("Returning unget token " + tok); - return tok; - } - - for (;;) { - Source s = getSource(); - if (s == null) { - Token t = next_source(); - if (t.getType() == P_LINE && !getFeature(Feature.LINEMARKERS)) - continue; - return t; - } - Token tok = s.token(); - /* XXX Refactor with skipline() */ - if (tok.getType() == EOF && s.isAutopop()) { - // System.out.println("Autopop " + s); - Token mark = pop_source(true); - if (mark != null) - return mark; - continue; - } - if (getFeature(Feature.DEBUG)) - LOG.debug("Returning fresh token " + tok); - return tok; - } - } - - private void source_untoken(Token tok) { - if (this.source_token != null) - throw new IllegalStateException("Cannot return two tokens"); - this.source_token = tok; - } - - private boolean isWhite(Token tok) { - int type = tok.getType(); - return (type == WHITESPACE) - || (type == CCOMMENT) - || (type == CPPCOMMENT); - } - - private Token source_token_nonwhite() - throws IOException, - LexerException { - Token tok; - do { - tok = source_token(); - } while (isWhite(tok)); - return tok; - } - - /** - * Returns an NL or an EOF token. - * - * The metadata on the token will be correct, which is better - * than generating a new one. - * - * This method can, as of recent patches, return a P_LINE token. - */ - private Token source_skipline(boolean white) - throws IOException, - LexerException { - // (new Exception("skipping line")).printStackTrace(System.out); - Source s = getSource(); - Token tok = s.skipline(white); - /* XXX Refactor with source_token() */ - if (tok.getType() == EOF && s.isAutopop()) { - // System.out.println("Autopop " + s); - Token mark = pop_source(true); - if (mark != null) - return mark; - } - return tok; - } - - /* processes and expands a macro. */ - private boolean macro(Macro m, Token orig) - throws IOException, - LexerException { - Token tok; - List args; - - // System.out.println("pp: expanding " + m); - if (m.isFunctionLike()) { - OPEN: - for (;;) { - tok = source_token(); - // System.out.println("pp: open: token is " + tok); - switch (tok.getType()) { - case WHITESPACE: /* XXX Really? */ - - case CCOMMENT: - case CPPCOMMENT: - case NL: - break; /* continue */ - - case '(': - break OPEN; - default: - source_untoken(tok); - return false; - } - } - - // tok = expanded_token_nonwhite(); - tok = source_token_nonwhite(); - - /* We either have, or we should have args. - * This deals elegantly with the case that we have - * one empty arg. */ - if (tok.getType() != ')' || m.getArgs() > 0) { - args = new ArrayList(); - - Argument arg = new Argument(); - int depth = 0; - boolean space = false; - - ARGS: - for (;;) { - // System.out.println("pp: arg: token is " + tok); - switch (tok.getType()) { - case EOF: - error(tok, "EOF in macro args"); - return false; - - case ',': - if (depth == 0) { - if (m.isVariadic() - && /* We are building the last arg. */ args.size() == m.getArgs() - 1) { - /* Just add the comma. */ - arg.addToken(tok); - } else { - args.add(arg); - arg = new Argument(); - } - } else { - arg.addToken(tok); - } - space = false; - break; - case ')': - if (depth == 0) { - args.add(arg); - break ARGS; - } else { - depth--; - arg.addToken(tok); - } - space = false; - break; - case '(': - depth++; - arg.addToken(tok); - space = false; - break; - - case WHITESPACE: - case CCOMMENT: - case CPPCOMMENT: - case NL: - /* Avoid duplicating spaces. */ - space = true; - break; - - default: - /* Do not put space on the beginning of - * an argument token. */ - if (space && !arg.isEmpty()) - arg.addToken(Token.space); - arg.addToken(tok); - space = false; - break; - - } - // tok = expanded_token(); - tok = source_token(); - } - /* space may still be true here, thus trailing space - * is stripped from arguments. */ - - if (args.size() != m.getArgs()) { - if (m.isVariadic()) { - if (args.size() == m.getArgs() - 1) { - args.add(new Argument()); - } else { - error(tok, - "variadic macro " + m.getName() - + " has at least " + (m.getArgs() - 1) + " parameters " - + "but given " + args.size() + " args"); - return false; - } - } else { - error(tok, - "macro " + m.getName() - + " has " + m.getArgs() + " parameters " - + "but given " + args.size() + " args"); - /* We could replay the arg tokens, but I - * note that GNU cpp does exactly what we do, - * i.e. output the macro name and chew the args. - */ - return false; - } - } - - for (Argument a : args) { - a.expand(this); - } - - // System.out.println("Macro " + m + " args " + args); - } else { - /* nargs == 0 and we (correctly) got () */ - args = null; - } - - } else { - /* Macro without args. */ - args = null; - } - - if (m == __LINE__) { - push_source(new FixedTokenSource( - new Token[]{new Token(NUMBER, - orig.getLine(), orig.getColumn(), - Integer.toString(orig.getLine()), - new NumericValue(10, Integer.toString(orig.getLine())))} - ), true); - } else if (m == __FILE__) { - StringBuilder buf = new StringBuilder("\""); - String name = getSource().getName(); - if (name == null) - name = ""; - for (int i = 0; i < name.length(); i++) { - char c = name.charAt(i); - switch (c) { - case '\\': - buf.append("\\\\"); - break; - case '"': - buf.append("\\\""); - break; - default: - buf.append(c); - break; - } - } - buf.append("\""); - String text = buf.toString(); - push_source(new FixedTokenSource( - new Token[]{new Token(STRING, - orig.getLine(), orig.getColumn(), - text, text)} - ), true); - } else if (m == __COUNTER__) { - /* This could equivalently have been done by adding - * a special Macro subclass which overrides getTokens(). */ - int value = this.counter++; - push_source(new FixedTokenSource( - new Token[]{new Token(NUMBER, - orig.getLine(), orig.getColumn(), - Integer.toString(value), - new NumericValue(10, Integer.toString(value)))} - ), true); - } else { - push_source(new MacroTokenSource(m, args), true); - } - - return true; - } - - /** - * Expands an argument. - */ - /* I'd rather this were done lazily, but doing so breaks spec. */ - @Nonnull - /* pp */ List expand(@Nonnull List arg) - throws IOException, - LexerException { - List expansion = new ArrayList(); - boolean space = false; - - push_source(new FixedTokenSource(arg), false); - - EXPANSION: - for (;;) { - Token tok = expanded_token(); - switch (tok.getType()) { - case EOF: - break EXPANSION; - - case WHITESPACE: - case CCOMMENT: - case CPPCOMMENT: - space = true; - break; - - default: - if (space && !expansion.isEmpty()) - expansion.add(Token.space); - expansion.add(tok); - space = false; - break; - } - } - - // Always returns null. - pop_source(false); - - return expansion; - } - - /* processes a #define directive */ - private Token define() - throws IOException, - LexerException { - Token tok = source_token_nonwhite(); - if (tok.getType() != IDENTIFIER) { - error(tok, "Expected identifier"); - return source_skipline(false); - } - /* if predefined */ - - String name = tok.getText(); - if ("defined".equals(name)) { - error(tok, "Cannot redefine name 'defined'"); - return source_skipline(false); - } - - Macro m = new Macro(getSource(), name); - List args; - - tok = source_token(); - if (tok.getType() == '(') { - tok = source_token_nonwhite(); - if (tok.getType() != ')') { - args = new ArrayList(); - ARGS: - for (;;) { - switch (tok.getType()) { - case IDENTIFIER: - args.add(tok.getText()); - break; - case ELLIPSIS: - // Unnamed Variadic macro - args.add("__VA_ARGS__"); - // We just named the ellipsis, but we unget the token - // to allow the ELLIPSIS handling below to process it. - source_untoken(tok); - break; - case NL: - case EOF: - error(tok, - "Unterminated macro parameter list"); - return tok; - default: - error(tok, - "error in macro parameters: " - + tok.getText()); - return source_skipline(false); - } - tok = source_token_nonwhite(); - switch (tok.getType()) { - case ',': - break; - case ELLIPSIS: - tok = source_token_nonwhite(); - if (tok.getType() != ')') - error(tok, - "ellipsis must be on last argument"); - m.setVariadic(true); - break ARGS; - case ')': - break ARGS; - - case NL: - case EOF: - /* Do not skip line. */ - error(tok, - "Unterminated macro parameters"); - return tok; - default: - error(tok, - "Bad token in macro parameters: " - + tok.getText()); - return source_skipline(false); - } - tok = source_token_nonwhite(); - } - } else { - assert tok.getType() == ')' : "Expected ')'"; - args = Collections.emptyList(); - } - - m.setArgs(args); - } else { - /* For searching. */ - args = Collections.emptyList(); - source_untoken(tok); - } - - /* Get an expansion for the macro, using indexOf. */ - boolean space = false; - boolean paste = false; - int idx; - - /* Ensure no space at start. */ - tok = source_token_nonwhite(); - EXPANSION: - for (;;) { - switch (tok.getType()) { - case EOF: - break EXPANSION; - case NL: - break EXPANSION; - - case CCOMMENT: - case CPPCOMMENT: - /* XXX This is where we implement GNU's cpp -CC. */ - // break; - case WHITESPACE: - if (!paste) - space = true; - break; - - /* Paste. */ - case PASTE: - space = false; - paste = true; - m.addPaste(new Token(M_PASTE, - tok.getLine(), tok.getColumn(), - "#" + "#", null)); - break; - - /* Stringify. */ - case '#': - if (space) - m.addToken(Token.space); - space = false; - Token la = source_token_nonwhite(); - if (la.getType() == IDENTIFIER - && ((idx = args.indexOf(la.getText())) != -1)) { - m.addToken(new Token(M_STRING, - la.getLine(), la.getColumn(), - "#" + la.getText(), - Integer.valueOf(idx))); - } else { - m.addToken(tok); - /* Allow for special processing. */ - source_untoken(la); - } - break; - - case IDENTIFIER: - if (space) - m.addToken(Token.space); - space = false; - paste = false; - idx = args.indexOf(tok.getText()); - if (idx == -1) - m.addToken(tok); - else - m.addToken(new Token(M_ARG, - tok.getLine(), tok.getColumn(), - tok.getText(), - Integer.valueOf(idx))); - break; - - default: - if (space) - m.addToken(Token.space); - space = false; - paste = false; - m.addToken(tok); - break; - } - tok = source_token(); - } - - if (getFeature(Feature.DEBUG)) - LOG.debug("Defined macro " + m); - addMacro(m); - - return tok; /* NL or EOF. */ - - } - - @Nonnull - private Token undef() - throws IOException, - LexerException { - Token tok = source_token_nonwhite(); - if (tok.getType() != IDENTIFIER) { - error(tok, - "Expected identifier, not " + tok.getText()); - if (tok.getType() == NL || tok.getType() == EOF) - return tok; - } else { - Macro m = getMacro(tok.getText()); - if (m != null) { - /* XXX error if predefined */ - macros.remove(m.getName()); - } - } - return source_skipline(true); - } - - /** - * Attempts to include the given file. - * - * User code may override this method to implement a virtual - * file system. - * - * @param file The VirtualFile to attempt to include. - * @return true if the file was successfully included, false otherwise. - * @throws IOException if an I/O error occurs. - */ - protected boolean include(@Nonnull VirtualFile file) - throws IOException { - // System.out.println("Try to include " + ((File)file).getAbsolutePath()); - if (!file.isFile()) - return false; - if (getFeature(Feature.DEBUG)) - LOG.debug("pp: including " + file); - includes.add(file); - push_source(file.getSource(), true); - return true; - } - - /** - * Attempts to include a file from an include path, by name. - * - * @param path The list of virtual directories to search for the given name. - * @param name The name of the file to attempt to include. - * @return true if the file was successfully included, false otherwise. - * @throws IOException if an I/O error occurs. - */ - protected boolean include(@Nonnull Iterable path, @Nonnull String name) - throws IOException { - for (String dir : path) { - VirtualFile file = getFileSystem().getFile(dir, name); - if (include(file)) - return true; - } - return false; - } - - /** - * Handles an include directive. - * - * @throws IOException if an I/O error occurs. - * @throws LexerException if the include fails, and the error handler is fatal. - */ - private void include( - @CheckForNull String parent, int line, - @Nonnull String name, boolean quoted, boolean next) - throws IOException, - LexerException { - if (name.startsWith("/")) { - VirtualFile file = filesystem.getFile(name); - if (include(file)) - return; - StringBuilder buf = new StringBuilder(); - buf.append("File not found: ").append(name); - error(line, 0, buf.toString()); - return; - } - - VirtualFile pdir = null; - if (quoted) { - if (parent != null) { - VirtualFile pfile = filesystem.getFile(parent); - pdir = pfile.getParentFile(); - } - if (pdir != null) { - VirtualFile ifile = pdir.getChildFile(name); - if (include(ifile)) - return; - } - if (include(quoteincludepath, name)) - return; - } else { - int idx = name.indexOf('/'); - if (idx != -1) { - String frameworkName = name.substring(0, idx); - String headerName = name.substring(idx + 1); - String headerPath = frameworkName + ".framework/Headers/" + headerName; - if (include(frameworkspath, headerPath)) - return; - } - } - - if (include(sysincludepath, name)) - return; - - StringBuilder buf = new StringBuilder(); - buf.append("File not found: ").append(name); - buf.append(" in"); - if (quoted) { - buf.append(" .").append('(').append(pdir).append(')'); - for (String dir : quoteincludepath) - buf.append(" ").append(dir); - } - for (String dir : sysincludepath) - buf.append(" ").append(dir); - error(line, 0, buf.toString()); - } - - @Nonnull - private Token include(boolean next) - throws IOException, - LexerException { - LexerSource lexer = (LexerSource) source; - try { - lexer.setInclude(true); - Token tok = token_nonwhite(); - - String name; - boolean quoted; - - if (tok.getType() == STRING) { - /* XXX Use the original text, not the value. - * Backslashes must not be treated as escapes here. */ - StringBuilder buf = new StringBuilder((String) tok.getValue()); - HEADER: - for (;;) { - tok = token_nonwhite(); - switch (tok.getType()) { - case STRING: - buf.append((String) tok.getValue()); - break; - case NL: - case EOF: - break HEADER; - default: - warning(tok, - "Unexpected token on #" + "include line"); - return source_skipline(false); - } - } - name = buf.toString(); - quoted = true; - } else if (tok.getType() == HEADER) { - name = (String) tok.getValue(); - quoted = false; - tok = source_skipline(true); - } else { - error(tok, - "Expected string or header, not " + tok.getText()); - switch (tok.getType()) { - case NL: - case EOF: - return tok; - default: - /* Only if not a NL or EOF already. */ - return source_skipline(false); - } - } - - /* Do the inclusion. */ - include(source.getPath(), tok.getLine(), name, quoted, next); - - /* 'tok' is the 'nl' after the include. We use it after the - * #line directive. */ - if (getFeature(Feature.LINEMARKERS)) - return line_token(1, source.getName(), " 1"); - return tok; - } finally { - lexer.setInclude(false); - } - } - - protected void pragma_once(@Nonnull Token name) - throws IOException, LexerException { - Source s = this.source; - if (!onceseenpaths.add(s.getPath())) { - Token mark = pop_source(true); - // FixedTokenSource should never generate a linemarker on exit. - if (mark != null) - push_source(new FixedTokenSource(Arrays.asList(mark)), true); - } - } - - protected void pragma(@Nonnull Token name, @Nonnull List value) - throws IOException, - LexerException { - if (getFeature(Feature.PRAGMA_ONCE)) { - if ("once".equals(name.getText())) { - pragma_once(name); - return; - } - } - warning(name, "Unknown #" + "pragma: " + name.getText()); - } - - @Nonnull - private Token pragma() - throws IOException, - LexerException { - Token name; - - NAME: - for (;;) { - Token tok = source_token(); - switch (tok.getType()) { - case EOF: - /* There ought to be a newline before EOF. - * At least, in any skipline context. */ - /* XXX Are we sure about this? */ - warning(tok, - "End of file in #" + "pragma"); - return tok; - case NL: - /* This may contain one or more newlines. */ - warning(tok, - "Empty #" + "pragma"); - return tok; - case CCOMMENT: - case CPPCOMMENT: - case WHITESPACE: - continue NAME; - case IDENTIFIER: - name = tok; - break NAME; - default: - warning(tok, - "Illegal #" + "pragma " + tok.getText()); - return source_skipline(false); - } - } - - Token tok; - List value = new ArrayList(); - VALUE: - for (;;) { - tok = source_token(); - switch (tok.getType()) { - case EOF: - /* There ought to be a newline before EOF. - * At least, in any skipline context. */ - /* XXX Are we sure about this? */ - warning(tok, - "End of file in #" + "pragma"); - break VALUE; - case NL: - /* This may contain one or more newlines. */ - break VALUE; - case CCOMMENT: - case CPPCOMMENT: - break; - case WHITESPACE: - value.add(tok); - break; - default: - value.add(tok); - break; - } - } - - pragma(name, value); - - return tok; /* The NL. */ - - } - - /* For #error and #warning. */ - private void error(@Nonnull Token pptok, boolean is_error) - throws IOException, - LexerException { - StringBuilder buf = new StringBuilder(); - buf.append('#').append(pptok.getText()).append(' '); - /* Peculiar construction to ditch first whitespace. */ - Token tok = source_token_nonwhite(); - ERROR: - for (;;) { - switch (tok.getType()) { - case NL: - case EOF: - break ERROR; - default: - buf.append(tok.getText()); - break; - } - tok = source_token(); - } - if (is_error) - error(pptok, buf.toString()); - else - warning(pptok, buf.toString()); - } - - /* This bypasses token() for #elif expressions. - * If we don't do this, then isActive() == false - * causes token() to simply chew the entire input line. */ - @Nonnull - private Token expanded_token() - throws IOException, - LexerException { - for (;;) { - Token tok = source_token(); - // System.out.println("Source token is " + tok); - if (tok.getType() == IDENTIFIER) { - Macro m = getMacro(tok.getText()); - if (m == null) - return tok; - if (source.isExpanding(m)) - return tok; - if (macro(m, tok)) - continue; - } - return tok; - } - } - - @Nonnull - private Token expanded_token_nonwhite() - throws IOException, - LexerException { - Token tok; - do { - tok = expanded_token(); - // System.out.println("expanded token is " + tok); - } while (isWhite(tok)); - return tok; - } - - @CheckForNull - private Token expr_token = null; - - @Nonnull - private Token expr_token() - throws IOException, - LexerException { - Token tok = expr_token; - - if (tok != null) { - // System.out.println("ungetting"); - expr_token = null; - } else { - tok = expanded_token_nonwhite(); - // System.out.println("expt is " + tok); - - if (tok.getType() == IDENTIFIER - && tok.getText().equals("defined")) { - Token la = source_token_nonwhite(); - boolean paren = false; - if (la.getType() == '(') { - paren = true; - la = source_token_nonwhite(); - } - - // System.out.println("Core token is " + la); - if (la.getType() != IDENTIFIER) { - error(la, - "defined() needs identifier, not " - + la.getText()); - tok = new Token(NUMBER, - la.getLine(), la.getColumn(), - "0", new NumericValue(10, "0")); - } else if (macros.containsKey(la.getText())) { - // System.out.println("Found macro"); - tok = new Token(NUMBER, - la.getLine(), la.getColumn(), - "1", new NumericValue(10, "1")); - } else { - // System.out.println("Not found macro"); - tok = new Token(NUMBER, - la.getLine(), la.getColumn(), - "0", new NumericValue(10, "0")); - } - - if (paren) { - la = source_token_nonwhite(); - if (la.getType() != ')') { - expr_untoken(la); - error(la, "Missing ) in defined(). Got " + la.getText()); - } - } - } - } - - // System.out.println("expr_token returns " + tok); - return tok; - } - - private void expr_untoken(@Nonnull Token tok) - throws LexerException { - if (expr_token != null) - throw new InternalException( - "Cannot unget two expression tokens." - ); - expr_token = tok; - } - - private int expr_priority(@Nonnull Token op) { - switch (op.getType()) { - case '/': - return 11; - case '%': - return 11; - case '*': - return 11; - case '+': - return 10; - case '-': - return 10; - case LSH: - return 9; - case RSH: - return 9; - case '<': - return 8; - case '>': - return 8; - case LE: - return 8; - case GE: - return 8; - case EQ: - return 7; - case NE: - return 7; - case '&': - return 6; - case '^': - return 5; - case '|': - return 4; - case LAND: - return 3; - case LOR: - return 2; - case '?': - return 1; - default: - // System.out.println("Unrecognised operator " + op); - return 0; - } - } - - private int expr_char(Token token) { - Object value = token.getValue(); - if (value instanceof Character) - return ((Character) value).charValue(); - String text = String.valueOf(value); - if (text.length() == 0) - return 0; - return text.charAt(0); - } - - private long expr(int priority) - throws IOException, - LexerException { - /* - * (new Exception("expr(" + priority + ") called")).printStackTrace(); - */ - - Token tok = expr_token(); - long lhs, rhs; - - // System.out.println("Expr lhs token is " + tok); - switch (tok.getType()) { - case '(': - lhs = expr(0); - tok = expr_token(); - if (tok.getType() != ')') { - expr_untoken(tok); - error(tok, "Missing ) in expression. Got " + tok.getText()); - return 0; - } - break; - - case '~': - lhs = ~expr(11); - break; - case '!': - lhs = expr(11) == 0 ? 1 : 0; - break; - case '-': - lhs = -expr(11); - break; - case NUMBER: - NumericValue value = (NumericValue) tok.getValue(); - lhs = value.longValue(); - break; - case CHARACTER: - lhs = expr_char(tok); - break; - case IDENTIFIER: - if (warnings.contains(Warning.UNDEF)) - warning(tok, "Undefined token '" + tok.getText() - + "' encountered in conditional."); - lhs = 0; - break; - - default: - expr_untoken(tok); - error(tok, - "Bad token in expression: " + tok.getText()); - return 0; - } - - EXPR: - for (;;) { - // System.out.println("expr: lhs is " + lhs + ", pri = " + priority); - Token op = expr_token(); - int pri = expr_priority(op); /* 0 if not a binop. */ - - if (pri == 0 || priority >= pri) { - expr_untoken(op); - break EXPR; - } - rhs = expr(pri); - // System.out.println("rhs token is " + rhs); - switch (op.getType()) { - case '/': - if (rhs == 0) { - error(op, "Division by zero"); - lhs = 0; - } else { - lhs = lhs / rhs; - } - break; - case '%': - if (rhs == 0) { - error(op, "Modulus by zero"); - lhs = 0; - } else { - lhs = lhs % rhs; - } - break; - case '*': - lhs = lhs * rhs; - break; - case '+': - lhs = lhs + rhs; - break; - case '-': - lhs = lhs - rhs; - break; - case '<': - lhs = lhs < rhs ? 1 : 0; - break; - case '>': - lhs = lhs > rhs ? 1 : 0; - break; - case '&': - lhs = lhs & rhs; - break; - case '^': - lhs = lhs ^ rhs; - break; - case '|': - lhs = lhs | rhs; - break; - - case LSH: - lhs = lhs << rhs; - break; - case RSH: - lhs = lhs >> rhs; - break; - case LE: - lhs = lhs <= rhs ? 1 : 0; - break; - case GE: - lhs = lhs >= rhs ? 1 : 0; - break; - case EQ: - lhs = lhs == rhs ? 1 : 0; - break; - case NE: - lhs = lhs != rhs ? 1 : 0; - break; - case LAND: - lhs = (lhs != 0) && (rhs != 0) ? 1 : 0; - break; - case LOR: - lhs = (lhs != 0) || (rhs != 0) ? 1 : 0; - break; - - case '?': { - tok = expr_token(); - if (tok.getType() != ':') { - expr_untoken(tok); - error(tok, "Missing : in conditional expression. Got " + tok.getText()); - return 0; - } - long falseResult = expr(0); - lhs = (lhs != 0) ? rhs : falseResult; - } - break; - - default: - error(op, - "Unexpected operator " + op.getText()); - return 0; - - } - } - - /* - * (new Exception("expr returning " + lhs)).printStackTrace(); - */ - // System.out.println("expr returning " + lhs); - return lhs; - } - - @Nonnull - private Token toWhitespace(@Nonnull Token tok) { - String text = tok.getText(); - int len = text.length(); - boolean cr = false; - int nls = 0; - - for (int i = 0; i < len; i++) { - char c = text.charAt(i); - - switch (c) { - case '\r': - cr = true; - nls++; - break; - case '\n': - if (cr) { - cr = false; - break; - } - /* fallthrough */ - case '\u2028': - case '\u2029': - case '\u000B': - case '\u000C': - case '\u0085': - cr = false; - nls++; - break; - } - } - - char[] cbuf = new char[nls]; - Arrays.fill(cbuf, '\n'); - return new Token(WHITESPACE, - tok.getLine(), tok.getColumn(), - new String(cbuf)); - } - - @Nonnull - private Token _token() - throws IOException, - LexerException { - - for (;;) { - Token tok; - if (!isActive()) { - Source s = getSource(); - if (s == null) { - Token t = next_source(); - if (t.getType() == P_LINE && !getFeature(Feature.LINEMARKERS)) - continue; - return t; - } - - try { - /* XXX Tell lexer to ignore warnings. */ - s.setActive(false); - tok = source_token(); - } finally { - /* XXX Tell lexer to stop ignoring warnings. */ - s.setActive(true); - } - switch (tok.getType()) { - case HASH: - case NL: - case EOF: - /* The preprocessor has to take action here. */ - break; - case WHITESPACE: - return tok; - case CCOMMENT: - case CPPCOMMENT: - // Patch up to preserve whitespace. - if (getFeature(Feature.KEEPALLCOMMENTS)) - return tok; - if (!isActive()) - return toWhitespace(tok); - if (getFeature(Feature.KEEPCOMMENTS)) - return tok; - return toWhitespace(tok); - default: - // Return NL to preserve whitespace. - /* XXX This might lose a comment. */ - return source_skipline(false); - } - } else { - tok = source_token(); - } - - LEX: - switch (tok.getType()) { - case EOF: - /* Pop the stacks. */ - return tok; - - case WHITESPACE: - case NL: - return tok; - - case CCOMMENT: - case CPPCOMMENT: - return tok; - - case '!': - case '%': - case '&': - case '(': - case ')': - case '*': - case '+': - case ',': - case '-': - case '/': - case ':': - case ';': - case '<': - case '=': - case '>': - case '?': - case '[': - case ']': - case '^': - case '{': - case '|': - case '}': - case '~': - case '.': - - /* From Olivier Chafik for Objective C? */ - case '@': - /* The one remaining ASCII, might as well. */ - case '`': - - // case '#': - case AND_EQ: - case ARROW: - case CHARACTER: - case DEC: - case DIV_EQ: - case ELLIPSIS: - case EQ: - case GE: - case HEADER: /* Should only arise from include() */ - - case INC: - case LAND: - case LE: - case LOR: - case LSH: - case LSH_EQ: - case SUB_EQ: - case MOD_EQ: - case MULT_EQ: - case NE: - case OR_EQ: - case PLUS_EQ: - case RANGE: - case RSH: - case RSH_EQ: - case STRING: - case SQSTRING: - case XOR_EQ: - return tok; - - case NUMBER: - return tok; - - case IDENTIFIER: - Macro m = getMacro(tok.getText()); - if (m == null) - return tok; - if (source.isExpanding(m)) - return tok; - if (macro(m, tok)) - break; - return tok; - - case P_LINE: - if (getFeature(Feature.LINEMARKERS)) - return tok; - break; - - case INVALID: - if (getFeature(Feature.CSYNTAX)) - error(tok, String.valueOf(tok.getValue())); - return tok; - - default: - throw new InternalException("Bad token " + tok); - // break; - - case HASH: - tok = source_token_nonwhite(); - // (new Exception("here")).printStackTrace(); - switch (tok.getType()) { - case NL: - break LEX; /* Some code has #\n */ - - case IDENTIFIER: - break; - default: - error(tok, - "Preprocessor directive not a word " - + tok.getText()); - return source_skipline(false); - } - PreprocessorCommand ppcmd = PreprocessorCommand.forText(tok.getText()); - if (ppcmd == null) { - error(tok, - "Unknown preprocessor directive " - + tok.getText()); - return source_skipline(false); - } - - PP: - switch (ppcmd) { - - case PP_DEFINE: - if (!isActive()) - return source_skipline(false); - else - return define(); - // break; - - case PP_UNDEF: - if (!isActive()) - return source_skipline(false); - else - return undef(); - // break; - - case PP_INCLUDE: - if (!isActive()) - return source_skipline(false); - else - return include(false); - // break; - case PP_INCLUDE_NEXT: - if (!isActive()) - return source_skipline(false); - if (!getFeature(Feature.INCLUDENEXT)) { - error(tok, - "Directive include_next not enabled" - ); - return source_skipline(false); - } - return include(true); - // break; - - case PP_WARNING: - case PP_ERROR: - if (!isActive()) - return source_skipline(false); - else - error(tok, ppcmd == PP_ERROR); - break; - - case PP_IF: - push_state(); - if (!isActive()) { - return source_skipline(false); - } - expr_token = null; - states.peek().setActive(expr(0) != 0); - tok = expr_token(); /* unget */ - - if (tok.getType() == NL) - return tok; - return source_skipline(true); - // break; - - case PP_ELIF: - State state = states.peek(); - if (false) { - /* Check for 'if' */; - } else if (state.sawElse()) { - error(tok, - "#elif after #" + "else"); - return source_skipline(false); - } else if (!state.isParentActive()) { - /* Nested in skipped 'if' */ - return source_skipline(false); - } else if (state.isActive()) { - /* The 'if' part got executed. */ - state.setParentActive(false); - /* This is like # else # if but with - * only one # end. */ - state.setActive(false); - return source_skipline(false); - } else { - expr_token = null; - state.setActive(expr(0) != 0); - tok = expr_token(); /* unget */ - - if (tok.getType() == NL) - return tok; - return source_skipline(true); - } - // break; - - case PP_ELSE: - state = states.peek(); - if (false) - /* Check for 'if' */ ; else if (state.sawElse()) { - error(tok, - "#" + "else after #" + "else"); - return source_skipline(false); - } else { - state.setSawElse(); - state.setActive(!state.isActive()); - return source_skipline(warnings.contains(Warning.ENDIF_LABELS)); - } - // break; - - case PP_IFDEF: - push_state(); - if (!isActive()) { - return source_skipline(false); - } else { - tok = source_token_nonwhite(); - // System.out.println("ifdef " + tok); - if (tok.getType() != IDENTIFIER) { - error(tok, - "Expected identifier, not " - + tok.getText()); - return source_skipline(false); - } else { - String text = tok.getText(); - boolean exists - = macros.containsKey(text); - states.peek().setActive(exists); - return source_skipline(true); - } - } - // break; - - case PP_IFNDEF: - push_state(); - if (!isActive()) { - return source_skipline(false); - } else { - tok = source_token_nonwhite(); - if (tok.getType() != IDENTIFIER) { - error(tok, - "Expected identifier, not " - + tok.getText()); - return source_skipline(false); - } else { - String text = tok.getText(); - boolean exists - = macros.containsKey(text); - states.peek().setActive(!exists); - return source_skipline(true); - } - } - // break; - - case PP_ENDIF: - pop_state(); - return source_skipline(warnings.contains(Warning.ENDIF_LABELS)); - // break; - - case PP_LINE: - return source_skipline(false); - // break; - - case PP_PRAGMA: - if (!isActive()) - return source_skipline(false); - return pragma(); - // break; - - default: - /* Actual unknown directives are - * processed above. If we get here, - * we succeeded the map lookup but - * failed to handle it. Therefore, - * this is (unconditionally?) fatal. */ - // if (isActive()) /* XXX Could be warning. */ - throw new InternalException( - "Internal error: Unknown directive " - + tok); - // return source_skipline(false); - } - - } - } - } - - @Nonnull - private Token token_nonwhite() - throws IOException, - LexerException { - Token tok; - do { - tok = _token(); - } while (isWhite(tok)); - return tok; - } - - /** - * Returns the next preprocessor token. - * - * @see Token - * @return The next fully preprocessed token. - * @throws IOException if an I/O error occurs. - * @throws LexerException if a preprocessing error occurs. - * @throws InternalException if an unexpected error condition arises. - */ - @Nonnull - public Token token() - throws IOException, - LexerException { - Token tok = _token(); - if (getFeature(Feature.DEBUG)) - LOG.debug("pp: Returning " + tok); - return tok; - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - - Source s = getSource(); - while (s != null) { - buf.append(" -> ").append(String.valueOf(s)).append("\n"); - s = s.getParent(); - } - - Map macros = new TreeMap(getMacros()); - for (Macro macro : macros.values()) { - buf.append("#").append("macro ").append(macro).append("\n"); - } - - return buf.toString(); - } - - @Override - public void close() - throws IOException { - { - Source s = source; - while (s != null) { - s.close(); - s = s.getParent(); - } - } - for (Source s : inputs) { - s.close(); - } - } - -} diff --git a/src/main/java/org/anarres/cpp/PreprocessorCommand.java b/src/main/java/org/anarres/cpp/PreprocessorCommand.java deleted file mode 100644 index 3938360a7f..0000000000 --- a/src/main/java/org/anarres/cpp/PreprocessorCommand.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.anarres.cpp; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; - -/** - * - * @author shevek - */ -public enum PreprocessorCommand { - - PP_DEFINE("define"), - PP_ELIF("elif"), - PP_ELSE("else"), - PP_ENDIF("endif"), - PP_ERROR("error"), - PP_IF("if"), - PP_IFDEF("ifdef"), - PP_IFNDEF("ifndef"), - PP_INCLUDE("include"), - PP_LINE("line"), - PP_PRAGMA("pragma"), - PP_UNDEF("undef"), - PP_WARNING("warning"), - PP_INCLUDE_NEXT("include_next"), - PP_IMPORT("import"); - private final String text; - /* pp */ PreprocessorCommand(String text) { - this.text = text; - } - - @CheckForNull - public static PreprocessorCommand forText(@Nonnull String text) { - for (PreprocessorCommand ppcmd : PreprocessorCommand.values()) - if (ppcmd.text.equals(text)) - return ppcmd; - return null; - } -} diff --git a/src/main/java/org/anarres/cpp/PreprocessorListener.java b/src/main/java/org/anarres/cpp/PreprocessorListener.java deleted file mode 100644 index 48308d898f..0000000000 --- a/src/main/java/org/anarres/cpp/PreprocessorListener.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import javax.annotation.Nonnull; - -/** - * A handler for preprocessor events, primarily errors and warnings. - * - * If no PreprocessorListener is installed in a Preprocessor, all - * error and warning events will throw an exception. Installing a - * listener allows more intelligent handling of these events. - */ -public interface PreprocessorListener { - - /** - * Handles a warning. - * - * The behaviour of this method is defined by the - * implementation. It may simply record the error message, or - * it may throw an exception. - */ - public void handleWarning(@Nonnull Source source, int line, int column, - @Nonnull String msg) - throws LexerException; - - /** - * Handles an error. - * - * The behaviour of this method is defined by the - * implementation. It may simply record the error message, or - * it may throw an exception. - */ - public void handleError(@Nonnull Source source, int line, int column, - @Nonnull String msg) - throws LexerException; - - public enum SourceChangeEvent { - - SUSPEND, PUSH, POP, RESUME; - } - - public void handleSourceChange(@Nonnull Source source, @Nonnull SourceChangeEvent event); - -} diff --git a/src/main/java/org/anarres/cpp/ResourceFileSystem.java b/src/main/java/org/anarres/cpp/ResourceFileSystem.java deleted file mode 100644 index ebcaf8daf9..0000000000 --- a/src/main/java/org/anarres/cpp/ResourceFileSystem.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.anarres.cpp; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; - -import javax.annotation.Nonnull; - -/** - * - * @author shevek - */ -public class ResourceFileSystem implements VirtualFileSystem { - - private final ClassLoader loader; - private final Charset charset; - - public ResourceFileSystem(@Nonnull ClassLoader loader, @Nonnull Charset charset) { - this.loader = loader; - this.charset = charset; - } - - @Override - public VirtualFile getFile(String path) { - return new ResourceFile(loader, path); - } - - @Override - public VirtualFile getFile(String dir, String name) { - return getFile(dir + "/" + name); - } - - private class ResourceFile implements VirtualFile { - - private final ClassLoader loader; - private final String path; - - public ResourceFile(ClassLoader loader, String path) { - this.loader = loader; - this.path = path; - } - - @Override - public boolean isFile() { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - - @Override - public String getPath() { - return path; - } - - @Override - public String getName() { - return path.substring(path.lastIndexOf('/') + 1); - } - - @Override - public ResourceFile getParentFile() { - int idx = path.lastIndexOf('/'); - if (idx < 1) - return null; - return new ResourceFile(loader, path.substring(0, idx)); - } - - @Override - public ResourceFile getChildFile(String name) { - return new ResourceFile(loader, path + "/" + name); - } - - @Override - public Source getSource() throws IOException { - InputStream stream = loader.getResourceAsStream(path); - return new InputLexerSource(stream, charset); - } - } -} diff --git a/src/main/java/org/anarres/cpp/Source.java b/src/main/java/org/anarres/cpp/Source.java deleted file mode 100644 index 6d98242002..0000000000 --- a/src/main/java/org/anarres/cpp/Source.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import static org.anarres.cpp.Token.CCOMMENT; -import static org.anarres.cpp.Token.CPPCOMMENT; -import static org.anarres.cpp.Token.EOF; -import static org.anarres.cpp.Token.NL; -import static org.anarres.cpp.Token.WHITESPACE; - -import java.io.Closeable; -import java.io.IOException; -import java.util.Iterator; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; - -/** - * An input to the Preprocessor. - * - * Inputs may come from Files, Strings or other sources. The - * preprocessor maintains a stack of Sources. Operations such as - * file inclusion or token pasting will push a new source onto - * the Preprocessor stack. Sources pop from the stack when they - * are exhausted; this may be transparent or explicit. - * - * BUG: Error messages are not handled properly. - */ -public abstract class Source implements Iterable, Closeable { - - private Source parent; - private boolean autopop; - private PreprocessorListener listener; - private boolean active; - private boolean werror; - - /* LineNumberReader */ - - /* - // We can't do this, since we would lose the LexerException - private class Itr implements Iterator { - private Token next = null; - private void advance() { - try { - if (next != null) - next = token(); - } - catch (IOException e) { - throw new UnsupportedOperationException( - "Failed to advance token iterator: " + - e.getMessage() - ); - } - } - public boolean hasNext() { - return next.getType() != EOF; - } - public Token next() { - advance(); - Token t = next; - next = null; - return t; - } - public void remove() { - throw new UnsupportedOperationException( - "Cannot remove tokens from a Source." - ); - } - } - */ - public Source() { - this.parent = null; - this.autopop = false; - this.listener = null; - this.active = true; - this.werror = false; - } - - /** - * Sets the parent source of this source. - * - * Sources form a singly linked list. - */ - /* pp */ void setParent(Source parent, boolean autopop) { - this.parent = parent; - this.autopop = autopop; - } - - /** - * Returns the parent source of this source. - * - * Sources form a singly linked list. - */ - /* pp */ final Source getParent() { - return parent; - } - - - // @OverrideMustInvoke - /* pp */ void init(Preprocessor pp) { - setListener(pp.getListener()); - this.werror = pp.getWarnings().contains(Warning.ERROR); - } - - /** - * Sets the listener for this Source. - * - * Normally this is set by the Preprocessor when a Source is - * used, but if you are using a Source as a standalone object, - * you may wish to call this. - */ - public void setListener(PreprocessorListener pl) { - this.listener = pl; - } - - /** - * Returns the File currently being lexed. - * - * If this Source is not a {@link FileLexerSource}, then - * it will ask the parent Source, and so forth recursively. - * If no Source on the stack is a FileLexerSource, returns null. - */ - @CheckForNull - public String getPath() { - Source parent = getParent(); - if (parent != null) - return parent.getPath(); - return null; - } - - /** - * Returns the human-readable name of the current Source. - */ - @CheckForNull - public String getName() { - Source parent = getParent(); - if (parent != null) - return parent.getName(); - return null; - } - - /** - * Returns the current line number within this Source. - */ - @Nonnegative - public int getLine() { - Source parent = getParent(); - if (parent == null) - return 0; - return parent.getLine(); - } - - /** - * Returns the current column number within this Source. - */ - public int getColumn() { - Source parent = getParent(); - if (parent == null) - return 0; - return parent.getColumn(); - } - - /** - * Returns true if this Source is expanding the given macro. - * - * This is used to prevent macro recursion. - */ - /* pp */ boolean isExpanding(@Nonnull Macro m) { - Source parent = getParent(); - if (parent != null) - return parent.isExpanding(m); - return false; - } - - /** - * Returns true if this Source should be transparently popped - * from the input stack. - * - * Examples of such sources are macro expansions. - */ - /* pp */ boolean isAutopop() { - return autopop; - } - - /** - * Returns true if this source has line numbers. - */ - /* pp */ boolean isNumbered() { - return false; - } - - /* This is an incredibly lazy way of disabling warnings when - * the source is not active. */ - /* pp */ void setActive(boolean b) { - this.active = b; - } - - /* pp */ boolean isActive() { - return active; - } - - /** - * Returns the next Token parsed from this input stream. - * - * @see Token - */ - @Nonnull - public abstract Token token() - throws IOException, - LexerException; - - /** - * Returns a token iterator for this Source. - */ - @Override - public Iterator iterator() { - return new SourceIterator(this); - } - - /** - * Skips tokens until the end of line. - * - * @param white true if only whitespace is permitted on the - * remainder of the line. - * @return the NL token. - */ - @Nonnull - public Token skipline(boolean white) - throws IOException, - LexerException { - for (;;) { - Token tok = token(); - switch (tok.getType()) { - case EOF: - /* There ought to be a newline before EOF. - * At least, in any skipline context. */ - /* XXX Are we sure about this? */ - warning(tok.getLine(), tok.getColumn(), - "No newline before end of file"); - return new Token(NL, - tok.getLine(), tok.getColumn(), - "\n"); - // return tok; - case NL: - /* This may contain one or more newlines. */ - return tok; - case CCOMMENT: - case CPPCOMMENT: - case WHITESPACE: - break; - default: - /* XXX Check white, if required. */ - if (white) - warning(tok.getLine(), tok.getColumn(), - "Unexpected nonwhite token"); - break; - } - } - } - - protected void error(int line, int column, String msg) - throws LexerException { - if (listener != null) - listener.handleError(this, line, column, msg); - else - throw new LexerException("Error at " + line + ":" + column + ": " + msg); - } - - protected void warning(int line, int column, String msg) - throws LexerException { - if (werror) - error(line, column, msg); - else if (listener != null) - listener.handleWarning(this, line, column, msg); - else - throw new LexerException("Warning at " + line + ":" + column + ": " + msg); - } - - public void close() - throws IOException { - } - -} diff --git a/src/main/java/org/anarres/cpp/SourceIterator.java b/src/main/java/org/anarres/cpp/SourceIterator.java deleted file mode 100644 index 74da49b242..0000000000 --- a/src/main/java/org/anarres/cpp/SourceIterator.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import static org.anarres.cpp.Token.EOF; - -import java.io.IOException; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import javax.annotation.Nonnull; - -/** - * An Iterator for {@link Source Sources}, - * returning {@link Token Tokens}. - */ -public class SourceIterator implements Iterator { - - private final Source source; - private Token tok; - - public SourceIterator(@Nonnull Source s) { - this.source = s; - this.tok = null; - } - - /** - * Rethrows IOException inside IllegalStateException. - */ - private void advance() { - try { - if (tok == null) - tok = source.token(); - } catch (LexerException e) { - throw new IllegalStateException(e); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - /** - * Returns true if the enclosed Source has more tokens. - * - * The EOF token is never returned by the iterator. - * @throws IllegalStateException if the Source - * throws a LexerException or IOException - */ - @Override - public boolean hasNext() { - advance(); - return tok.getType() != EOF; - } - - /** - * Returns the next token from the enclosed Source. - * - * The EOF token is never returned by the iterator. - * @throws IllegalStateException if the Source - * throws a LexerException or IOException - */ - @Override - public Token next() { - if (!hasNext()) - throw new NoSuchElementException(); - Token t = this.tok; - this.tok = null; - return t; - } - - /** - * Not supported. - * - * @throws UnsupportedOperationException unconditionally. - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); - } -} diff --git a/src/main/java/org/anarres/cpp/State.java b/src/main/java/org/anarres/cpp/State.java deleted file mode 100644 index b6f3ada293..0000000000 --- a/src/main/java/org/anarres/cpp/State.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -/* pp */ class State { - - boolean parent; - boolean active; - boolean sawElse; - - /* pp */ State() { - this.parent = true; - this.active = true; - this.sawElse = false; - } - - /* pp */ State(State parent) { - this.parent = parent.isParentActive() && parent.isActive(); - this.active = true; - this.sawElse = false; - } - - /* Required for #elif */ - /* pp */ void setParentActive(boolean b) { - this.parent = b; - } - - /* pp */ boolean isParentActive() { - return parent; - } - - /* pp */ void setActive(boolean b) { - this.active = b; - } - - /* pp */ boolean isActive() { - return active; - } - - /* pp */ void setSawElse() { - sawElse = true; - } - - /* pp */ boolean sawElse() { - return sawElse; - } - - @Override - public String toString() { - return "parent=" + parent - + ", active=" + active - + ", sawelse=" + sawElse; - } -} diff --git a/src/main/java/org/anarres/cpp/StringLexerSource.java b/src/main/java/org/anarres/cpp/StringLexerSource.java deleted file mode 100644 index e3b365a95d..0000000000 --- a/src/main/java/org/anarres/cpp/StringLexerSource.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.io.StringReader; - -/** - * A Source for lexing a String. - * - * This class is used by token pasting, but can be used by user - * code. - */ -public class StringLexerSource extends LexerSource { - - /** - * Creates a new Source for lexing the given String. - * - * @param string The input string to lex. - * @param ppvalid true if preprocessor directives are to be - * honoured within the string. - */ - public StringLexerSource(String string, boolean ppvalid) { - super(new StringReader(string), ppvalid); - } - - /** - * Creates a new Source for lexing the given String. - * - * Equivalent to calling new StringLexerSource(string, false). - * - * By default, preprocessor directives are not honoured within - * the string. - * - * @param string The input string to lex. - */ - public StringLexerSource(String string) { - this(string, false); - } - - @Override - public String toString() { - return "string literal"; - } -} diff --git a/src/main/java/org/anarres/cpp/Token.java b/src/main/java/org/anarres/cpp/Token.java deleted file mode 100644 index 7c006af45b..0000000000 --- a/src/main/java/org/anarres/cpp/Token.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import javax.annotation.Nonnull; - -/** - * A Preprocessor token. - * - * @see Preprocessor - */ -public final class Token { - - // public static final int EOF = -1; - private final int type; - private int line; - private int column; - private final Object value; - private final String text; - - public Token(int type, int line, int column, - String text, Object value) { - this.type = type; - this.line = line; - this.column = column; - this.text = text; - this.value = value; - } - - public Token(int type, int line, int column, String text) { - this(type, line, column, text, null); - } - - /* pp */ Token(int type, String text, Object value) { - this(type, -1, -1, text, value); - } - - /* pp */ Token(int type, String text) { - this(type, text, null); - } - - /* pp */ Token(int type) { - this(type, TokenType.getTokenText(type)); - } - - /** - * Returns the semantic type of this token. - * - * @return the semantic type of this token. - * @see #getTokenName(int) - */ - public int getType() { - return type; - } - - /* pp */ void setLocation(int line, int column) { - this.line = line; - this.column = column; - } - - /** - * Returns the line at which this token started. - * - * Lines are numbered from 1. - * - * @return the line at which this token started. - * @see LexerSource#getLine() - */ - // Not @Nonnegative - might not have been assigned? - public int getLine() { - return line; - } - - /** - * Returns the column at which this token started. - * - * Columns are numbered from 0. - * - * @return the column at which this token started. - * @see LexerSource#getColumn() - */ - // Not @Nonnegative - might not have been assigned? - public int getColumn() { - return column; - } - - /** - * Returns the original or generated text of this token. - * - * This is distinct from the semantic value of the token. - * - * @return the original or generated text of this token. - * @see #getValue() - */ - // Not @Nonnull - might not have been assigned? - public String getText() { - return text; - } - - /** - * Returns the semantic value of this token. - * - * For strings, this is the parsed String. - * For integers, this is an Integer object. - * For other token types, as appropriate. - * - * @return the semantic value of this token, or null. - * @see #getText() - */ - // @CheckForNull // Not useful to annotate, as we have usually checked the type before calling this. - public Object getValue() { - return value; - } - - /** - * Returns a description of this token, for debugging purposes. - */ - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - - buf.append('[').append(getTokenName(type)); - if (line != -1) { - buf.append('@').append(line); - if (column != -1) - buf.append(',').append(column); - } - buf.append("]:"); - if (text != null) - buf.append('"').append(text).append('"'); - else if (type > 3 && type < 256) - buf.append((char) type); - else - buf.append('<').append(type).append('>'); - if (value != null) - buf.append('=').append(value); - return buf.toString(); - } - - /** - * Returns the descriptive name of the given token type. - * - * This is mostly used for stringification and debugging. - * - * @param type The type constant from this class to name. - * @return the descriptive name of the given token type. - * @see Token#getType() - */ - @Nonnull - public static String getTokenName(int type) { - return TokenType.getTokenName(type); - } - - public static final int AND_EQ = 257; - public static final int ARROW = 258; - public static final int CHARACTER = 259; - public static final int CCOMMENT = 260; - public static final int CPPCOMMENT = 261; - public static final int DEC = 262; - public static final int DIV_EQ = 263; - public static final int ELLIPSIS = 264; - public static final int EOF = 265; - public static final int EQ = 266; - public static final int GE = 267; - public static final int HASH = 268; - public static final int HEADER = 269; - public static final int IDENTIFIER = 270; - public static final int INC = 271; - public static final int NUMBER = 272; - public static final int LAND = 273; - public static final int LAND_EQ = 274; - public static final int LE = 275; - public static final int LITERAL = 276; - public static final int LOR = 277; - public static final int LOR_EQ = 278; - public static final int LSH = 279; - public static final int LSH_EQ = 280; - public static final int MOD_EQ = 281; - public static final int MULT_EQ = 282; - public static final int NE = 283; - public static final int NL = 284; - public static final int OR_EQ = 285; - public static final int PASTE = 286; - public static final int PLUS_EQ = 287; - public static final int RANGE = 288; - public static final int RSH = 289; - public static final int RSH_EQ = 290; - public static final int SQSTRING = 291; - public static final int STRING = 292; - public static final int SUB_EQ = 293; - public static final int WHITESPACE = 294; - public static final int XOR_EQ = 295; - public static final int M_ARG = 296; - public static final int M_PASTE = 297; - public static final int M_STRING = 298; - public static final int P_LINE = 299; - public static final int INVALID = 300; - - /** The position-less space token. */ - /* pp */ static final Token space = new Token(WHITESPACE, -1, -1, " "); -} diff --git a/src/main/java/org/anarres/cpp/TokenSnifferSource.java b/src/main/java/org/anarres/cpp/TokenSnifferSource.java deleted file mode 100644 index 0f31d33061..0000000000 --- a/src/main/java/org/anarres/cpp/TokenSnifferSource.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import static org.anarres.cpp.Token.EOF; - -import java.io.IOException; -import java.util.List; - -@Deprecated -/* pp */ class TokenSnifferSource extends Source { - - private final List target; - - /* pp */ TokenSnifferSource(List target) { - this.target = target; - } - - public Token token() - throws IOException, - LexerException { - Token tok = getParent().token(); - if (tok.getType() != EOF) - target.add(tok); - return tok; - } - - @Override - public String toString() { - return getParent().toString(); - } -} diff --git a/src/main/java/org/anarres/cpp/TokenType.java b/src/main/java/org/anarres/cpp/TokenType.java deleted file mode 100644 index e13e982505..0000000000 --- a/src/main/java/org/anarres/cpp/TokenType.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.anarres.cpp; - -import static org.anarres.cpp.Token.AND_EQ; -import static org.anarres.cpp.Token.ARROW; -import static org.anarres.cpp.Token.CCOMMENT; -import static org.anarres.cpp.Token.CHARACTER; -import static org.anarres.cpp.Token.CPPCOMMENT; -import static org.anarres.cpp.Token.DEC; -import static org.anarres.cpp.Token.DIV_EQ; -import static org.anarres.cpp.Token.ELLIPSIS; -import static org.anarres.cpp.Token.EOF; -import static org.anarres.cpp.Token.EQ; -import static org.anarres.cpp.Token.GE; -import static org.anarres.cpp.Token.HASH; -import static org.anarres.cpp.Token.HEADER; -import static org.anarres.cpp.Token.IDENTIFIER; -import static org.anarres.cpp.Token.INC; -import static org.anarres.cpp.Token.INVALID; -import static org.anarres.cpp.Token.LAND; -import static org.anarres.cpp.Token.LAND_EQ; -import static org.anarres.cpp.Token.LE; -import static org.anarres.cpp.Token.LITERAL; -import static org.anarres.cpp.Token.LOR; -import static org.anarres.cpp.Token.LOR_EQ; -import static org.anarres.cpp.Token.LSH; -import static org.anarres.cpp.Token.LSH_EQ; -import static org.anarres.cpp.Token.MOD_EQ; -import static org.anarres.cpp.Token.MULT_EQ; -import static org.anarres.cpp.Token.M_ARG; -import static org.anarres.cpp.Token.M_PASTE; -import static org.anarres.cpp.Token.M_STRING; -import static org.anarres.cpp.Token.NE; -import static org.anarres.cpp.Token.NL; -import static org.anarres.cpp.Token.NUMBER; -import static org.anarres.cpp.Token.OR_EQ; -import static org.anarres.cpp.Token.PASTE; -import static org.anarres.cpp.Token.PLUS_EQ; -import static org.anarres.cpp.Token.P_LINE; -import static org.anarres.cpp.Token.RANGE; -import static org.anarres.cpp.Token.RSH; -import static org.anarres.cpp.Token.RSH_EQ; -import static org.anarres.cpp.Token.SQSTRING; -import static org.anarres.cpp.Token.STRING; -import static org.anarres.cpp.Token.SUB_EQ; -import static org.anarres.cpp.Token.WHITESPACE; -import static org.anarres.cpp.Token.XOR_EQ; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; - -/** - * - * @author shevek - */ -/* pp */ class TokenType { - - private static final List TYPES = new ArrayList(); - - private static void addTokenType(@Nonnegative int type, @Nonnull String name, @CheckForNull String text) { - while (TYPES.size() <= type) - TYPES.add(null); - TYPES.set(type, new TokenType(name, text)); - } - - private static void addTokenType(@Nonnegative int type, @Nonnull String name) { - addTokenType(type, name, null); - } - - @CheckForNull - public static TokenType getTokenType(@Nonnegative int type) { - try { - return TYPES.get(type); - } catch (IndexOutOfBoundsException e) { - return null; - } - } - - @Nonnull - public static String getTokenName(@Nonnegative int type) { - if (type < 0) - return "Invalid" + type; - TokenType tokenType = getTokenType(type); - if (tokenType == null) - return "Unknown" + type; - return tokenType.getName(); - } - - @CheckForNull - public static String getTokenText(@Nonnegative int type) { - TokenType tokenType = getTokenType(type); - if (tokenType == null) - return null; - return tokenType.getText(); - } - - static { - for (int i = 0; i < 255; i++) { - String text = String.valueOf((char) i); - addTokenType(i, text, text); - } - addTokenType(AND_EQ, "AND_EQ", "&="); - addTokenType(ARROW, "ARROW", "->"); - addTokenType(CHARACTER, "CHARACTER"); - addTokenType(CCOMMENT, "CCOMMENT"); - addTokenType(CPPCOMMENT, "CPPCOMMENT"); - addTokenType(DEC, "DEC", "--"); - addTokenType(DIV_EQ, "DIV_EQ", "/="); - addTokenType(ELLIPSIS, "ELLIPSIS", "..."); - addTokenType(EOF, "EOF"); - addTokenType(EQ, "EQ", "=="); - addTokenType(GE, "GE", ">="); - addTokenType(HASH, "HASH", "#"); - addTokenType(HEADER, "HEADER"); - addTokenType(IDENTIFIER, "IDENTIFIER"); - addTokenType(INC, "INC", "++"); - addTokenType(NUMBER, "NUMBER"); - addTokenType(LAND, "LAND", "&&"); - addTokenType(LAND_EQ, "LAND_EQ", "&&="); - addTokenType(LE, "LE", "<="); - addTokenType(LITERAL, "LITERAL"); - addTokenType(LOR, "LOR", "||"); - addTokenType(LOR_EQ, "LOR_EQ", "||="); - addTokenType(LSH, "LSH", "<<"); - addTokenType(LSH_EQ, "LSH_EQ", "<<="); - addTokenType(MOD_EQ, "MOD_EQ", "%="); - addTokenType(MULT_EQ, "MULT_EQ", "*="); - addTokenType(NE, "NE", "!="); - addTokenType(NL, "NL"); - addTokenType(OR_EQ, "OR_EQ", "|="); - addTokenType(PASTE, "PASTE", "##"); - addTokenType(PLUS_EQ, "PLUS_EQ", "+="); - addTokenType(RANGE, "RANGE", ".."); - addTokenType(RSH, "RSH", ">>"); - addTokenType(RSH_EQ, "RSH_EQ", ">>="); - addTokenType(SQSTRING, "SQSTRING"); - addTokenType(STRING, "STRING"); - addTokenType(SUB_EQ, "SUB_EQ", "-="); - addTokenType(WHITESPACE, "WHITESPACE"); - addTokenType(XOR_EQ, "XOR_EQ", "^="); - addTokenType(M_ARG, "M_ARG"); - addTokenType(M_PASTE, "M_PASTE"); - addTokenType(M_STRING, "M_STRING"); - addTokenType(P_LINE, "P_LINE"); - addTokenType(INVALID, "INVALID"); - } - - private final String name; - private final String text; - - /* pp */ TokenType(@Nonnull String name, @CheckForNull String text) { - this.name = name; - this.text = text; - } - - @Nonnull - public String getName() { - return name; - } - - @CheckForNull - public String getText() { - return text; - } -} diff --git a/src/main/java/org/anarres/cpp/VirtualFile.java b/src/main/java/org/anarres/cpp/VirtualFile.java deleted file mode 100644 index f60c80152e..0000000000 --- a/src/main/java/org/anarres/cpp/VirtualFile.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import java.io.IOException; - -import javax.annotation.CheckForNull; -import javax.annotation.Nonnull; - -/** - * An extremely lightweight virtual file interface. - */ -public interface VirtualFile { - - // public String getParent(); - public boolean isFile(); - - @Nonnull - public String getPath(); - - @Nonnull - public String getName(); - - @CheckForNull - public VirtualFile getParentFile(); - - @Nonnull - public VirtualFile getChildFile(String name); - - @Nonnull - public Source getSource() throws IOException; -} diff --git a/src/main/java/org/anarres/cpp/VirtualFileSystem.java b/src/main/java/org/anarres/cpp/VirtualFileSystem.java deleted file mode 100644 index 9d04857b6e..0000000000 --- a/src/main/java/org/anarres/cpp/VirtualFileSystem.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -import javax.annotation.Nonnull; - -/** - * An extremely lightweight virtual file system interface. - */ -public interface VirtualFileSystem { - - @Nonnull - public VirtualFile getFile(@Nonnull String path); - - @Nonnull - public VirtualFile getFile(@Nonnull String dir, @Nonnull String name); -} diff --git a/src/main/java/org/anarres/cpp/Warning.java b/src/main/java/org/anarres/cpp/Warning.java deleted file mode 100644 index de1b8b6ab7..0000000000 --- a/src/main/java/org/anarres/cpp/Warning.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Anarres C Preprocessor - * Copyright (c) 2007-2015, Shevek - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -package org.anarres.cpp; - -/** - * Warning classes which may optionally be emitted by the Preprocessor. - */ -public enum Warning { - - TRIGRAPHS, - // TRADITIONAL, - IMPORT, - UNDEF, - UNUSED_MACROS, - ENDIF_LABELS, - ERROR, - // SYSTEM_HEADERS -} diff --git a/src/main/java/repack/apache/commons/collections4/ArrayStack.java b/src/main/java/repack/apache/commons/collections4/ArrayStack.java deleted file mode 100644 index fb8db818f3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/ArrayStack.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - * {@code ArrayList} instead of a {@code Vector}, so it is not - * synchronized to protect against multithreaded 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 {@code 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 {@code Stack}, {@code ArrayStack} accepts null entries. - *

- * Note: From version 4.0 onwards, this class does not implement the - * removed {@code Buffer} interface anymore. - *

- * - * @param the type of elements in this list - * @see java.util.Stack - * @since 1.0 - * @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 {@code ArrayStack}. The initial size - * is controlled by {@code ArrayList} and is currently 10. - */ - public ArrayStack() { - } - - /** - * Constructs a new empty {@code 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 {@code true} if this stack is currently empty. - *

- * This method exists for compatibility with {@code java.util.Stack}. - * New users of this class should use {@code 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(); - } - 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(); - } - 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(); - } - 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 {@code 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 {@code 1}. If the object is not - * present on the stack, return {@code -1} instead. The - * {@code 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/ArrayUtils.java b/src/main/java/repack/apache/commons/collections4/ArrayUtils.java deleted file mode 100644 index 72a546847a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/ArrayUtils.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package repack.apache.commons.collections4; - -/** - *

- * Operations on arrays, primitive arrays (like {@code int[]}) and primitive wrapper arrays (like {@code Integer[]}). - *

- *

- * This class tries to handle {@code null} input gracefully. An exception will not be thrown for a {@code null} array - * input. However, an Object array that contains a {@code null} element may throw an exception. Each method documents - * its behavior. - *

- *

- * Package private, might move to an internal package if this needs to be public. - *

- *

- * #ThreadSafe# - *

- * - * @since 4.2 (Copied from Apache Commons Lang.) - * - */ -class ArrayUtils { - - - /** - * Don't allow instances. - */ - private ArrayUtils() {} - /** - *

- * Checks if the object is in the given array. - *

- * - *

- * The method returns {@code false} if a {@code null} array is passed in. - *

- * - * @param array - * the array to search through - * @param objectToFind - * the object to find - * @return {@code true} if the array contains the object - */ - static boolean contains(final Object[] array, final Object objectToFind) { - return indexOf(array, objectToFind) != CollectionUtils.INDEX_NOT_FOUND; - } - - /** - *

- * Finds the index of the given object in the array. - *

- * - *

- * This method returns {@link CollectionUtils#INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array. - *

- * - * @param array - * the array to search through for the object, may be {@code null} - * @param objectToFind - * the object to find, may be {@code null} - * @return the index of the object within the array, {@link CollectionUtils#INDEX_NOT_FOUND} ({@code -1}) if not found or - * {@code null} array input - */ - static int indexOf(final T[] array, final Object objectToFind) { - return indexOf(array, objectToFind, 0); - } - - /** - *

- * Finds the index of the given object in the array starting at the given index. - *

- * - *

- * This method returns {@link CollectionUtils#INDEX_NOT_FOUND} ({@code -1}) for a {@code null} input array. - *

- * - *

- * A negative startIndex is treated as zero. A startIndex larger than the array length will return - * {@link CollectionUtils#INDEX_NOT_FOUND} ({@code -1}). - *

- * - * @param array - * the array to search through for the object, may be {@code null} - * @param objectToFind - * the object to find, may be {@code null} - * @param startIndex - * the index to start searching at - * @return the index of the object within the array starting at the index, {@link CollectionUtils#INDEX_NOT_FOUND} ({@code -1}) if - * not found or {@code null} array input - */ - static int indexOf(final Object[] array, final Object objectToFind, int startIndex) { - if (array == null) { - return CollectionUtils.INDEX_NOT_FOUND; - } - if (startIndex < 0) { - startIndex = 0; - } - if (objectToFind == null) { - for (int i = startIndex; i < array.length; i++) { - if (array[i] == null) { - return i; - } - } - } else { - for (int i = startIndex; i < array.length; i++) { - if (objectToFind.equals(array[i])) { - return i; - } - } - } - return CollectionUtils.INDEX_NOT_FOUND; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/Bag.java b/src/main/java/repack/apache/commons/collections4/Bag.java deleted file mode 100644 index 9974966cf4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/Bag.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 {@code {a, a, b, c}}. - * Calling {@link #getCount(Object)} on {@code a} would return 2, while - * calling {@link #uniqueSet()} would return {@code {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 {@code Collection}. - * The non-compliant methods are clearly marked with "(Violation)". - * Exercise caution when using a bag as a {@code 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 of elements in this bag - * @since 2.0 - */ -public interface Bag extends Collection { - - /** - * Returns the number of occurrences (cardinality) of the given - * object currently in the bag. If the object does not exist in the - * bag, return 0. - * - * @param object the object to search for - * @return the number of occurrences of the object, zero if not found - */ - int getCount(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 {@code true}. Since it sometimes returns - * {@code false}, this method violates the contract. - *

- * - * @param object the object to add - * @return {@code true} if the object was not already in the {@code uniqueSet} - */ - @Override - boolean add(E object); - - /** - * Adds {@code 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 {@code nCopies}. - *

- * - * @param object the object to add - * @param nCopies the number of copies to add - * @return {@code true} if the object was not already in the {@code 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 {@code true} if this call changed the collection - */ - @Override - boolean remove(Object object); - - /** - * Removes {@code 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 {@code 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 - */ - @Override - int size(); - - /** - * (Violation) - * Returns {@code true} if the bag contains all elements in - * the given collection, respecting cardinality. That is, if the - * given collection {@code coll} contains {@code n} copies - * of a given object, calling {@link #getCount(Object)} on that object must - * be {@code >= n} for all {@code n} in {@code 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 {@code true} if the Bag contains all the collection - */ - @Override - boolean containsAll(Collection coll); - - /** - * (Violation) - * Remove all elements represented in the given collection, - * respecting cardinality. That is, if the given collection - * {@code coll} contains {@code n} copies of a given object, - * the bag will have {@code n} fewer copies, assuming the bag - * had at least {@code 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 {@code true} if this call changed the collection - */ - @Override - 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 {@code coll} contains {@code n} copies of a - * given object and the bag has {@code m > n} copies, then - * delete {@code m - n} copies from the bag. In addition, if - * {@code e} is an object in the bag but - * {@code !coll.contains(e)}, then remove {@code 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 {@code true} if this call changed the collection - */ - @Override - 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 - */ - @Override - 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 -// * {@code (e==null ? 0 : e.hashCode()) ^ noOccurrences)}. -// * This hash code definition is compatible with the Set interface. -// * -// * @return the hash code of the Bag -// */ -// int hashCode(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/BagUtils.java b/src/main/java/repack/apache/commons/collections4/BagUtils.java deleted file mode 100644 index b23c44a2fd..0000000000 --- a/src/main/java/repack/apache/commons/collections4/BagUtils.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import repack.apache.commons.collections4.bag.CollectionBag; -import repack.apache.commons.collections4.bag.HashBag; -import repack.apache.commons.collections4.bag.PredicatedBag; -import repack.apache.commons.collections4.bag.PredicatedSortedBag; -import repack.apache.commons.collections4.bag.SynchronizedBag; -import repack.apache.commons.collections4.bag.SynchronizedSortedBag; -import repack.apache.commons.collections4.bag.TransformedBag; -import repack.apache.commons.collections4.bag.TransformedSortedBag; -import repack.apache.commons.collections4.bag.TreeBag; -import repack.apache.commons.collections4.bag.UnmodifiableBag; -import repack.apache.commons.collections4.bag.UnmodifiableSortedBag; - -/** - * Provides utility methods and decorators for {@link Bag} and {@link SortedBag} instances. - * - * @since 2.1 - */ -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<>()); - - /** - * Don't allow instances. - */ - 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 NullPointerException 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 NullPointerException 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 NullPointerException 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 behavior, 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 NullPointerException 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 NullPointerException 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 NullPointerException 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 NullPointerException 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 NullPointerException 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 behavior, 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 NullPointerException 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 {@code Bag}. - * - * @param the element type - * @return an empty Bag - */ - @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type - public static Bag emptyBag() { - return EMPTY_BAG; - } - - /** - * Get an empty {@code 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; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/BidiMap.java b/src/main/java/repack/apache/commons/collections4/BidiMap.java deleted file mode 100644 index 756ee9b270..0000000000 --- a/src/main/java/repack/apache/commons/collections4/BidiMap.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Set; - -/** - * Defines a map that allows bidirectional lookup between key and values. - *

- * This extended {@code Map} represents a mapping where a key may - * lookup a value and a value may lookup a key with equal ease. - * This interface extends {@code 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 {@code 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 - */ -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 {@code 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 - */ - @Override - 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, {@code null} is returned. - *

- *

- * Implementations should seek to make this method perform equally as well - * as {@code get(Object)}. - *

- * - * @param value the value to find the key for - * @return the mapped key, or {@code 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, {@code null} is returned. - *

- *

- * Implementations should seek to make this method perform equally as well - * as {@code remove(Object)}. - *

- * - * @param value the value to find the key-value pair for - * @return the key that was removed, {@code 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 {@code Map}. - *

- *

- * Implementations should seek to avoid creating a new object every time this - * method is called. See {@code 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 - * {@code remove} operation), the results of the iteration are undefined. - * The set supports element removal, which removes the corresponding - * mapping from the map, via the {@code Iterator.remove}, - * {@code Collection.remove}, {@code removeAll}, - * {@code retainAll} and {@code clear} operations. It does not - * support the {@code add} or {@code addAll} operations. - * - * @return a set view of the values contained in this map - */ - @Override - Set values(); -} diff --git a/src/main/java/repack/apache/commons/collections4/BoundedCollection.java b/src/main/java/repack/apache/commons/collections4/BoundedCollection.java deleted file mode 100644 index 79bbab0cf1..0000000000 --- a/src/main/java/repack/apache/commons/collections4/BoundedCollection.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - * - * @param the type of elements in this collection - * @since 3.0 - */ -public interface BoundedCollection extends Collection { - - /** - * Returns true if this collection is full and no new elements can be added. - * - * @return {@code 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(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/BoundedMap.java b/src/main/java/repack/apache/commons/collections4/BoundedMap.java deleted file mode 100644 index a9adb6a4c8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/BoundedMap.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public interface BoundedMap extends IterableMap { - - /** - * Returns true if this map is full and no new elements can be added. - * - * @return {@code 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(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/Closure.java b/src/main/java/repack/apache/commons/collections4/Closure.java deleted file mode 100644 index eb492d3179..0000000000 --- a/src/main/java/repack/apache/commons/collections4/Closure.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -/** - * Defines a functor interface implemented by classes that do something. - *

- * A {@code 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 - */ -@FunctionalInterface -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); - -} diff --git a/src/main/java/repack/apache/commons/collections4/ClosureUtils.java b/src/main/java/repack/apache/commons/collections4/ClosureUtils.java deleted file mode 100644 index 30e13a2799..0000000000 --- a/src/main/java/repack/apache/commons/collections4/ClosureUtils.java +++ /dev/null @@ -1,375 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Collection; -import java.util.Map; -import java.util.Objects; - -import repack.apache.commons.collections4.functors.ChainedClosure; -import repack.apache.commons.collections4.functors.EqualPredicate; -import repack.apache.commons.collections4.functors.ExceptionClosure; -import repack.apache.commons.collections4.functors.ForClosure; -import repack.apache.commons.collections4.functors.IfClosure; -import repack.apache.commons.collections4.functors.InvokerTransformer; -import repack.apache.commons.collections4.functors.NOPClosure; -import repack.apache.commons.collections4.functors.SwitchClosure; -import repack.apache.commons.collections4.functors.TransformerClosure; -import repack.apache.commons.collections4.functors.WhileClosure; - -/** - * {@code 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 - *
  • Chained - chains two or more closures together - *
  • If - calls one closure or another based on a predicate - *
  • 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 - *
- *

- * Since v4.1 only closures which are considered to be safe are - * Serializable. Closures considered to be unsafe for serialization are: - *

- *
    - *
  • Invoker - *
  • For - *
  • While - *
- * - * @since 3.0 - */ -public class ClosureUtils { - - /** - * Don't allow instances. - */ - private ClosureUtils() {} - - /** - * Gets a Closure that always throws an exception. - * This could be useful during testing as a placeholder. - * - * @see repack.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 repack.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 repack.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 {@code count} times. - *

- * A null closure or zero count returns the {@code NOPClosure}. - * - * @see repack.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 {@code 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 repack.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 {@code while} closure - * @throws NullPointerException 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 repack.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 {@code do-while} closure - * @throws NullPointerException 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 repack.apache.commons.collections4.functors.InvokerTransformer - * @see repack.apache.commons.collections4.functors.TransformerClosure - * - * @param the type that the closure acts on - * @param methodName the name of the method - * @return the {@code invoker} closure - * @throws NullPointerException 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 repack.apache.commons.collections4.functors.InvokerTransformer - * @see repack.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 {@code invoker} closure - * @throws NullPointerException 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 repack.apache.commons.collections4.functors.ChainedClosure - * - * @param the type that the closure acts on - * @param closures an array of closures to chain - * @return the {@code chained} closure - * @throws NullPointerException if the closures array is null - * @throws NullPointerException 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 repack.apache.commons.collections4.functors.ChainedClosure - * - * @param the type that the closure acts on - * @param closures a collection of closures to chain - * @return the {@code chained} closure - * @throws NullPointerException if the closures collection is null - * @throws NullPointerException if any closure in the collection is null - * @throws IllegalArgumentException if the closures collection is empty - */ - 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 repack.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 {@code if} closure - * @throws NullPointerException if the predicate or 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 repack.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 {@code switch} closure - * @throws NullPointerException if the predicate or 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 repack.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 {@code switch} closure - * @throws NullPointerException if either array is null - * @throws NullPointerException if any element in the arrays is null - * @throws IllegalArgumentException if the arrays have 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 repack.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 {@code switch} closure - * @throws NullPointerException if either array is null - * @throws NullPointerException 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 repack.apache.commons.collections4.functors.SwitchClosure - * - * @param the type that the closure acts on - * @param predicatesAndClosures a map of predicates to closures - * @return the {@code switch} closure - * @throws NullPointerException if the map is null - * @throws NullPointerException if any closure in the map is null - * @throws IllegalArgumentException if the map is empty - * @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 repack.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 NullPointerException if the map is null - * @throws NullPointerException if any closure in the map is null - * @throws IllegalArgumentException if the map is empty - */ - @SuppressWarnings("unchecked") - public static Closure switchMapClosure(final Map> objectsAndClosures) { - Objects.requireNonNull(objectsAndClosures, "objectsAndClosures"); - 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/CollectionUtils.java b/src/main/java/repack/apache/commons/collections4/CollectionUtils.java deleted file mode 100644 index 9e3c789ace..0000000000 --- a/src/main/java/repack/apache/commons/collections4/CollectionUtils.java +++ /dev/null @@ -1,2156 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.bag.HashBag; -import repack.apache.commons.collections4.collection.PredicatedCollection; -import repack.apache.commons.collections4.collection.SynchronizedCollection; -import repack.apache.commons.collections4.collection.TransformedCollection; -import repack.apache.commons.collections4.collection.UnmodifiableBoundedCollection; -import repack.apache.commons.collections4.collection.UnmodifiableCollection; -import repack.apache.commons.collections4.functors.TruePredicate; -import repack.apache.commons.collections4.iterators.CollatingIterator; -import repack.apache.commons.collections4.iterators.PermutationIterator; - -/** - * Provides utility methods and decorators for {@link Collection} instances. - *

- * Various utility methods might put the input objects into a Set/Map/Bag. In case - * the input objects override {@link Object#equals(Object)}, it is mandatory that - * the general contract of the {@link Object#hashCode()} method is maintained. - *

- *

- * NOTE: From 4.0, method parameters will take {@link Iterable} objects when possible. - *

- * - * @since 1.0 - */ -public class CollectionUtils { - - /** - * The index value when an element is not found in a collection or array: {@code -1}. - * - * @since 4.5 - */ - public static final int INDEX_NOT_FOUND = -1; - - /** - * Default prefix used while converting an Iterator to its String representation. - * - * @since 4.5 - */ - public static final String DEFAULT_TOSTRING_PREFIX = "["; - - /** - * Default suffix used while converting an Iterator to its String representation. - * - * @since 4.5 - */ - public static final String DEFAULT_TOSTRING_SUFFIX = "]"; - - /** - * A String for Colon (":"). - * - * @since 4.5 - */ - public static final String COLON = ":"; - /** - * A String for Comma (","). - * - * @since 4.5 - */ - public static final String COMMA = ","; - - /** - * 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 - */ - 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 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 - */ - 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()); - } - - @Override - 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 = Collections.emptyList(); - - /** - * Don't allow instances. - */ - 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 {@code null}, - * or the argument itself otherwise. - * - * @param the element type - * @param collection the collection, possibly {@code null} - * @return an empty collection if the argument is {@code null} - */ - public static Collection emptyIfNull(final Collection collection) { - return collection == null ? CollectionUtils.emptyCollection() : 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 - * @throws NullPointerException if either collection is null - * @see Collection#addAll - */ - public static Collection union(final Iterable a, final Iterable b) { - Objects.requireNonNull(a, "a"); - Objects.requireNonNull(b, "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 - * @throws NullPointerException if either collection is null - * @see Collection#retainAll - * @see #containsAny - */ - public static Collection intersection(final Iterable a, final Iterable b) { - Objects.requireNonNull(a, "a"); - Objects.requireNonNull(b, "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 - * {@code {@link #subtract subtract}({@link #union union(a,b)},{@link #intersection intersection(a,b)})} - * or - * {@code {@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 - * @throws NullPointerException if either collection is null - */ - public static Collection disjunction(final Iterable a, final Iterable b) { - Objects.requireNonNull(a, "a"); - Objects.requireNonNull(b, "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 {@code 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 - * @throws NullPointerException if either collection or p is null - * @since 4.0 - * @see Collection#removeAll - */ - public static Collection subtract(final Iterable a, - final Iterable b, - final Predicate p) { - Objects.requireNonNull(a, "a"); - Objects.requireNonNull(b, "b"); - Objects.requireNonNull(p, "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 {@code 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 {@code 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 {@code true} iff the intersection of the collections has the same cardinality - * as the set of unique elements from the second collection - * @throws NullPointerException if coll1 or coll2 is null - * @since 4.0 - */ - public static boolean containsAll(final Collection coll1, final Collection coll2) { - Objects.requireNonNull(coll1, "coll1"); - Objects.requireNonNull(coll2, "coll2"); - if (coll2.isEmpty()) { - return true; - } - final Set elementsAlreadySeen = new HashSet<>(); - for (final Object nextElement : coll2) { - if (elementsAlreadySeen.contains(nextElement)) { - continue; - } - - boolean foundCurrentElement = false; - for (final Object p : coll1) { - elementsAlreadySeen.add(p); - if (Objects.equals(nextElement, p)) { - foundCurrentElement = true; - break; - } - } - - if (!foundCurrentElement) { - return false; - } - } - return true; - } - - /** - * Returns {@code true} iff at least one element is in both collections. - *

- * In other words, this method returns {@code true} iff the - * {@link #intersection} of coll1 and coll2 is not empty. - *

- * - * @param the type of object to lookup in {@code coll1}. - * @param coll1 the first collection, must not be null - * @param coll2 the second collection, must not be null - * @return {@code true} iff the intersection of the collections is non-empty - * @throws NullPointerException if coll1 or coll2 is null - * @since 4.2 - * @see #intersection - */ - public static boolean containsAny(final Collection coll1, @SuppressWarnings("unchecked") final T... coll2) { - Objects.requireNonNull(coll1, "coll1"); - Objects.requireNonNull(coll2, "coll2"); - if (coll1.size() < coll2.length) { - for (final Object aColl1 : coll1) { - if (ArrayUtils.contains(coll2, aColl1)) { - return true; - } - } - } else { - for (final Object aColl2 : coll2) { - if (coll1.contains(aColl2)) { - return true; - } - } - } - return false; - } - - /** - * Returns {@code true} iff at least one element is in both collections. - *

- * In other words, this method returns {@code 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 {@code true} iff the intersection of the collections is non-empty - * @throws NullPointerException if coll1 or coll2 is null - * @since 2.1 - * @see #intersection - */ - public static boolean containsAny(final Collection coll1, final Collection coll2) { - Objects.requireNonNull(coll1, "coll1"); - Objects.requireNonNull(coll2, "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 <I>. - * @param coll the collection to get the cardinality map for, must not be null - * @return the populated cardinality map - * @throws NullPointerException if coll is null - */ - public static Map getCardinalityMap(final Iterable coll) { - Objects.requireNonNull(coll, "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 {@code 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 {@code true} iff a is a sub-collection of b - * @throws NullPointerException if either collection is null - * @see #isProperSubCollection - * @see Collection#containsAll - */ - public static boolean isSubCollection(final Collection a, final Collection b) { - Objects.requireNonNull(a, "a"); - Objects.requireNonNull(b, "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 {@code 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 - *

- *
    - *
  • {@code a.size()} and {@code b.size()} represent the - * total cardinality of a and b, resp.
  • - *
  • {@code 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 {@code true} iff a is a proper sub-collection of b - * @throws NullPointerException if either collection is null - * @see #isSubCollection - * @see Collection#containsAll - */ - public static boolean isProperSubCollection(final Collection a, final Collection b) { - Objects.requireNonNull(a, "a"); - Objects.requireNonNull(b, "b"); - return a.size() < b.size() && CollectionUtils.isSubCollection(a, b); - } - - /** - * Returns {@code 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 {@code true} iff the collections contain the same elements with the same cardinalities. - * @throws NullPointerException if either collection is null - */ - public static boolean isEqualCollection(final Collection a, final Collection b) { - Objects.requireNonNull(a, "a"); - Objects.requireNonNull(b, "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 {@code 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. - *

- *

- * Note: from version 4.1 onwards this method requires the input - * collections and equator to be of compatible type (using bounded wildcards). - * Providing incompatible arguments (e.g. by casting to their rawtypes) - * will result in a {@code ClassCastException} thrown at runtime. - *

- * - * @param the element type - * @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 {@code true} iff the collections contain the same elements with the same cardinalities. - * @throws NullPointerException if either collection or equator is null - * @since 4.0 - */ - public static boolean isEqualCollection(final Collection a, - final Collection b, - final Equator equator) { - Objects.requireNonNull(a, "a"); - Objects.requireNonNull(b, "b"); - Objects.requireNonNull(equator, "equator"); - - if (a.size() != b.size()) { - return false; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - final Transformer transformer = input -> new EquatorWrapper(equator, input); - - return isEqualCollection(collect(a, transformer), collect(b, transformer)); - } - - /** - * Returns the hash code of the input collection using the hash method of an equator. - * - *

- * Returns 0 if the input collection is {@code null}. - *

- * - * @param the element type - * @param collection the input collection - * @param equator the equator used for generate hashCode - * @return the hash code of the input collection using the hash method of an equator - * @throws NullPointerException if the equator is {@code null} - * @since 4.5 - */ - public static int hashCode(final Collection collection, - final Equator equator) { - Objects.requireNonNull(equator, "equator"); - if (null == collection) { - return 0; - } - int hashCode = 1; - for (final E e : collection) { - hashCode = 31 * hashCode + equator.hash(e); - } - return hashCode; - } - - /** - * 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; - - 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 collection the {@link Iterable} to search - * @param the type of object that the {@link Iterable} may contain. - * @return the number of occurrences of obj in coll - * @throws NullPointerException if collection is null - * @deprecated since 4.1, use {@link IterableUtils#frequency(Iterable, Object)} instead. - * Be aware that the order of parameters has changed. - */ - @Deprecated - public static int cardinality(final O obj, final Iterable collection) { - return IterableUtils.frequency(Objects.requireNonNull(collection, "collection"), obj); - } - - /** - * 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 - * @deprecated since 4.1, use {@link IterableUtils#find(Iterable, Predicate)} instead - */ - @Deprecated - public static T find(final Iterable collection, final Predicate predicate) { - return predicate != null ? IterableUtils.find(collection, predicate) : 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 - * @deprecated since 4.1, use {@link IterableUtils#forEach(Iterable, Closure)} instead - */ - @Deprecated - public static > C forAllDo(final Iterable collection, final C closure) { - if (closure != null) { - IterableUtils.forEach(collection, closure); - } - 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 - * @deprecated since 4.1, use {@link IteratorUtils#forEach(Iterator, Closure)} instead - */ - @Deprecated - public static > C forAllDo(final Iterator iterator, final C closure) { - if (closure != null) { - IteratorUtils.forEach(iterator, closure); - } - 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 - * @deprecated since 4.1, use {@link IterableUtils#forEachButLast(Iterable, Closure)} instead - */ - @Deprecated - public static > T forAllButLastDo(final Iterable collection, - final C closure) { - return closure != null ? IterableUtils.forEachButLast(collection, 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 - * @deprecated since 4.1, use {@link IteratorUtils#forEachButLast(Iterator, Closure)} instead - */ - @Deprecated - public static > T forAllButLastDo(final Iterator iterator, final C closure) { - return closure != null ? IteratorUtils.forEachButLast(iterator, closure) : 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 {@code 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 {@code 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 - * @deprecated since 4.1, use {@link IterableUtils#countMatches(Iterable, Predicate)} instead - */ - @Deprecated - public static int countMatches(final Iterable input, final Predicate predicate) { - return predicate == null ? 0 : (int) IterableUtils.countMatches(input, predicate); - } - - /** - * Answers true if a predicate is true for at least one element of a - * collection. - *

- * A {@code 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 - * @deprecated since 4.1, use {@link IterableUtils#matchesAny(Iterable, Predicate)} instead - */ - @Deprecated - public static boolean exists(final Iterable input, final Predicate predicate) { - return predicate != null && IterableUtils.matchesAny(input, predicate); - } - - /** - * Answers true if a predicate is true for every element of a - * collection. - * - *

- * A {@code null} predicate returns false. - *

- *

- * A {@code 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 - * @deprecated since 4.1, use {@link IterableUtils#matchesAll(Iterable, Predicate)} instead - */ - @Deprecated - public static boolean matchesAll(final Iterable input, final Predicate predicate) { - return predicate != null && IterableUtils.matchesAll(input, predicate); - } - - /** - * Selects all elements from input collection which match the given - * predicate into an output collection. - *

- * A {@code 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) - */ - public static Collection select(final Iterable inputCollection, - final Predicate predicate) { - int size = 0; - if (null != inputCollection) { - size = inputCollection instanceof Collection ? ((Collection) inputCollection).size() : 0; - } - final Collection answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size); - 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 into an output and rejected collection, - * based on the evaluation of the given predicate. - *

- * Elements matching the predicate are added to the {@code outputCollection}, - * all other elements are added to the {@code rejectedCollection}. - *

- *

- * If the input predicate is {@code null}, no elements are added to - * {@code outputCollection} or {@code rejectedCollection}. - *

- *

- * Note: calling the method is equivalent to the following code snippet: - *

- *
-     *   select(inputCollection, predicate, outputCollection);
-     *   selectRejected(inputCollection, predicate, rejectedCollection);
-     * 
- * - * @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 selected elements into, may not be null if the - * inputCollection and predicate are not null - * @param rejectedCollection the collection to output rejected elements into, may not be null if the - * inputCollection or predicate are not null - * @return the outputCollection - * @since 4.1 - */ - public static > R select(final Iterable inputCollection, - final Predicate predicate, final R outputCollection, final R rejectedCollection) { - - if (inputCollection != null && predicate != null) { - for (final O element : inputCollection) { - if (predicate.evaluate(element)) { - outputCollection.add(element); - } else { - rejectedCollection.add(element); - } - } - } - return outputCollection; - } - - /** - * Selects all elements from inputCollection which don't match the given - * predicate into an output collection. - *

- * If the input predicate is {@code 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) - */ - public static Collection selectRejected(final Iterable inputCollection, - final Predicate predicate) { - int size = 0; - if (null != inputCollection) { - size = inputCollection instanceof Collection ? ((Collection) inputCollection).size() : 0; - } - final Collection answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size); - 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 {@code null}, no elements are added to - * {@code 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 containing all elements of the input collection - * transformed by the given transformer. - *

- * If the input collection or 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 outputCollection is null and both, inputCollection and - * transformer are not null - */ - public static Collection collect(final Iterable inputCollection, - final Transformer transformer) { - int size = 0; - if (null != inputCollection) { - size = inputCollection instanceof Collection ? ((Collection) inputCollection).size() : 0; - } - final Collection answer = size == 0 ? new ArrayList<>() : new ArrayList<>(size); - return collect(inputCollection, transformer, answer); - } - - /** - * Transforms all elements from the input iterator with the given transformer - * and adds them to the output collection. - *

- * If the input iterator or 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 inputIterator the iterator to get the input from, may be null - * @param transformer the transformer to use, may be null - * @return the transformed result (new list) - */ - public static Collection collect(final Iterator inputIterator, - final Transformer transformer) { - return collect(inputIterator, transformer, new ArrayList<>()); - } - - /** - * Transforms all elements from input collection with the given transformer - * and adds them to the output collection. - *

- * 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 type of the output collection - * @param inputCollection the collection to get the input from, may be null - * @param transformer the transformer to use, may be null - * @param outputCollection the collection to output into, may not be null if inputCollection - * and transformer are not null - * @return the output collection with the transformed input added - * @throws NullPointerException if the outputCollection 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 input iterator with the given transformer - * and adds them to the output collection. - *

- * If the input iterator 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 type of 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 inputIterator - * and transformer are not null - * @return the outputCollection with the transformed input added - * @throws NullPointerException if the output collection is null and both, inputIterator 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) { - Objects.requireNonNull(collection, "collection"); - 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 iterable is null - */ - public static boolean addAll(final Collection collection, final Iterable iterable) { - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(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) { - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(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) { - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(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 elements is null - */ - public static boolean addAll(final Collection collection, final C... elements) { - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(elements, "elements"); - boolean changed = false; - for (final C element : elements) { - changed |= collection.add(element); - } - return changed; - } - - /** - * Returns the {@code index}-th value in {@link Iterator}, throwing - * {@code IndexOutOfBoundsException} if there is no such element. - *

- * The Iterator is advanced to {@code index} (or to the end, if - * {@code 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 - * @throws NullPointerException if iterator is null - * @deprecated since 4.1, use {@code IteratorUtils.get(Iterator, int)} instead - */ - @Deprecated - public static T get(final Iterator iterator, final int index) { - Objects.requireNonNull(iterator, "iterator"); - return IteratorUtils.get(iterator, index); - } - - /** - * Ensures an index is not negative. - * @param index the index to check. - * @throws IndexOutOfBoundsException if the index is negative. - */ - static void checkIndexBounds(final int index) { - if (index < 0) { - throw new IndexOutOfBoundsException("Index cannot be negative: " + index); - } - } - - /** - * Returns the {@code index}-th value in the {@code iterable}'s {@link Iterator}, throwing - * {@code 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 - * @deprecated since 4.1, use {@code IterableUtils.get(Iterable, int)} instead - */ - @Deprecated - public static T get(final Iterable iterable, final int index) { - Objects.requireNonNull(iterable, "iterable"); - return IterableUtils.get(iterable, index); - } - - /** - * Returns the {@code index}-th value in {@code object}, throwing - * {@code IndexOutOfBoundsException} if there is no such element or - * {@code IllegalArgumentException} if {@code object} is not an - * instance of one of the supported types. - *

- * The supported types, and associated semantics are: - *

- *
    - *
  • Map -- the value returned is the {@code Map.Entry} in position - * {@code index} in the map's {@code entrySet} iterator, - * if there is such an entry.
  • - *
  • List -- this method is equivalent to the list's get method.
  • - *
  • Array -- the {@code index}-th array entry is returned, - * if there is such an entry; otherwise an {@code IndexOutOfBoundsException} - * is thrown.
  • - *
  • Collection -- the value returned is the {@code index}-th object - * returned by the collection's default iterator, if there is such an element.
  • - *
  • Iterator or Enumeration -- the value returned is the - * {@code index}-th object in the Iterator/Enumeration, if there - * is such an element. The Iterator/Enumeration is advanced to - * {@code index} (or to the end, if {@code 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) { - final 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 IteratorUtils.get(iterator, i); - } - if (object instanceof Object[]) { - return ((Object[]) object)[i]; - } - if (object instanceof Iterator) { - final Iterator it = (Iterator) object; - return IteratorUtils.get(it, i); - } - if (object instanceof Iterable) { - final Iterable iterable = (Iterable) object; - return IterableUtils.get(iterable, i); - } - if (object instanceof Enumeration) { - final Enumeration it = (Enumeration) object; - return EnumerationUtils.get(it, i); - } - if (object == null) { - throw new IllegalArgumentException("Unsupported object type: null"); - } - try { - return Array.get(object, i); - } catch (final IllegalArgumentException ex) { - throw new IllegalArgumentException("Unsupported object type: " + object.getClass().getName()); - } - } - - /** - * Returns the {@code index}-th {@code Map.Entry} in the {@code map}'s {@code entrySet}, - * throwing {@code IndexOutOfBoundsException} if there is no such element. - * - * @param the key type in the {@link Map} - * @param the value 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) { - Objects.requireNonNull(map, "map"); - 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 recognized - * @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 Iterable) { - total = IterableUtils.size((Iterable) object); - } else if (object instanceof Object[]) { - total = ((Object[]) object).length; - } else if (object instanceof Iterator) { - total = IteratorUtils.size((Iterator) object); - } 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 recognized - * @since 3.2 - */ - public static boolean sizeIsEmpty(final Object object) { - if (object == null) { - return true; - } - if (object instanceof Collection) { - return ((Collection) object).isEmpty(); - } - if (object instanceof Iterable) { - return IterableUtils.isEmpty((Iterable) object); - } - if (object instanceof Map) { - return ((Map) object).isEmpty(); - } - if (object instanceof Object[]) { - return ((Object[]) object).length == 0; - } - if (object instanceof Iterator) { - return !((Iterator) object).hasNext(); - } - if (object instanceof Enumeration) { - return !((Enumeration) object).hasMoreElements(); - } - 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) { - Objects.requireNonNull(array, "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 collection the collection to check - * @return true if the BoundedCollection is full - * @throws NullPointerException if the collection is null - */ - public static boolean isFull(final Collection collection) { - Objects.requireNonNull(collection, "collection"); - if (collection instanceof BoundedCollection) { - return ((BoundedCollection) collection).isFull(); - } - try { - final BoundedCollection bcoll = - UnmodifiableBoundedCollection.unmodifiableBoundedCollection(collection); - 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 collection 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 collection) { - Objects.requireNonNull(collection, "collection"); - if (collection instanceof BoundedCollection) { - return ((BoundedCollection) collection).maxSize(); - } - try { - final BoundedCollection bcoll = - UnmodifiableBoundedCollection.unmodifiableBoundedCollection(collection); - 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 NullPointerException if either collection is null - * @since 4.0 - */ - public static > List collate(final Iterable a, - final 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 NullPointerException 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 NullPointerException 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 iterableA the first collection, must not be null - * @param iterableB the second collection, must not be null - * @param comparator 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 NullPointerException if either collection or the comparator is null - * @since 4.0 - */ - public static List collate(final Iterable iterableA, final Iterable iterableB, - final Comparator comparator, final boolean includeDuplicates) { - - Objects.requireNonNull(iterableA, "iterableA"); - Objects.requireNonNull(iterableB, "iterableB"); - Objects.requireNonNull(comparator, "comparator"); - - // if both Iterables are a Collection, we can estimate the size - final int totalSize = iterableA instanceof Collection && iterableB instanceof Collection ? - Math.max(1, ((Collection) iterableA).size() + ((Collection) iterableB).size()) : 10; - - final Iterator iterator = new CollatingIterator<>(comparator, iterableA.iterator(), iterableB.iterator()); - if (includeDuplicates) { - return IteratorUtils.toList(iterator, totalSize); - } - 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, must 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) { - Objects.requireNonNull(collection, "collection"); - final PermutationIterator it = new PermutationIterator<>(collection); - final Collection> result = new ArrayList<>(); - while (it.hasNext()) { - result.add(it.next()); - } - return result; - } - - /** - * Returns a collection containing all the elements in {@code collection} - * that are also in {@code retain}. The cardinality of an element {@code e} - * in the returned collection is the same as the cardinality of {@code e} - * in {@code collection} unless {@code retain} does not contain {@code e}, in which - * case the cardinality is zero. This method is useful if you do not wish to modify - * the collection {@code c} and thus cannot call {@code c.retainAll(retain);}. - *

- * This implementation iterates over {@code collection}, checking each element in - * turn to see if it's contained in {@code retain}. If it's contained, it's added - * to the returned list. As a consequence, it is advised to use a collection type for - * {@code retain} that provides a fast (e.g. O(1)) implementation of - * {@link Collection#contains(Object)}. - *

- * - * @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 {@code Collection} containing all the elements of {@code collection} - * that occur at least once in {@code retain}. - * @throws NullPointerException if either parameter is null - * @since 3.2 - */ - public static Collection retainAll(final Collection collection, final Collection retain) { - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(retain, "retain"); - return ListUtils.retainAll(collection, retain); - } - - /** - * Returns a collection containing all the elements in - * {@code collection} that are also in {@code retain}. The - * cardinality of an element {@code e} in the returned collection is - * the same as the cardinality of {@code e} in {@code collection} - * unless {@code retain} does not contain {@code e}, in which case - * the cardinality is zero. This method is useful if you do not wish to - * modify the collection {@code c} and thus cannot call - * {@code c.retainAll(retain);}. - *

- * Moreover this method uses an {@link Equator} instead of - * {@link Object#equals(Object)} to determine the equality of the elements - * in {@code collection} and {@code retain}. Hence this method is - * useful in cases where the equals behavior of an object needs to be - * modified without changing the object itself. - *

- * - * @param the type of object the {@link Collection} contains - * @param collection the collection whose contents are the target of the {@code retainAll} operation - * @param retain the collection containing the elements to be retained in the returned collection - * @param equator the Equator used for testing equality - * @return a {@code Collection} containing all the elements of {@code collection} - * that occur at least once in {@code retain} according to the {@code equator} - * @throws NullPointerException if any of the parameters is null - * @since 4.1 - */ - public static Collection retainAll(final Iterable collection, - final Iterable retain, - final Equator equator) { - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(retain, "retain"); - Objects.requireNonNull(equator, "equator"); - final Transformer> transformer = input -> new EquatorWrapper<>(equator, input); - - final Set> retainSet = - collect(retain, transformer, new HashSet<>()); - - final List list = new ArrayList<>(); - for (final E element : collection) { - if (retainSet.contains(new EquatorWrapper<>(equator, element))) { - list.add(element); - } - } - return list; - } - - /** - * Removes elements whose index are between startIndex, inclusive and endIndex, - * exclusive in the collection and returns them. - * This method modifies the input collections. - * - * @param the type of object the {@link Collection} contains - * @param input the collection will be operated, must not be null - * @param startIndex the start index (inclusive) to remove element, must not be less than 0 - * @param endIndex the end index (exclusive) to remove, must not be less than startIndex - * @return collection of elements that removed from the input collection - * @throws NullPointerException if input is null - * @since 4.5 - */ - public static Collection removeRange(final Collection input, final int startIndex, final int endIndex) { - Objects.requireNonNull(input, "input"); - if (endIndex < startIndex) { - throw new IllegalArgumentException("The end index can't be less than the start index."); - } - if (input.size() < endIndex) { - throw new IndexOutOfBoundsException("The end index can't be greater than the size of collection."); - } - return CollectionUtils.removeCount(input, startIndex, endIndex - startIndex); - } - - /** - * Removes the specified number of elements from the start index in the collection and returns them. - * This method modifies the input collections. - * - * @param the type of object the {@link Collection} contains - * @param input the collection will be operated, can't be null - * @param startIndex the start index (inclusive) to remove element, can't be less than 0 - * @param count the specified number to remove, can't be less than 1 - * @return collection of elements that removed from the input collection - * @throws NullPointerException if input is null - * @since 4.5 - */ - public static Collection removeCount(final Collection input, int startIndex, int count) { - Objects.requireNonNull(input, "input"); - if (startIndex < 0) { - throw new IndexOutOfBoundsException("The start index can't be less than 0."); - } - if (count < 0) { - throw new IndexOutOfBoundsException("The count can't be less than 0."); - } - if (input.size() < startIndex + count) { - throw new IndexOutOfBoundsException( - "The sum of start index and count can't be greater than the size of collection."); - } - - final Collection result = new ArrayList<>(count); - final Iterator iterator = input.iterator(); - while (count > 0) { - if (startIndex > 0) { - startIndex = startIndex - 1; - iterator.next(); - continue; - } - count = count - 1; - result.add(iterator.next()); - iterator.remove(); - } - return result; - } - - /** - * Removes the elements in {@code remove} from {@code collection}. That is, this - * method returns a collection containing all the elements in {@code c} - * that are not in {@code remove}. The cardinality of an element {@code e} - * in the returned collection is the same as the cardinality of {@code e} - * in {@code collection} unless {@code remove} contains {@code e}, in which - * case the cardinality is zero. This method is useful if you do not wish to modify - * the collection {@code c} and thus cannot call {@code collection.removeAll(remove);}. - *

- * This implementation iterates over {@code collection}, checking each element in - * turn to see if it's contained in {@code 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 - * {@code remove} that provides a fast (e.g. O(1)) implementation of - * {@link Collection#contains(Object)}. - *

- * - * @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 {@code collection} - * @return a {@code Collection} containing all the elements of {@code collection} except - * any elements that also occur in {@code 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); - } - - /** - * Removes all elements in {@code remove} from {@code collection}. - * That is, this method returns a collection containing all the elements in - * {@code collection} that are not in {@code remove}. The - * cardinality of an element {@code e} in the returned collection is - * the same as the cardinality of {@code e} in {@code collection} - * unless {@code remove} contains {@code e}, in which case the - * cardinality is zero. This method is useful if you do not wish to modify - * the collection {@code c} and thus cannot call - * {@code collection.removeAll(remove)}. - *

- * Moreover this method uses an {@link Equator} instead of - * {@link Object#equals(Object)} to determine the equality of the elements - * in {@code collection} and {@code remove}. Hence this method is - * useful in cases where the equals behavior of an object needs to be - * modified without changing the object itself. - *

- * - * @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 - * @param equator the Equator used for testing equality - * @return a {@code Collection} containing all the elements of {@code collection} - * except any element that if equal according to the {@code equator} - * @throws NullPointerException if any of the parameters is null - * @since 4.1 - */ - public static Collection removeAll(final Iterable collection, - final Iterable remove, - final Equator equator) { - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(remove, "remove"); - Objects.requireNonNull(equator, "equator"); - final Transformer> transformer = input -> new EquatorWrapper<>(equator, input); - - final Set> removeSet = - collect(remove, transformer, new HashSet<>()); - - final List list = new ArrayList<>(); - for (final E element : collection) { - if (!removeSet.contains(new EquatorWrapper<>(equator, element))) { - list.add(element); - } - } - return list; - } - - /** - * 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 NullPointerException if the collection is null - * @deprecated since 4.1, use {@link java.util.Collections#synchronizedCollection(Collection)} instead - */ - @Deprecated - public static Collection synchronizedCollection(final Collection collection) { - Objects.requireNonNull(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 NullPointerException if the collection is null - * @deprecated since 4.1, use {@link java.util.Collections#unmodifiableCollection(Collection)} instead - */ - @Deprecated - public static Collection unmodifiableCollection(final Collection collection) { - Objects.requireNonNull(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 the type of objects in the Collection. - * @param collection the collection to predicate, must not be null - * @param predicate the predicate for the collection, must not be null - * @return a predicated collection backed by the given collection - * @throws NullPointerException if the collection or predicate is null - */ - public static Collection predicatedCollection(final Collection collection, - final Predicate predicate) { - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(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 behavior, 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 NullPointerException if the collection or transformer is null - */ - public static Collection transformingCollection(final Collection collection, - final Transformer transformer) { - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(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 NullPointerException if collection is null - * @throws IllegalArgumentException if collection is empty or contains more than one element - * @since 4.0 - */ - public static E extractSingleton(final Collection collection) { - Objects.requireNonNull(collection, "collection"); - if (collection.size() != 1) { - throw new IllegalArgumentException("Can extract singleton only when collection size == 1"); - } - return collection.iterator().next(); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/ComparatorUtils.java b/src/main/java/repack/apache/commons/collections4/ComparatorUtils.java deleted file mode 100644 index 9447099738..0000000000 --- a/src/main/java/repack/apache/commons/collections4/ComparatorUtils.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Collection; -import java.util.Comparator; -import java.util.Objects; - -import repack.apache.commons.collections4.comparators.BooleanComparator; -import repack.apache.commons.collections4.comparators.ComparableComparator; -import repack.apache.commons.collections4.comparators.ComparatorChain; -import repack.apache.commons.collections4.comparators.NullComparator; -import repack.apache.commons.collections4.comparators.ReverseComparator; -import repack.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 - * {@code comparators} package. This class merely provides a - * convenient central place if you have use for more than one class - * in the {@code comparators} subpackage. - *

- * - * @since 2.1 - */ -public class ComparatorUtils { - - @SuppressWarnings("rawtypes") - private static final Comparator[] EMPTY_COMPARATOR_ARRAY = {}; - - /** - * Don't allow instances. - */ - 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) { - chain.addComparator(Objects.requireNonNull(comparator, "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(comparators.toArray(EMPTY_COMPARATOR_ARRAY)); - } - - /** - * 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 {@code true}, sort - * {@code true} {@link Boolean}s before - * {@code 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 {@code 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 {@code 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 smallest 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 largest 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/EnumerationUtils.java b/src/main/java/repack/apache/commons/collections4/EnumerationUtils.java deleted file mode 100644 index e43c79d6dc..0000000000 --- a/src/main/java/repack/apache/commons/collections4/EnumerationUtils.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.StringTokenizer; - -import repack.apache.commons.collections4.iterators.EnumerationIterator; -import repack.apache.commons.collections4.iterators.IteratorIterable; - -/** - * Provides utility methods for {@link Enumeration} instances. - * - * @since 3.0 - */ -public class EnumerationUtils { - - /** - * Don't allow instances. - */ - private EnumerationUtils() { - // no instances. - } - - /** - * Creates an {@link Iterable} that wraps an {@link Enumeration}. The returned {@link Iterable} can be used for a - * single iteration. - * - * @param the element type - * @param enumeration the enumeration to use, may not be null - * @return a new, single use {@link Iterable} - * @since 4.5 - */ - public static Iterable asIterable(final Enumeration enumeration) { - return new IteratorIterable<>(new EnumerationIterator<>(enumeration)); - } - - /** - * Returns the {@code index}-th value in the {@link Enumeration}, throwing - * {@code IndexOutOfBoundsException} if there is no such element. - *

- * The Enumeration is advanced to {@code index} (or to the end, if - * {@code index} exceeds the number of entries) as a side effect of this method. - * - * @param e the enumeration to get a value from - * @param index the index to get - * @param the type of object in the {@link Enumeration} - * @return the object at the specified index - * @throws IndexOutOfBoundsException if the index is invalid - * @throws IllegalArgumentException if the object type is invalid - * @since 4.1 - */ - public static T get(final Enumeration e, final int index) { - CollectionUtils.checkIndexBounds(index); - int i = index; - while (e.hasMoreElements()) { - i--; - if (i == -1) { - return e.nextElement(); - } - e.nextElement(); - } - throw new IndexOutOfBoundsException("Entry does not exist: " + i); - } - - /** - * 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 {@code null}. - * @return a list containing all elements of the given enumeration - * @throws NullPointerException if the enumeration parameter is {@code 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/Equator.java b/src/main/java/repack/apache/commons/collections4/Equator.java deleted file mode 100644 index de84a210bd..0000000000 --- a/src/main/java/repack/apache/commons/collections4/Equator.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 Comparable}. - *

- * - * @param the types of object this {@link Equator} can evaluate. - * @since 4.0 - */ -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 repack.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); -} diff --git a/src/main/java/repack/apache/commons/collections4/Factory.java b/src/main/java/repack/apache/commons/collections4/Factory.java deleted file mode 100644 index a52393cdd6..0000000000 --- a/src/main/java/repack/apache/commons/collections4/Factory.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -/** - * Defines a functor interface implemented by classes that create objects. - *

- * A {@code 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 - */ -@FunctionalInterface -public interface Factory { - - /** - * Create a new object. - * - * @return a new object - * @throws FunctorException (runtime) if the factory cannot create an object - */ - T create(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/FactoryUtils.java b/src/main/java/repack/apache/commons/collections4/FactoryUtils.java deleted file mode 100644 index 5e0e53c5c2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/FactoryUtils.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import repack.apache.commons.collections4.functors.ConstantFactory; -import repack.apache.commons.collections4.functors.ExceptionFactory; -import repack.apache.commons.collections4.functors.InstantiateFactory; -import repack.apache.commons.collections4.functors.PrototypeFactory; - -/** - * {@code FactoryUtils} provides reference implementations and utilities - * for the Factory functor interface. The supplied factories are: - *
    - *
  • Prototype - clones a specified object - *
  • Instantiate - creates objects using reflection - *
  • Constant - always returns the same object - *
  • Null - always returns null - *
  • Exception - always throws an exception - *
- *

- * Since v4.1 only factories which are considered to be safe are - * Serializable. Factories considered to be unsafe for serialization are: - *

    - *
  • Prototype - *
  • Instantiate - *
- * - * @since 3.0 - */ -public class FactoryUtils { - - /** - * Don't allow instances. - */ - private FactoryUtils() {} - - /** - * Gets a Factory that always throws an exception. - * This could be useful during testing as a placeholder. - * - * @see repack.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 repack.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 repack.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 {@code 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 repack.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 {@code 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 repack.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 {@code reflection} factory - * @throws NullPointerException 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 repack.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 {@code reflection} factory - * @throws NullPointerException 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/FluentIterable.java b/src/main/java/repack/apache/commons/collections4/FluentIterable.java deleted file mode 100644 index 2f372640e7..0000000000 --- a/src/main/java/repack/apache/commons/collections4/FluentIterable.java +++ /dev/null @@ -1,491 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; - -import repack.apache.commons.collections4.iterators.SingletonIterator; - -/** - * A FluentIterable provides a powerful yet simple API for manipulating - * Iterable instances in a fluent manner. - *

- * A FluentIterable can be created either from an Iterable or from a set - * of elements. The following types of methods are provided: - *

- *
    - *
  • fluent methods which return a new {@code FluentIterable} instance, - * providing a view of the original iterable (e.g. filter(Predicate)); - *
  • conversion methods which copy the FluentIterable's contents into a - * new collection or array (e.g. toList()); - *
  • utility methods which answer questions about the FluentIterable's - * contents (e.g. size(), anyMatch(Predicate)). - *
  • - *
- *

- * The following example outputs the first 3 even numbers in the range [1, 10] - * into a list: - *

- *
- * List<String> result =
- *   FluentIterable
- *       .of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
- *       .filter(new Predicate<Integer>() {
- *                   public boolean evaluate(Integer number) {
- *                        return number % 2 == 0;
- *                   }
- *              )
- *       .transform(TransformerUtils.stringValueTransformer())
- *       .limit(3)
- *       .toList();
- * 
- * The resulting list will contain the following elements: - *
[2, 4, 6]
- * - * @param the element type - * @since 4.1 - */ -public class FluentIterable implements Iterable { - - /** A reference to the wrapped iterable. */ - private final Iterable iterable; - - /** - * Creates a new empty FluentIterable. - * - * @param the element type - * @return a new empty FluentIterable - */ - public static FluentIterable empty() { - return IterableUtils.EMPTY_ITERABLE; - } - - /** - * Creates a new FluentIterable of the single provided element. - *

- * The returned iterable's iterator does not support {@code remove()}. - * - * @param the element type - * @param singleton the singleton element - * @return a new FluentIterable containing the singleton - */ - public static FluentIterable of(final T singleton) { - return of(IteratorUtils.asIterable(new SingletonIterator<>(singleton, false))); - } - - /** - * Creates a new FluentIterable from the provided elements. - *

- * The returned iterable's iterator does not support {@code remove()}. - * - * @param the element type - * @param elements the elements to be contained in the FluentIterable - * @return a new FluentIterable containing the provided elements - */ - public static FluentIterable of(final T... elements) { - return of(Arrays.asList(elements)); - } - - /** - * Construct a new FluentIterable from the provided iterable. If the - * iterable is already an instance of FluentIterable, the instance - * will be returned instead. - *

- * The returned iterable's iterator supports {@code remove()} when the - * corresponding input iterator supports it. - * - * @param the element type - * @param iterable the iterable to wrap into a FluentIterable, may not be null - * @return a new FluentIterable wrapping the provided iterable - * @throws NullPointerException if iterable is null - */ - public static FluentIterable of(final Iterable iterable) { - IterableUtils.checkNotNull(iterable); - if (iterable instanceof FluentIterable) { - return (FluentIterable) iterable; - } - return new FluentIterable<>(iterable); - } - - /** - * Don't allow instances. - */ - FluentIterable() { - this.iterable = this; - } - - /** - * Create a new FluentIterable by wrapping the provided iterable. - * @param iterable the iterable to wrap - */ - private FluentIterable(final Iterable iterable) { - this.iterable = iterable; - } - - /** - * Returns a new FluentIterable whose iterator will first traverse - * the elements of the current iterable, followed by the provided - * elements. - * - * @param elements the elements to append to the iterable - * @return a new iterable, combining this iterable with the elements - */ - public FluentIterable append(final E... elements) { - return append(Arrays.asList(elements)); - } - - /** - * Returns a new FluentIterable whose iterator will first traverse - * the elements of the current iterable, followed by the elements - * of the provided iterable. - * - * @param other the other iterable to combine, may not be null - * @return a new iterable, combining this iterable with other - * @throws NullPointerException if other is null - */ - public FluentIterable append(final Iterable other) { - return of(IterableUtils.chainedIterable(iterable, other)); - } - - /** - * Returns a new FluentIterable whose iterator will traverse the - * elements of the current and provided iterable in natural order. - *

- * Example: natural ordering - *

    - *
  • this contains elements [1, 3, 5, 7] - *
  • other contains elements [2, 4, 6, 8] - *
- *

- * The returned iterable will traverse the elements in the following - * order: [1, 2, 3, 4, 5, 6, 7, 8] - * - * @param other the other iterable to collate, may not be null - * @return a new iterable, collating this iterable with the other in natural order - * @throws NullPointerException if other is null - * @see repack.apache.commons.collections4.iterators.CollatingIterator - */ - public FluentIterable collate(final Iterable other) { - return of(IterableUtils.collatedIterable(iterable, other)); - } - - /** - * Returns a new FluentIterable whose iterator will traverse the - * elements of the current and provided iterable according to the - * ordering defined by a comparator. - *

- * Example: descending order - *

    - *
  • this contains elements [7, 5, 3, 1] - *
  • other contains elements [8, 6, 4, 2] - *
- *

- * The returned iterable will traverse the elements in the following - * order: [8, 7, 6, 5, 4, 3, 2, 1] - * - * @param comparator the comparator to define an ordering, may be null, - * in which case natural ordering will be used - * @param other the other iterable to collate, may not be null - * @return a new iterable, collating this iterable with the other in natural order - * @throws NullPointerException if other is null - * @see repack.apache.commons.collections4.iterators.CollatingIterator - */ - public FluentIterable collate(final Iterable other, - final Comparator comparator) { - return of(IterableUtils.collatedIterable(comparator, iterable, other)); - } - - /** - * This method fully traverses an iterator of this iterable and returns - * a new iterable with the same contents, but without any reference - * to the originating iterables and/or iterators. - *

- * Calling this method is equivalent to: - *

-     *   FluentIterable<E> someIterable = ...;
-     *   FluentIterable.of(someIterable.toList());
-     * 
- * - * @return a new iterable with the same contents as this iterable - */ - public FluentIterable eval() { - return of(toList()); - } - - /** - * Returns a new FluentIterable whose iterator will only return - * elements from this iterable matching the provided predicate. - * - * @param predicate the predicate used to filter elements - * @return a new iterable, providing a filtered view of this iterable - * @throws NullPointerException if predicate is null - */ - public FluentIterable filter(final Predicate predicate) { - return of(IterableUtils.filteredIterable(iterable, predicate)); - } - - /** - * Returns a new FluentIterable whose iterator will return at most - * the provided maximum number of elements from this iterable. - * - * @param maxSize the maximum number of elements - * @return a new iterable, providing a bounded view of this iterable - * @throws IllegalArgumentException if maxSize is negative - */ - public FluentIterable limit(final long maxSize) { - return of(IterableUtils.boundedIterable(iterable, maxSize)); - } - - /** - * Returns a new FluentIterable whose iterator will loop infinitely - * over the elements from this iterable. - * - * @return a new iterable, providing a looping view of this iterable - */ - public FluentIterable loop() { - return of(IterableUtils.loopingIterable(iterable)); - } - - /** - * Returns a new FluentIterable whose iterator will traverse the - * elements from this iterable in reverse order. - * - * @return a new iterable, providing a reversed view of this iterable - */ - public FluentIterable reverse() { - return of(IterableUtils.reversedIterable(iterable)); - } - - /** - * Returns a new FluentIterable whose iterator will skip the first - * N elements from this iterable. - * - * @param elementsToSkip the number of elements to skip - * @return a new iterable, providing a view of this iterable by skipping - * the first N elements - * @throws IllegalArgumentException if elementsToSkip is negative - */ - public FluentIterable skip(final long elementsToSkip) { - return of(IterableUtils.skippingIterable(iterable, elementsToSkip)); - } - - /** - * Returns a new FluentIterable whose iterator will return all elements - * of this iterable transformed by the provided transformer. - * - * @param the output element type - * @param transformer the transformer applied to each element - * @return a new iterable, providing a transformed view of this iterable - * @throws NullPointerException if transformer is null - */ - public FluentIterable transform(final Transformer transformer) { - return of(IterableUtils.transformedIterable(iterable, transformer)); - } - - /** - * Returns a new FluentIterable whose iterator will return a unique view - * of this iterable. - * - * @return a new iterable, providing a unique view of this iterable - */ - public FluentIterable unique() { - return of(IterableUtils.uniqueIterable(iterable)); - } - - /** - * Returns a new FluentIterable whose iterator will return an unmodifiable - * view of this iterable. - * - * @return a new iterable, providing an unmodifiable view of this iterable - */ - public FluentIterable unmodifiable() { - return of(IterableUtils.unmodifiableIterable(iterable)); - } - - /** - * Returns a new FluentIterable whose iterator will traverse - * the elements of this iterable and the other iterable in - * alternating order. - * - * @param other the other iterable to interleave, may not be null - * @return a new iterable, interleaving this iterable with others - * @throws NullPointerException if other is null - */ - public FluentIterable zip(final Iterable other) { - return of(IterableUtils.zippingIterable(iterable, other)); - } - - /** - * Returns a new FluentIterable whose iterator will traverse - * the elements of this iterable and the other iterables in - * alternating order. - * - * @param others the iterables to interleave, may not be null - * @return a new iterable, interleaving this iterable with others - * @throws NullPointerException if either of the provided iterables is null - */ - public FluentIterable zip(final Iterable... others) { - return of(IterableUtils.zippingIterable(iterable, others)); - } - - /** {@inheritDoc} */ - @Override - public Iterator iterator() { - return iterable.iterator(); - } - - /** - * Returns an Enumeration that will enumerate all elements contained - * in this iterable. - * - * @return an Enumeration over the elements of this iterable - */ - public Enumeration asEnumeration() { - return IteratorUtils.asEnumeration(iterator()); - } - - /** - * Checks if all elements contained in this iterable are matching the - * provided predicate. - *

- * A {@code null} or empty iterable returns true. - * - * @param predicate the predicate to use, may not be null - * @return true if all elements contained in this iterable match the predicate, - * false otherwise - * @throws NullPointerException if predicate is null - */ - public boolean allMatch(final Predicate predicate) { - return IterableUtils.matchesAll(iterable, predicate); - } - - /** - * Checks if this iterable contains any element matching the provided predicate. - *

- * A {@code null} or empty iterable returns false. - * - * @param predicate the predicate to use, may not be null - * @return true if at least one element contained in this iterable matches the predicate, - * false otherwise - * @throws NullPointerException if predicate is null - */ - public boolean anyMatch(final Predicate predicate) { - return IterableUtils.matchesAny(iterable, predicate); - } - - /** - * Checks if this iterable is empty. - * - * @return true if this iterable does not contain any elements, false otherwise - */ - public boolean isEmpty() { - return IterableUtils.isEmpty(iterable); - } - - /** - * Checks if the object is contained in this iterable. - * - * @param object the object to check - * @return true if the object is contained in this iterable, false otherwise - */ - public boolean contains(final Object object) { - return IterableUtils.contains(iterable, object); - } - - /** - * Applies the closure to all elements contained in this iterable. - * - * @param closure the closure to apply to each element, may not be null - * @throws NullPointerException if closure is null - */ - public void forEach(final Closure closure) { - IterableUtils.forEach(iterable, closure); - } - - /** - * Returns the element at the provided position in this iterable. - * In order to return the element, an iterator needs to be traversed - * up to the requested position. - * - * @param position the position of the element to return - * @return the element - * @throws IndexOutOfBoundsException if the provided position is outside the - * valid range of this iterable: [0, size) - */ - public E get(final int position) { - return IterableUtils.get(iterable, position); - } - - /** - * Returns the number of elements that are contained in this iterable. - * In order to determine the size, an iterator needs to be traversed. - * - * @return the size of this iterable - */ - public int size() { - return IterableUtils.size(iterable); - } - - /** - * Traverses an iterator of this iterable and adds all elements - * to the provided collection. - * - * @param collection the collection to add the elements - * @throws NullPointerException if collection is null - */ - public void copyInto(final Collection collection) { - Objects.requireNonNull(collection, "collection"); - CollectionUtils.addAll(collection, iterable); - } - - /** - * Returns an array containing all elements of this iterable by traversing - * its iterator. - * - * @param arrayClass the class of array to create - * @return an array of the iterable contents - * @throws ArrayStoreException if arrayClass is invalid - */ - public E[] toArray(final Class arrayClass) { - return IteratorUtils.toArray(iterator(), arrayClass); - } - - /** - * Returns a mutable list containing all elements of this iterable - * by traversing its iterator. - *

- * The returned list is guaranteed to be mutable. - * - * @return a list of the iterable contents - */ - public List toList() { - return IterableUtils.toList(iterable); - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return IterableUtils.toString(iterable); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/FunctorException.java b/src/main/java/repack/apache/commons/collections4/FunctorException.java deleted file mode 100644 index a9ca5cfdd4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/FunctorException.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -/** - * Runtime exception thrown from functors. - * If required, a root cause error can be wrapped within this one. - * - * @since 3.0 - */ -public class FunctorException extends RuntimeException { - - /** Serialization version */ - private static final long serialVersionUID = -4704772662059351193L; - - /** - * Constructs a new {@code FunctorException} without specified - * detail message. - */ - public FunctorException() { - } - - /** - * Constructs a new {@code FunctorException} with specified - * detail message. - * - * @param msg the error message. - */ - public FunctorException(final String msg) { - super(msg); - } - - /** - * Constructs a new {@code FunctorException} with specified - * nested {@code 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 {@code FunctorException} with specified - * detail message and nested {@code 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/Get.java b/src/main/java/repack/apache/commons/collections4/Get.java deleted file mode 100644 index 9b3d6f7d16..0000000000 --- a/src/main/java/repack/apache/commons/collections4/Get.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Collection; -import java.util.Set; - -/** - * The "read" subset of the {@link java.util.Map} interface. - * - * @param the type of the keys in this map - * @param the type of the values in this map - * - * @since 4.0 - * @see Put - */ -public interface Get { - - /** - * @param key key whose presence in this map is to be tested - * @return {@code true} if this map contains a mapping for the specified - * key - * @see java.util.Map#containsKey(Object) - */ - boolean containsKey(Object key); - - /** - * @param value value whose presence in this map is to be tested - * @return {@code true} if this map maps one or more keys to the - * specified value - * @see java.util.Map#containsValue(Object) - */ - boolean containsValue(Object value); - - /** - * @return a set view of the mappings contained in this map - * @see java.util.Map#entrySet() - */ - Set> entrySet(); - - /** - * @param key the key whose associated value is to be returned - * @return the value to which the specified key is mapped, or - * {@code null} if this map contains no mapping for the key - * @see java.util.Map#get(Object) - */ - V get(Object key); - - /** - * @param key key whose mapping is to be removed from the map - * @return the previous value associated with {@code key}, or - * {@code null} if there was no mapping for {@code key}. - * @see java.util.Map#remove(Object) - */ - V remove(Object key); - - /** - * @return {@code true} if this map contains no key-value mappings - * @see java.util.Map#isEmpty() - */ - boolean isEmpty(); - - /** - * @return a set view of the keys contained in this map - * @see java.util.Map#keySet() - */ - Set keySet(); - - /** - * @return the number of key-value mappings in this map - * @see java.util.Map#size() - */ - int size(); - - /** - * @return a collection view of the values contained in this map - * @see java.util.Map#values() - */ - Collection values(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/IterableGet.java b/src/main/java/repack/apache/commons/collections4/IterableGet.java deleted file mode 100644 index eb3b10a2f9..0000000000 --- a/src/main/java/repack/apache/commons/collections4/IterableGet.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -/** - * The "read" subset of the {@link java.util.Map} interface. - * - * @param the type of the keys in this map - * @param the type of the values in this map - * - * @since 4.0 - * @see Put - */ -public interface IterableGet extends Get { - /** - * Obtains a {@code 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<String,Integer> map = new HashedMap<String,Integer>();
-     * MapIterator<String,Integer> it = map.mapIterator();
-     * while (it.hasNext()) {
-     *   String key = it.next();
-     *   Integer value = it.getValue();
-     *   it.setValue(value + 1);
-     * }
-     * 
- * - * @return a map iterator - */ - MapIterator mapIterator(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/IterableMap.java b/src/main/java/repack/apache/commons/collections4/IterableMap.java deleted file mode 100644 index 527f2ddfb3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/IterableMap.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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<String,Integer> map = new HashedMap<String,Integer>();
- * MapIterator<String,Integer> 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 this map - * @param the type of the values in this map - * - * @since 3.0 - */ -public interface IterableMap extends Map, Put, IterableGet { - // empty -} diff --git a/src/main/java/repack/apache/commons/collections4/IterableSortedMap.java b/src/main/java/repack/apache/commons/collections4/IterableSortedMap.java deleted file mode 100644 index 31a2272e0a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/IterableSortedMap.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -public interface IterableSortedMap extends SortedMap, OrderedMap { -} diff --git a/src/main/java/repack/apache/commons/collections4/IterableUtils.java b/src/main/java/repack/apache/commons/collections4/IterableUtils.java deleted file mode 100644 index f9e3166038..0000000000 --- a/src/main/java/repack/apache/commons/collections4/IterableUtils.java +++ /dev/null @@ -1,1043 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.functors.EqualPredicate; -import repack.apache.commons.collections4.iterators.LazyIteratorChain; -import repack.apache.commons.collections4.iterators.ReverseListIterator; -import repack.apache.commons.collections4.iterators.UniqueFilterIterator; - -/** - * Provides utility methods and decorators for {@link Iterable} instances. - *

- * Note: this util class has been designed for fail-fast argument checking. - *

- *
    - *
  • - * all decorator methods are NOT null-safe wrt the provided Iterable argument, i.e. - * they will throw a {@link NullPointerException} if a null Iterable is passed as argument. - *
  • - * all other utility methods are null-safe wrt the provided Iterable argument, i.e. they will - * treat a null Iterable the same way as an empty one. Other arguments which are null, - * e.g. a {@link Predicate}, will result in a {@link NullPointerException}. Exception: passing - * a null {@link Comparator} is equivalent to a Comparator with natural ordering. - *
- * - * @since 4.1 - */ -public class IterableUtils { - - /** - * An empty iterable. - */ - @SuppressWarnings("rawtypes") - static final FluentIterable EMPTY_ITERABLE = new FluentIterable() { - @Override - public Iterator iterator() { - return IteratorUtils.emptyIterator(); - } - }; - - /** - * Gets an empty iterable. - *

- * This iterable does not contain any elements. - * - * @param the element type - * @return an empty iterable - */ - @SuppressWarnings("unchecked") // OK, empty collection is compatible with any type - public static Iterable emptyIterable() { - return EMPTY_ITERABLE; - } - - /** - * Combines two iterables into a single iterable. - *

- * The returned iterable has an iterator that traverses the elements in {@code a}, - * followed by the elements in {@code b}. The source iterators are not polled until - * necessary. - *

- * The returned iterable's iterator supports {@code remove()} when the corresponding - * input iterator supports it. - * - * @param the element type - * @param a the first iterable, may not be null - * @param b the second iterable, may not be null - * @return a new iterable, combining the provided iterables - * @throws NullPointerException if either a or b is null - */ - @SuppressWarnings("unchecked") - public static Iterable chainedIterable(final Iterable a, - final Iterable b) { - return chainedIterable(new Iterable[] {a, b}); - } - - /** - * Combines three iterables into a single iterable. - *

- * The returned iterable has an iterator that traverses the elements in {@code a}, - * followed by the elements in {@code b} and {@code c}. The source iterators are - * not polled until necessary. - *

- * The returned iterable's iterator supports {@code remove()} when the corresponding - * input iterator supports it. - * - * @param the element type - * @param a the first iterable, may not be null - * @param b the second iterable, may not be null - * @param c the third iterable, may not be null - * @return a new iterable, combining the provided iterables - * @throws NullPointerException if either of the provided iterables is null - */ - @SuppressWarnings("unchecked") - public static Iterable chainedIterable(final Iterable a, - final Iterable b, - final Iterable c) { - return chainedIterable(new Iterable[] {a, b, c}); - } - - /** - * Combines four iterables into a single iterable. - *

- * The returned iterable has an iterator that traverses the elements in {@code a}, - * followed by the elements in {@code b}, {@code c} and {@code d}. The source - * iterators are not polled until necessary. - *

- * The returned iterable's iterator supports {@code remove()} when the corresponding - * input iterator supports it. - * - * @param the element type - * @param a the first iterable, may not be null - * @param b the second iterable, may not be null - * @param c the third iterable, may not be null - * @param d the fourth iterable, may not be null - * @return a new iterable, combining the provided iterables - * @throws NullPointerException if either of the provided iterables is null - */ - @SuppressWarnings("unchecked") - public static Iterable chainedIterable(final Iterable a, - final Iterable b, - final Iterable c, - final Iterable d) { - return chainedIterable(new Iterable[] {a, b, c, d}); - } - - /** - * Combines the provided iterables into a single iterable. - *

- * The returned iterable has an iterator that traverses the elements in the order - * of the arguments, i.e. iterables[0], iterables[1], .... The source iterators - * are not polled until necessary. - *

- * The returned iterable's iterator supports {@code remove()} when the corresponding - * input iterator supports it. - * - * @param the element type - * @param iterables the iterables to combine, may not be null - * @return a new iterable, combining the provided iterables - * @throws NullPointerException if either of the provided iterables is null - */ - public static Iterable chainedIterable(final Iterable... iterables) { - checkNotNull(iterables); - return new FluentIterable() { - @Override - public Iterator iterator() { - return new LazyIteratorChain() { - @Override - protected Iterator nextIterator(final int count) { - if (count > iterables.length) { - return null; - } - return iterables[count - 1].iterator(); - } - }; - } - }; - } - - /** - * Combines the two provided iterables into an ordered iterable using - * natural ordering. - *

- * The returned iterable's iterator supports {@code remove()} when the - * corresponding input iterator supports it. - * - * @param the element type - * @param a the first iterable, must not be null - * @param b the second iterable, must not be null - * @return a filtered view on the specified iterable - * @throws NullPointerException if either of the provided iterables is null - */ - public static Iterable collatedIterable(final Iterable a, - final Iterable b) { - checkNotNull(a, b); - return new FluentIterable() { - @Override - public Iterator iterator() { - return IteratorUtils.collatedIterator(null, a.iterator(), b.iterator()); - } - }; - } - - /** - * Combines the two provided iterables into an ordered iterable using the - * provided comparator. If the comparator is null, natural ordering will be - * used. - *

- * The returned iterable's iterator supports {@code remove()} when the - * corresponding input iterator supports it. - * - * @param the element type - * @param comparator the comparator defining an ordering over the elements, - * may be null, in which case natural ordering will be used - * @param a the first iterable, may not be null - * @param b the second iterable, may not be null - * @return a filtered view on the specified iterable - * @throws NullPointerException if either of the provided iterables is null - */ - public static Iterable collatedIterable(final Comparator comparator, - final Iterable a, - final Iterable b) { - checkNotNull(a, b); - return new FluentIterable() { - @Override - public Iterator iterator() { - return IteratorUtils.collatedIterator(comparator, a.iterator(), b.iterator()); - } - }; - } - - /** - * Returns a view of the given iterable that only contains elements matching - * the provided predicate. - *

- * The returned iterable's iterator supports {@code remove()} when the - * corresponding input iterator supports it. - * - * @param the element type - * @param iterable the iterable to filter, may not be null - * @param predicate the predicate used to filter elements, may not be null - * @return a filtered view on the specified iterable - * @throws NullPointerException if either iterable or predicate is null - */ - public static Iterable filteredIterable(final Iterable iterable, - final Predicate predicate) { - checkNotNull(iterable); - Objects.requireNonNull(predicate, "predicate"); - return new FluentIterable() { - @Override - public Iterator iterator() { - return IteratorUtils.filteredIterator(emptyIteratorIfNull(iterable), predicate); - } - }; - } - - /** - * Returns a view of the given iterable that contains at most the given number - * of elements. - *

- * The returned iterable's iterator supports {@code remove()} when the corresponding - * input iterator supports it. - * - * @param the element type - * @param iterable the iterable to limit, may not be null - * @param maxSize the maximum number of elements, must not be negative - * @return a bounded view on the specified iterable - * @throws IllegalArgumentException if maxSize is negative - * @throws NullPointerException if iterable is null - */ - public static Iterable boundedIterable(final Iterable iterable, final long maxSize) { - checkNotNull(iterable); - if (maxSize < 0) { - throw new IllegalArgumentException("MaxSize parameter must not be negative."); - } - - return new FluentIterable() { - @Override - public Iterator iterator() { - return IteratorUtils.boundedIterator(iterable.iterator(), maxSize); - } - }; - } - - /** - * Returns a view of the given iterable which will cycle infinitely over - * its elements. - *

- * The returned iterable's iterator supports {@code remove()} if - * {@code iterable.iterator()} does. After {@code remove()} is called, subsequent - * cycles omit the removed element, which is no longer in {@code iterable}. The - * iterator's {@code hasNext()} method returns {@code true} until {@code iterable} - * is empty. - * - * @param the element type - * @param iterable the iterable to loop, may not be null - * @return a view of the iterable, providing an infinite loop over its elements - * @throws NullPointerException if iterable is null - */ - public static Iterable loopingIterable(final Iterable iterable) { - checkNotNull(iterable); - return new FluentIterable() { - @Override - public Iterator iterator() { - return new LazyIteratorChain() { - @Override - protected Iterator nextIterator(final int count) { - if (IterableUtils.isEmpty(iterable)) { - return null; - } - return iterable.iterator(); - } - }; - } - }; - } - - /** - * Returns a reversed view of the given iterable. - *

- * In case the provided iterable is a {@link List} instance, a - * {@link ReverseListIterator} will be used to reverse the traversal - * order, otherwise an intermediate {@link List} needs to be created. - *

- * The returned iterable's iterator supports {@code remove()} if the - * provided iterable is a {@link List} instance. - * - * @param the element type - * @param iterable the iterable to use, may not be null - * @return a reversed view of the specified iterable - * @throws NullPointerException if iterable is null - * @see ReverseListIterator - */ - public static Iterable reversedIterable(final Iterable iterable) { - checkNotNull(iterable); - return new FluentIterable() { - @Override - public Iterator iterator() { - final List list = iterable instanceof List ? - (List) iterable : - IteratorUtils.toList(iterable.iterator()); - return new ReverseListIterator<>(list); - } - }; - } - - /** - * Returns a view of the given iterable that skips the first N elements. - *

- * The returned iterable's iterator supports {@code remove()} when the corresponding - * input iterator supports it. - * - * @param the element type - * @param iterable the iterable to use, may not be null - * @param elementsToSkip the number of elements to skip from the start, must not be negative - * @return a view of the specified iterable, skipping the first N elements - * @throws IllegalArgumentException if elementsToSkip is negative - * @throws NullPointerException if iterable is null - */ - public static Iterable skippingIterable(final Iterable iterable, final long elementsToSkip) { - checkNotNull(iterable); - if (elementsToSkip < 0) { - throw new IllegalArgumentException("ElementsToSkip parameter must not be negative."); - } - - return new FluentIterable() { - @Override - public Iterator iterator() { - return IteratorUtils.skippingIterator(iterable.iterator(), elementsToSkip); - } - }; - } - - /** - * Returns a transformed view of the given iterable where all of its elements - * have been transformed by the provided transformer. - *

- * The returned iterable's iterator supports {@code remove()} when the corresponding - * input iterator supports it. - * - * @param the input element type - * @param the output element type - * @param iterable the iterable to transform, may not be null - * @param transformer the transformer, must not be null - * @return a transformed view of the specified iterable - * @throws NullPointerException if either iterable or transformer is null - */ - public static Iterable transformedIterable(final Iterable iterable, - final Transformer transformer) { - checkNotNull(iterable); - Objects.requireNonNull(transformer, "transformer"); - return new FluentIterable() { - @Override - public Iterator iterator() { - return IteratorUtils.transformedIterator(iterable.iterator(), transformer); - } - }; - } - - /** - * Returns a unique view of the given iterable. - *

- * The returned iterable's iterator supports {@code remove()} when the - * corresponding input iterator supports it. Calling {@code remove()} - * will only remove a single element from the underlying iterator. - * - * @param the element type - * @param iterable the iterable to use, may not be null - * @return a unique view of the specified iterable - * @throws NullPointerException if iterable is null - */ - public static Iterable uniqueIterable(final Iterable iterable) { - checkNotNull(iterable); - return new FluentIterable() { - @Override - public Iterator iterator() { - return new UniqueFilterIterator<>(iterable.iterator()); - } - }; - } - - /** - * Returns an unmodifiable view of the given iterable. - *

- * The returned iterable's iterator does not support {@code remove()}. - * - * @param the element type - * @param iterable the iterable to use, may not be null - * @return an unmodifiable view of the specified iterable - * @throws NullPointerException if iterable is null - */ - public static Iterable unmodifiableIterable(final Iterable iterable) { - checkNotNull(iterable); - if (iterable instanceof UnmodifiableIterable) { - return iterable; - } - return new UnmodifiableIterable<>(iterable); - } - - /** - * Inner class to distinguish unmodifiable instances. - */ - private static final class UnmodifiableIterable extends FluentIterable { - private final Iterable unmodifiable; - - UnmodifiableIterable(final Iterable iterable) { - this.unmodifiable = iterable; - } - - @Override - public Iterator iterator() { - return IteratorUtils.unmodifiableIterator(unmodifiable.iterator()); - } - } - - /** - * Interleaves two iterables into a single iterable. - *

- * The returned iterable has an iterator that traverses the elements in {@code a} - * and {@code b} in alternating order. The source iterators are not polled until - * necessary. - *

- * The returned iterable's iterator supports {@code remove()} when the corresponding - * input iterator supports it. - * - * @param the element type - * @param a the first iterable, may not be null - * @param b the second iterable, may not be null - * @return a new iterable, interleaving the provided iterables - * @throws NullPointerException if either a or b is null - */ - public static Iterable zippingIterable(final Iterable a, - final Iterable b) { - checkNotNull(a); - checkNotNull(b); - return new FluentIterable() { - @Override - public Iterator iterator() { - return IteratorUtils.zippingIterator(a.iterator(), b.iterator()); - } - }; - } - - /** - * Interleaves two iterables into a single iterable. - *

- * The returned iterable has an iterator that traverses the elements in {@code a} - * and {@code b} in alternating order. The source iterators are not polled until - * necessary. - *

- * The returned iterable's iterator supports {@code remove()} when the corresponding - * input iterator supports it. - * - * @param the element type - * @param first the first iterable, may not be null - * @param others the array of iterables to interleave, may not be null - * @return a new iterable, interleaving the provided iterables - * @throws NullPointerException if either of the provided iterables is null - */ - public static Iterable zippingIterable(final Iterable first, - final Iterable... others) { - checkNotNull(first); - checkNotNull(others); - return new FluentIterable() { - @Override - public Iterator iterator() { - @SuppressWarnings("unchecked") // safe - final - Iterator[] iterators = new Iterator[others.length + 1]; - iterators[0] = first.iterator(); - for (int i = 0; i < others.length; i++) { - iterators[i + 1] = others[i].iterator(); - } - return IteratorUtils.zippingIterator(iterators); - } - }; - } - - /** - * Returns an immutable empty iterable if the argument is null, - * or the argument itself otherwise. - * - * @param the element type - * @param iterable the iterable, may be null - * @return an empty iterable if the argument is null - */ - public static Iterable emptyIfNull(final Iterable iterable) { - return iterable == null ? IterableUtils.emptyIterable() : iterable; - } - - /** - * Applies the closure to each element of the provided iterable. - * - * @param the element type - * @param iterable the iterator to use, may be null - * @param closure the closure to apply to each element, may not be null - * @throws NullPointerException if closure is null - */ - public static void forEach(final Iterable iterable, final Closure closure) { - IteratorUtils.forEach(emptyIteratorIfNull(iterable), closure); - } - - /** - * Executes the given closure on each but the last element in the iterable. - *

- * If the input iterable is null no change is made. - * - * @param the type of object the {@link Iterable} contains - * @param iterable the iterable to get the input from, may be null - * @param closure the closure to perform, may not be null - * @return the last element in the iterable, or null if iterable is null or empty - */ - public static E forEachButLast(final Iterable iterable, final Closure closure) { - return IteratorUtils.forEachButLast(emptyIteratorIfNull(iterable), closure); - } - - /** - * Finds the first element in the given iterable which matches the given predicate. - *

- * A {@code null} or empty iterator returns null. - * - * @param the element type - * @param iterable the iterable to search, may be null - * @param predicate the predicate to use, must not be null - * @return the first element of the iterable which matches the predicate or null if none could be found - * @throws NullPointerException if predicate is null - */ - public static E find(final Iterable iterable, final Predicate predicate) { - return IteratorUtils.find(emptyIteratorIfNull(iterable), predicate); - } - - /** - * Returns the index of the first element in the specified iterable that - * matches the given predicate. - *

- * A {@code null} or empty iterable returns -1. - * - * @param the element type - * @param iterable the iterable to search, may be null - * @param predicate the predicate to use, must not be null - * @return the index of the first element which matches the predicate or -1 if none matches - * @throws NullPointerException if predicate is null - */ - public static int indexOf(final Iterable iterable, final Predicate predicate) { - return IteratorUtils.indexOf(emptyIteratorIfNull(iterable), predicate); - } - - /** - * Answers true if a predicate is true for every element of an iterable. - *

- * A {@code null} or empty iterable returns true. - * - * @param the type of object the {@link Iterable} contains - * @param iterable the {@link Iterable} to use, may be null - * @param predicate the predicate to use, may not be null - * @return true if every element of the collection matches the predicate or if the - * collection is empty, false otherwise - * @throws NullPointerException if predicate is null - */ - public static boolean matchesAll(final Iterable iterable, final Predicate predicate) { - return IteratorUtils.matchesAll(emptyIteratorIfNull(iterable), predicate); - } - - /** - * Answers true if a predicate is true for any element of the iterable. - *

- * A {@code null} or empty iterable returns false. - * - * @param the type of object the {@link Iterable} contains - * @param iterable the {@link Iterable} to use, may be null - * @param predicate the predicate to use, may not be null - * @return true if any element of the collection matches the predicate, false otherwise - * @throws NullPointerException if predicate is null - */ - public static boolean matchesAny(final Iterable iterable, final Predicate predicate) { - return IteratorUtils.matchesAny(emptyIteratorIfNull(iterable), predicate); - } - - /** - * Counts the number of elements in the input iterable that match the predicate. - *

- * A {@code null} iterable 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 not be null - * @return the number of matches for the predicate in the collection - * @throws NullPointerException if predicate is null - */ - public static long countMatches(final Iterable input, final Predicate predicate) { - Objects.requireNonNull(predicate, "predicate"); - return size(filteredIterable(emptyIfNull(input), predicate)); - } - - /** - * Answers true if the provided iterable is empty. - *

- * A {@code null} iterable returns true. - * - * @param iterable the {@link Iterable to use}, may be null - * @return true if the iterable is null or empty, false otherwise - */ - public static boolean isEmpty(final Iterable iterable) { - if (iterable instanceof Collection) { - return ((Collection) iterable).isEmpty(); - } - return IteratorUtils.isEmpty(emptyIteratorIfNull(iterable)); - } - - /** - * Checks if the object is contained in the given iterable. - *

- * A {@code null} or empty iterable returns false. - * - * @param the type of object the {@link Iterable} contains - * @param iterable the iterable to check, may be null - * @param object the object to check - * @return true if the object is contained in the iterable, false otherwise - */ - public static boolean contains(final Iterable iterable, final Object object) { - if (iterable instanceof Collection) { - return ((Collection) iterable).contains(object); - } - return IteratorUtils.contains(emptyIteratorIfNull(iterable), object); - } - - /** - * Checks if the object is contained in the given iterable. Object equality - * is tested with an {@code equator} unlike {@link #contains(Iterable, Object)} - * which uses {@link Object#equals(Object)}. - *

- * A {@code null} or empty iterable returns false. - * A {@code null} object will not be passed to the equator, instead a - * {@link repack.apache.commons.collections4.functors.NullPredicate NullPredicate} - * will be used. - * - * @param the type of object the {@link Iterable} contains - * @param iterable the iterable to check, may be null - * @param object the object to check - * @param equator the equator to use to check, may not be null - * @return true if the object is contained in the iterable, false otherwise - * @throws NullPointerException if equator is null - */ - public static boolean contains(final Iterable iterable, final E object, - final Equator equator) { - Objects.requireNonNull(equator, "equator"); - return matchesAny(iterable, EqualPredicate.equalPredicate(object, equator)); - } - - /** - * Returns the number of occurrences of the provided object in the iterable. - * - * @param the element type that the {@link Iterable} may contain - * @param the element type of the object to find - * @param iterable the {@link Iterable} to search - * @param obj the object to find the cardinality of - * @return the number of occurrences of obj in iterable - */ - public static int frequency(final Iterable iterable, final T obj) { - if (iterable instanceof Set) { - return ((Set) iterable).contains(obj) ? 1 : 0; - } - if (iterable instanceof Bag) { - return ((Bag) iterable).getCount(obj); - } - return size(filteredIterable(emptyIfNull(iterable), EqualPredicate.equalPredicate(obj))); - } - - /** - * Returns the {@code index}-th value in the {@code iterable}'s {@link Iterator}, throwing - * {@code IndexOutOfBoundsException} if there is no such element. - *

- * If the {@link Iterable} is a {@link List}, then it will use {@link List#get(int)}. - * - * @param the type of object in the {@link Iterable}. - * @param iterable the {@link Iterable} to get a value from, may be null - * @param index the index to get - * @return the object at the specified index - * @throws IndexOutOfBoundsException if the index is invalid - */ - public static T get(final Iterable iterable, final int index) { - CollectionUtils.checkIndexBounds(index); - if (iterable instanceof List) { - return ((List) iterable).get(index); - } - return IteratorUtils.get(emptyIteratorIfNull(iterable), index); - } - - /** - * Shortcut for {@code get(iterator, 0)}. - *

- * Returns the {@code first} value in the {@code iterable}'s {@link Iterator}, throwing - * {@code IndexOutOfBoundsException} if there is no such element. - *

- *

- * If the {@link Iterable} is a {@link List}, then it will use {@link List#get(int)}. - *

- * - * @param the type of object in the {@link Iterable}. - * @param iterable the {@link Iterable} to get a value from, may be null - * @return the first object - * @throws IndexOutOfBoundsException if the request is invalid - * @since 4.2 - */ - public static T first(final Iterable iterable) { - return get(iterable, 0); - } - - /** - * Returns the number of elements contained in the given iterator. - *

- * A {@code null} or empty iterator returns {@code 0}. - * - * @param iterable the iterable to check, may be null - * @return the number of elements contained in the iterable - */ - public static int size(final Iterable iterable) { - if (iterable == null) { - return 0; - } - if (iterable instanceof Collection) { - return ((Collection) iterable).size(); - } - return IteratorUtils.size(emptyIteratorIfNull(iterable)); - } - - /** - * Partitions all elements from iterable into separate output collections, - * based on the evaluation of the given predicate. - *

- * For each predicate, the result will contain a list holding all elements of the - * input iterable matching the predicate. The last list will hold all elements - * which didn't match any predicate: - *

-     *  [C1, R] = partition(I, P1) with
-     *  I = input
-     *  P1 = first predicate
-     *  C1 = collection of elements matching P1
-     *  R = collection of elements rejected by all predicates
-     * 
- *

- * If the input iterable is {@code null}, the same is returned as for an - * empty iterable. - *

- * Example: for an input list [1, 2, 3, 4, 5] calling partition with a predicate [x < 3] - * will result in the following output: [[1, 2], [3, 4, 5]]. - * - * @param the type of object the {@link Iterable} contains - * @param iterable the iterable to partition, may be null - * @param predicate the predicate to use, may not be null - * @return a list containing the output collections - * @throws NullPointerException if predicate is null - */ - public static List> partition(final Iterable iterable, - final Predicate predicate) { - Objects.requireNonNull(predicate, "predicate"); - @SuppressWarnings({ "unchecked", "rawtypes" }) // safe - final Factory> factory = FactoryUtils.instantiateFactory((Class) ArrayList.class); - @SuppressWarnings("unchecked") // safe - final Predicate[] predicates = new Predicate[] { predicate }; - return partition(iterable, factory, predicates); - } - - /** - * Partitions all elements from iterable into separate output collections, - * based on the evaluation of the given predicates. - *

- * For each predicate, the result will contain a list holding all elements of the - * input iterable matching the predicate. The last list will hold all elements - * which didn't match any predicate: - *

-     *  [C1, C2, R] = partition(I, P1, P2) with
-     *  I = input
-     *  P1 = first predicate
-     *  P2 = second predicate
-     *  C1 = collection of elements matching P1
-     *  C2 = collection of elements matching P2
-     *  R = collection of elements rejected by all predicates
-     * 
- *

- * Note: elements are only added to the output collection of the first matching - * predicate, determined by the order of arguments. - *

- * If the input iterable is {@code null}, the same is returned as for an - * empty iterable. - *

- * Example: for an input list [1, 2, 3, 4, 5] calling partition with predicates [x < 3] - * and [x < 5] will result in the following output: [[1, 2], [3, 4], [5]]. - * - * @param the type of object the {@link Iterable} contains - * @param iterable the collection to get the input from, may be null - * @param predicates the predicates to use, may not be null - * @return a list containing the output collections - * @throws NullPointerException if any predicate is null - */ - public static List> partition(final Iterable iterable, - final Predicate... predicates) { - - @SuppressWarnings({ "unchecked", "rawtypes" }) // safe - final Factory> factory = FactoryUtils.instantiateFactory((Class) ArrayList.class); - return partition(iterable, factory, predicates); - } - - /** - * Partitions all elements from iterable into separate output collections, - * based on the evaluation of the given predicates. - *

- * For each predicate, the returned list will contain a collection holding - * all elements of the input iterable matching the predicate. The last collection - * contained in the list will hold all elements which didn't match any predicate: - *

-     *  [C1, C2, R] = partition(I, P1, P2) with
-     *  I = input
-     *  P1 = first predicate
-     *  P2 = second predicate
-     *  C1 = collection of elements matching P1
-     *  C2 = collection of elements matching P2
-     *  R = collection of elements rejected by all predicates
-     * 
- *

- * Note: elements are only added to the output collection of the first matching - * predicate, determined by the order of arguments. - *

- * If the input iterable is {@code null}, the same is returned as for an - * empty iterable. - * If no predicates have been provided, all elements of the input collection - * will be added to the rejected collection. - *

- * Example: for an input list [1, 2, 3, 4, 5] calling partition with predicates [x < 3] - * and [x < 5] will result in the following output: [[1, 2], [3, 4], [5]]. - * - * @param the type of object the {@link Iterable} contains - * @param the type of the output {@link Collection} - * @param iterable the collection to get the input from, may be null - * @param partitionFactory the factory used to create the output collections - * @param predicates the predicates to use, may not be null - * @return a list containing the output collections - * @throws NullPointerException if any predicate is null - */ - public static > List partition(final Iterable iterable, - final Factory partitionFactory, final Predicate... predicates) { - - if (iterable == null) { - final Iterable empty = emptyIterable(); - return partition(empty, partitionFactory, predicates); - } - - Objects.requireNonNull(predicates, "predicates"); - - for (final Predicate predicate : predicates) { - Objects.requireNonNull(predicate, "predicate"); - } - - if (predicates.length < 1) { - // return the entire input collection as a single partition - final R singlePartition = partitionFactory.create(); - CollectionUtils.addAll(singlePartition, iterable); - return Collections.singletonList(singlePartition); - } - - // create the empty partitions - final int numberOfPredicates = predicates.length; - final int numberOfPartitions = numberOfPredicates + 1; - final List partitions = new ArrayList<>(numberOfPartitions); - for (int i = 0; i < numberOfPartitions; ++i) { - partitions.add(partitionFactory.create()); - } - - // for each element in inputCollection: - // find the first predicate that evaluates to true. - // if there is a predicate, add the element to the corresponding partition. - // if there is no predicate, add it to the last, catch-all partition. - for (final O element : iterable) { - boolean elementAssigned = false; - for (int i = 0; i < numberOfPredicates; ++i) { - if (predicates[i].evaluate(element)) { - partitions.get(i).add(element); - elementAssigned = true; - break; - } - } - - if (!elementAssigned) { - // no predicates evaluated to true - // add element to last partition - partitions.get(numberOfPredicates).add(element); - } - } - - return partitions; - } - - /** - * Gets a new list with the contents of the provided iterable. - * - * @param the element type - * @param iterable the iterable to use, may be null - * @return a list of the iterator contents - */ - public static List toList(final Iterable iterable) { - return IteratorUtils.toList(emptyIteratorIfNull(iterable)); - } - - /** - * Returns a string representation of the elements of the specified iterable. - *

- * The string representation consists of a list of the iterable's elements, - * enclosed in square brackets ({@code "[]"}). Adjacent elements are separated - * by the characters {@code ", "} (a comma followed by a space). Elements are - * converted to strings as by {@code String.valueOf(Object)}. - * - * @param the element type - * @param iterable the iterable to convert to a string, may be null - * @return a string representation of {@code iterable} - */ - public static String toString(final Iterable iterable) { - return IteratorUtils.toString(emptyIteratorIfNull(iterable)); - } - - /** - * Returns a string representation of the elements of the specified iterable. - *

- * The string representation consists of a list of the iterable's elements, - * enclosed in square brackets ({@code "[]"}). Adjacent elements are separated - * by the characters {@code ", "} (a comma followed by a space). Elements are - * converted to strings as by using the provided {@code transformer}. - * - * @param the element type - * @param iterable the iterable to convert to a string, may be null - * @param transformer the transformer used to get a string representation of an element - * @return a string representation of {@code iterable} - * @throws NullPointerException if {@code transformer} is null - */ - public static String toString(final Iterable iterable, - final Transformer transformer) { - Objects.requireNonNull(transformer, "transformer"); - return IteratorUtils.toString(emptyIteratorIfNull(iterable), transformer); - } - - /** - * Returns a string representation of the elements of the specified iterable. - *

- * The string representation consists of a list of the iterable's elements, - * enclosed by the provided {@code prefix} and {@code suffix}. Adjacent elements - * are separated by the provided {@code delimiter}. Elements are converted to - * strings as by using the provided {@code transformer}. - * - * @param the element type - * @param iterable the iterable to convert to a string, may be null - * @param transformer the transformer used to get a string representation of an element - * @param delimiter the string to delimit elements - * @param prefix the prefix, prepended to the string representation - * @param suffix the suffix, appended to the string representation - * @return a string representation of {@code iterable} - * @throws NullPointerException if either transformer, delimiter, prefix or suffix is null - */ - public static String toString(final Iterable iterable, - final Transformer transformer, - final String delimiter, - final String prefix, - final String suffix) { - return IteratorUtils.toString(emptyIteratorIfNull(iterable), - transformer, delimiter, prefix, suffix); - } - - /** - * Fail-fast check for null arguments. - * - * @param iterable the iterable to check - * @throws NullPointerException if iterable is null - */ - static void checkNotNull(final Iterable iterable) { - Objects.requireNonNull(iterable, "iterable"); - } - - /** - * Fail-fast check for null arguments. - * - * @param iterables the iterables to check - * @throws NullPointerException if the argument or any of its contents is null - */ - static void checkNotNull(final Iterable... iterables) { - Objects.requireNonNull(iterables, "iterables"); - for (final Iterable iterable : iterables) { - checkNotNull(iterable); - } - } - - /** - * Returns an empty iterator if the argument is {@code null}, - * or {@code iterable.iterator()} otherwise. - * - * @param the element type - * @param iterable the iterable, possibly {@code null} - * @return an empty iterator if the argument is {@code null} - */ - private static Iterator emptyIteratorIfNull(final Iterable iterable) { - return iterable != null ? iterable.iterator() : IteratorUtils.emptyIterator(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/IteratorUtils.java b/src/main/java/repack/apache/commons/collections4/IteratorUtils.java deleted file mode 100644 index 7eb3626a8c..0000000000 --- a/src/main/java/repack/apache/commons/collections4/IteratorUtils.java +++ /dev/null @@ -1,1444 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.lang.reflect.Array; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.Dictionary; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; -import java.util.Objects; - -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import repack.apache.commons.collections4.functors.EqualPredicate; -import repack.apache.commons.collections4.iterators.ArrayIterator; -import repack.apache.commons.collections4.iterators.ArrayListIterator; -import repack.apache.commons.collections4.iterators.BoundedIterator; -import repack.apache.commons.collections4.iterators.CollatingIterator; -import repack.apache.commons.collections4.iterators.EmptyIterator; -import repack.apache.commons.collections4.iterators.EmptyListIterator; -import repack.apache.commons.collections4.iterators.EmptyMapIterator; -import repack.apache.commons.collections4.iterators.EmptyOrderedIterator; -import repack.apache.commons.collections4.iterators.EmptyOrderedMapIterator; -import repack.apache.commons.collections4.iterators.EnumerationIterator; -import repack.apache.commons.collections4.iterators.FilterIterator; -import repack.apache.commons.collections4.iterators.FilterListIterator; -import repack.apache.commons.collections4.iterators.IteratorChain; -import repack.apache.commons.collections4.iterators.IteratorEnumeration; -import repack.apache.commons.collections4.iterators.IteratorIterable; -import repack.apache.commons.collections4.iterators.ListIteratorWrapper; -import repack.apache.commons.collections4.iterators.LoopingIterator; -import repack.apache.commons.collections4.iterators.LoopingListIterator; -import repack.apache.commons.collections4.iterators.NodeListIterator; -import repack.apache.commons.collections4.iterators.ObjectArrayIterator; -import repack.apache.commons.collections4.iterators.ObjectArrayListIterator; -import repack.apache.commons.collections4.iterators.ObjectGraphIterator; -import repack.apache.commons.collections4.iterators.PeekingIterator; -import repack.apache.commons.collections4.iterators.PushbackIterator; -import repack.apache.commons.collections4.iterators.SingletonIterator; -import repack.apache.commons.collections4.iterators.SingletonListIterator; -import repack.apache.commons.collections4.iterators.SkippingIterator; -import repack.apache.commons.collections4.iterators.TransformIterator; -import repack.apache.commons.collections4.iterators.UnmodifiableIterator; -import repack.apache.commons.collections4.iterators.UnmodifiableListIterator; -import repack.apache.commons.collections4.iterators.UnmodifiableMapIterator; -import repack.apache.commons.collections4.iterators.ZippingIterator; - -/** - * Provides static utility methods and decorators for {@link Iterator} - * instances. The implementations are provided in the iterators subpackage. - * - * @since 2.1 - */ -public class IteratorUtils { - // validation is done in this class in certain cases because the - // public classes allow invalid states - - /** - * An iterator over no elements. - */ - @SuppressWarnings("rawtypes") - public static final ResettableIterator EMPTY_ITERATOR = EmptyIterator.RESETTABLE_INSTANCE; - - /** - * A list iterator over no elements. - */ - @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; - /** - * Default delimiter used to delimit elements while converting an Iterator - * to its String representation. - */ - private static final String DEFAULT_TOSTRING_DELIMITER = ", "; - - /** - * Don't allow instances. - */ - private IteratorUtils() {} - - // Empty - /** - * Gets an empty iterator. - *

- * This iterator is a valid iterator object that will iterate over nothing. - * - * @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. - * - * @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. - * - * @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. - * - * @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. - * - * @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. - * - * @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); - } - - // Bounded - /** - * Decorates the specified iterator to return at most the given number - * of elements. - * - * @param the element type - * @param iterator the iterator to decorate - * @param max the maximum number of elements returned by this iterator - * @return a new bounded iterator - * @throws NullPointerException if the iterator is null - * @throws IllegalArgumentException if max is negative - * @since 4.1 - */ - public static BoundedIterator boundedIterator(final Iterator iterator, final long max) { - return boundedIterator(iterator, 0, max); - } - - /** - * Decorates the specified iterator to return at most the given number - * of elements, skipping all elements until the iterator reaches the - * position at {@code offset}. - *

- * The iterator is immediately advanced until it reaches the position at - * {@code offset}, incurring O(n) time. - * - * @param the element type - * @param iterator the iterator to decorate - * @param offset the index of the first element of the decorated iterator to return - * @param max the maximum number of elements returned by this iterator - * @return a new bounded iterator - * @throws NullPointerException if the iterator is null - * @throws IllegalArgumentException if either offset or max is negative - * @since 4.1 - */ - public static BoundedIterator boundedIterator(final Iterator iterator, - final long offset, final long max) { - return new BoundedIterator<>(iterator, offset, max); - } - - // 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.unmodifiableListIterator(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 {@code A} and {@code B}, - * the {@link Iterator#next()} method will return the lesser of - * {@code A.next()} and {@code 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) { - @SuppressWarnings("unchecked") - final Comparator comp = - comparator == null ? ComparatorUtils.NATURAL_COMPARATOR : (Comparator) comparator; - return new CollatingIterator<>(comp, 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 {@code A} and {@code B}, - * the {@link Iterator#next()} method will return the lesser of - * {@code A.next()} and {@code 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) { - @SuppressWarnings("unchecked") - final Comparator comp = - comparator == null ? ComparatorUtils.NATURAL_COMPARATOR : (Comparator) comparator; - return new CollatingIterator<>(comp, 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 {@code A} and {@code B}, - * the {@link Iterator#next()} method will return the lesser of - * {@code A.next()} and {@code 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) { - @SuppressWarnings("unchecked") - final Comparator comp = - comparator == null ? ComparatorUtils.NATURAL_COMPARATOR : (Comparator) comparator; - return new CollatingIterator<>(comp, 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 {@code Transformer} to extract the iterators and elements. - * Its main benefit is that no intermediate {@code 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 {@code 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 transformer 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 transformer) { - - Objects.requireNonNull(iterator, "iterator"); - Objects.requireNonNull(transformer, "transformer"); - return new TransformIterator<>(iterator, transformer); - } - - // 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) { - Objects.requireNonNull(iterator, "iterator"); - Objects.requireNonNull(predicate, "predicate"); - 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) { - - Objects.requireNonNull(listIterator, "listIterator"); - Objects.requireNonNull(predicate, "predicate"); - 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 collection 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 collection) { - return new LoopingIterator<>(Objects.requireNonNull(collection, "collection")); - } - - /** - * 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) { - return new LoopingListIterator<>(Objects.requireNonNull(list, "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, may not be null - * @return a new, single use {@link Iterator} - * @throws NullPointerException if nodeList is null - * @since 4.0 - */ - public static NodeListIterator nodeListIterator(final NodeList nodeList) { - return new NodeListIterator(Objects.requireNonNull(nodeList, "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, may not be null - * @return a new, single use {@link Iterator} - * @throws NullPointerException if node is null - * @since 4.0 - */ - public static NodeListIterator nodeListIterator(final Node node) { - return new NodeListIterator(Objects.requireNonNull(node, "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); - } - - // Skipping - /** - * Decorates the specified iterator to skip the first N elements. - * - * @param the element type - * @param iterator the iterator to decorate - * @param offset the first number of elements to skip - * @return a new skipping iterator - * @throws NullPointerException if the iterator is null - * @throws IllegalArgumentException if offset is negative - * @since 4.1 - */ - public static SkippingIterator skippingIterator(final Iterator iterator, final long offset) { - return new SkippingIterator<>(iterator, offset); - } - - // Zipping - /** - * Returns an iterator that interleaves elements from the decorated iterators. - * - * @param the element type - * @param a the first iterator to interleave - * @param b the second iterator to interleave - * @return an iterator, interleaving the decorated iterators - * @throws NullPointerException if any iterator is null - * @since 4.1 - */ - public static ZippingIterator zippingIterator(final Iterator a, - final Iterator b) { - return new ZippingIterator<>(a, b); - } - - /** - * Returns an iterator that interleaves elements from the decorated iterators. - * - * @param the element type - * @param a the first iterator to interleave - * @param b the second iterator to interleave - * @param c the third iterator to interleave - * @return an iterator, interleaving the decorated iterators - * @throws NullPointerException if any iterator is null - * @since 4.1 - */ - public static ZippingIterator zippingIterator(final Iterator a, - final Iterator b, - final Iterator c) { - return new ZippingIterator<>(a, b, c); - } - - /** - * Returns an iterator that interleaves elements from the decorated iterators. - * - * @param the element type - * @param iterators the array of iterators to interleave - * @return an iterator, interleaving the decorated iterators - * @throws NullPointerException if any iterator is null - * @since 4.1 - */ - public static ZippingIterator zippingIterator(final Iterator... iterators) { - return new ZippingIterator<>(iterators); - } - - // Views - /** - * Gets an iterator that provides an iterator view of the given enumeration. - * - * @param the element type - * @param enumeration the enumeration to use, may not be null - * @return a new iterator - * @throws NullPointerException if enumeration is null - */ - public static Iterator asIterator(final Enumeration enumeration) { - return new EnumerationIterator<>(Objects.requireNonNull(enumeration, "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, may not be null - * @param removeCollection the collection to remove elements from, may not be null - * @return a new iterator - * @throws NullPointerException if enumeration or removeCollection is null - */ - public static Iterator asIterator(final Enumeration enumeration, - final Collection removeCollection) { - return new EnumerationIterator<>(Objects.requireNonNull(enumeration, "enumeration"), - Objects.requireNonNull(removeCollection, "removeCollection")); - } - - /** - * Gets an enumeration that wraps an iterator. - * - * @param the element type - * @param iterator the iterator to use, may not be null - * @return a new enumeration - * @throws NullPointerException if iterator is null - */ - public static Enumeration asEnumeration(final Iterator iterator) { - return new IteratorEnumeration<>(Objects.requireNonNull(iterator, "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, may not be null - * @return a new, single use {@link Iterable} - * @throws NullPointerException if iterator is null - */ - public static Iterable asIterable(final Iterator iterator) { - Objects.requireNonNull(iterator, "iterator"); - 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, may not be null - * @return a new, multiple use iterable - * @throws NullPointerException if iterator is null - */ - public static Iterable asMultipleUseIterable(final Iterator iterator) { - Objects.requireNonNull(iterator, "iterator"); - 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, may not be null - * @return a new iterator - * @throws NullPointerException if iterator parameter is null - */ - public static ListIterator toListIterator(final Iterator iterator) { - Objects.requireNonNull(iterator, "iterator"); - 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) { - Objects.requireNonNull(iterator, "iterator"); - 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 ArrayStoreException if the arrayClass is invalid - */ - public static E[] toArray(final Iterator iterator, final Class arrayClass) { - Objects.requireNonNull(iterator, "iterator"); - Objects.requireNonNull(arrayClass, "arrayClass"); - final List list = toList(iterator, 100); - @SuppressWarnings("unchecked") - 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) { - Objects.requireNonNull(iterator, "iterator"); - 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 Iterable) { - return ((Iterable) 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()); - } - 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 | ReflectiveOperationException ignore) { // NOPMD - // ignore - } - return singletonIterator(obj); - } - - // Utility methods - - /** - * Applies the closure to each element of the provided iterator. - * - * @param the element type - * @param iterator the iterator to use, may be null - * @param closure the closure to apply to each element, may not be null - * @throws NullPointerException if closure is null - * @since 4.1 - */ - public static void forEach(final Iterator iterator, final Closure closure) { - Objects.requireNonNull(closure, "closure"); - - if (iterator != null) { - while (iterator.hasNext()) { - final E element = iterator.next(); - closure.execute(element); - } - } - } - - /** - * Executes the given closure on each but the last element in the iterator. - *

- * If the input iterator is null no change is made. - * - * @param the type of object the {@link Iterator} contains - * @param iterator the iterator to get the input from, may be null - * @param closure the closure to perform, may not be null - * @return the last element in the iterator, or null if iterator is null or empty - * @throws NullPointerException if closure is null - * @since 4.1 - */ - public static E forEachButLast(final Iterator iterator, final Closure closure) { - Objects.requireNonNull(closure, "closure"); - - if (iterator != null) { - while (iterator.hasNext()) { - final E element = iterator.next(); - if (!iterator.hasNext()) { - return element; - } - closure.execute(element); - } - } - return null; - } - - /** - * Finds the first element in the given iterator which matches the given predicate. - *

- * A {@code null} or empty iterator returns null. - * - * @param the element type - * @param iterator the iterator to search, may be null - * @param predicate the predicate to use, must not be null - * @return the first element of the iterator which matches the predicate or null if none could be found - * @throws NullPointerException if predicate is null - * @since 4.1 - */ - public static E find(final Iterator iterator, final Predicate predicate) { - Objects.requireNonNull(predicate, "predicate"); - - if (iterator != null) { - while (iterator.hasNext()) { - final E element = iterator.next(); - if (predicate.evaluate(element)) { - return element; - } - } - } - return null; - } - - /** - * Returns the index of the first element in the specified iterator that - * matches the given predicate. - *

- * A {@code null} or empty iterator returns -1. - * - * @param the element type - * @param iterator the iterator to search, may be null - * @param predicate the predicate to use, may not be null - * @return the index of the first element which matches the predicate or -1 if none matches - * @throws NullPointerException if predicate is null - * @since 4.1 - */ - public static int indexOf(final Iterator iterator, final Predicate predicate) { - Objects.requireNonNull(predicate, "predicate"); - - if (iterator != null) { - for (int index = 0; iterator.hasNext(); index++) { - final E element = iterator.next(); - if (predicate.evaluate(element)) { - return index; - } - } - } - return CollectionUtils.INDEX_NOT_FOUND; - } - - /** - * Answers true if a predicate is true for any element of the iterator. - *

- * A {@code null} or empty iterator returns false. - * - * @param the type of object the {@link Iterator} contains - * @param iterator the {@link Iterator} to use, may be null - * @param predicate the predicate to use, may not be null - * @return true if any element of the collection matches the predicate, false otherwise - * @throws NullPointerException if predicate is null - * @since 4.1 - */ - public static boolean matchesAny(final Iterator iterator, final Predicate predicate) { - return indexOf(iterator, predicate) != -1; - } - - /** - * Answers true if a predicate is true for every element of an iterator. - *

- * A {@code null} or empty iterator returns true. - * - * @param the type of object the {@link Iterator} contains - * @param iterator the {@link Iterator} to use, may be null - * @param predicate the predicate to use, may not be null - * @return true if every element of the collection matches the predicate or if the - * collection is empty, false otherwise - * @throws NullPointerException if predicate is null - * @since 4.1 - */ - public static boolean matchesAll(final Iterator iterator, final Predicate predicate) { - Objects.requireNonNull(predicate, "predicate"); - - if (iterator != null) { - while (iterator.hasNext()) { - final E element = iterator.next(); - if (!predicate.evaluate(element)) { - return false; - } - } - } - return true; - } - - /** - * Checks if the given iterator is empty. - *

- * A {@code null} or empty iterator returns true. - * - * @param iterator the {@link Iterator} to use, may be null - * @return true if the iterator is exhausted or null, false otherwise - * @since 4.1 - */ - public static boolean isEmpty(final Iterator iterator) { - return iterator == null || !iterator.hasNext(); - } - - /** - * Checks if the object is contained in the given iterator. - *

- * A {@code null} or empty iterator returns false. - * - * @param the type of object the {@link Iterator} contains - * @param iterator the iterator to check, may be null - * @param object the object to check - * @return true if the object is contained in the iterator, false otherwise - * @since 4.1 - */ - public static boolean contains(final Iterator iterator, final Object object) { - return matchesAny(iterator, EqualPredicate.equalPredicate(object)); - } - - /** - * Returns the {@code index}-th value in {@link Iterator}, throwing - * {@code IndexOutOfBoundsException} if there is no such element. - *

- * The Iterator is advanced to {@code index} (or to the end, if - * {@code index} exceeds the number of entries) as a side effect of this method. - * - * @param the type of object in the {@link Iterator} - * @param iterator the iterator 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 - * @since 4.1 - */ - public static E get(final Iterator iterator, final int index) { - int i = index; - CollectionUtils.checkIndexBounds(i); - while (iterator.hasNext()) { - i--; - if (i == -1) { - return iterator.next(); - } - iterator.next(); - } - throw new IndexOutOfBoundsException("Entry does not exist: " + i); - } - - /** - * Shortcut for {@code get(iterator, 0)}. - *

- * Returns the {@code first} value in {@link Iterator}, throwing - * {@code IndexOutOfBoundsException} if there is no such element. - *

- *

- * The Iterator is advanced to {@code 0} (or to the end, if - * {@code 0} exceeds the number of entries) as a side effect of this method. - *

- * @param the type of object in the {@link Iterator} - * @param iterator the iterator to get a value from - * @return the first object - * @throws IndexOutOfBoundsException if the request is invalid - * @since 4.2 - */ - public static E first(final Iterator iterator) { - return get(iterator, 0); - } - - /** - * Returns the number of elements contained in the given iterator. - *

- * A {@code null} or empty iterator returns {@code 0}. - * - * @param iterator the iterator to check, may be null - * @return the number of elements contained in the iterator - * @since 4.1 - */ - public static int size(final Iterator iterator) { - int size = 0; - if (iterator != null) { - while (iterator.hasNext()) { - iterator.next(); - size++; - } - } - return size; - } - - /** - * Returns a string representation of the elements of the specified iterator. - *

- * The string representation consists of a list of the iterator's elements, - * enclosed in square brackets ({@code "[]"}). Adjacent elements are separated - * by the characters {@code ", "} (a comma followed by a space). Elements are - * converted to strings as by {@code String.valueOf(Object)}. - * - * @param the element type - * @param iterator the iterator to convert to a string, may be null - * @return a string representation of {@code iterator} - * @since 4.1 - */ - public static String toString(final Iterator iterator) { - return toString(iterator, TransformerUtils.stringValueTransformer(), - DEFAULT_TOSTRING_DELIMITER, CollectionUtils.DEFAULT_TOSTRING_PREFIX, - CollectionUtils.DEFAULT_TOSTRING_SUFFIX); - } - - /** - * Returns a string representation of the elements of the specified iterator. - *

- * The string representation consists of a list of the iterable's elements, - * enclosed in square brackets ({@code "[]"}). Adjacent elements are separated - * by the characters {@code ", "} (a comma followed by a space). Elements are - * converted to strings as by using the provided {@code transformer}. - * - * @param the element type - * @param iterator the iterator to convert to a string, may be null - * @param transformer the transformer used to get a string representation of an element - * @return a string representation of {@code iterator} - * @throws NullPointerException if {@code transformer} is null - * @since 4.1 - */ - public static String toString(final Iterator iterator, - final Transformer transformer) { - return toString(iterator, transformer, DEFAULT_TOSTRING_DELIMITER, - CollectionUtils.DEFAULT_TOSTRING_PREFIX, CollectionUtils.DEFAULT_TOSTRING_SUFFIX); - } - - /** - * Returns a string representation of the elements of the specified iterator. - *

- * The string representation consists of a list of the iterator's elements, - * enclosed by the provided {@code prefix} and {@code suffix}. Adjacent elements - * are separated by the provided {@code delimiter}. Elements are converted to - * strings as by using the provided {@code transformer}. - * - * @param the element type - * @param iterator the iterator to convert to a string, may be null - * @param transformer the transformer used to get a string representation of an element - * @param delimiter the string to delimit elements - * @param prefix the prefix, prepended to the string representation - * @param suffix the suffix, appended to the string representation - * @return a string representation of {@code iterator} - * @throws NullPointerException if either transformer, delimiter, prefix or suffix is null - * @since 4.1 - */ - public static String toString(final Iterator iterator, - final Transformer transformer, - final String delimiter, - final String prefix, - final String suffix) { - Objects.requireNonNull(transformer, "transformer"); - Objects.requireNonNull(delimiter, "delimiter"); - Objects.requireNonNull(prefix, "prefix"); - Objects.requireNonNull(suffix, "suffix"); - final StringBuilder stringBuilder = new StringBuilder(prefix); - if (iterator != null) { - while (iterator.hasNext()) { - final E element = iterator.next(); - stringBuilder.append(transformer.transform(element)); - stringBuilder.append(delimiter); - } - if (stringBuilder.length() > prefix.length()) { - stringBuilder.setLength(stringBuilder.length() - delimiter.length()); - } - } - stringBuilder.append(suffix); - return stringBuilder.toString(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/KeyValue.java b/src/main/java/repack/apache/commons/collections4/KeyValue.java deleted file mode 100644 index 2f97d4f0ca..0000000000 --- a/src/main/java/repack/apache/commons/collections4/KeyValue.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -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(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/ListUtils.java b/src/main/java/repack/apache/commons/collections4/ListUtils.java deleted file mode 100644 index 9046630bb6..0000000000 --- a/src/main/java/repack/apache/commons/collections4/ListUtils.java +++ /dev/null @@ -1,749 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.Objects; - -import repack.apache.commons.collections4.bag.HashBag; -import repack.apache.commons.collections4.functors.DefaultEquator; -import repack.apache.commons.collections4.list.FixedSizeList; -import repack.apache.commons.collections4.list.LazyList; -import repack.apache.commons.collections4.list.PredicatedList; -import repack.apache.commons.collections4.list.TransformedList; -import repack.apache.commons.collections4.list.UnmodifiableList; -import repack.apache.commons.collections4.sequence.CommandVisitor; -import repack.apache.commons.collections4.sequence.EditScript; -import repack.apache.commons.collections4.sequence.SequencesComparator; - -/** - * Provides utility methods and decorators for {@link List} instances. - * - * @since 1.0 - */ -public class ListUtils { - /** - * A simple wrapper to use a CharSequence as List. - */ - private static final class CharSequenceAsList extends AbstractList { - private final CharSequence sequence; - - CharSequenceAsList(final CharSequence sequence) { - this.sequence = sequence; - } - - @Override - public Character get(final int index) { - return Character.valueOf(sequence.charAt(index)); - } - - @Override - public int size() { - return sequence.length(); - } - } - - - /** - * A helper class used to construct the longest common subsequence. - */ - private static final class LcsVisitor implements CommandVisitor { - private final ArrayList sequence; - - LcsVisitor() { - sequence = new ArrayList<>(); - } - - public List getSubSequence() { - return sequence; - } - - @Override - public void visitDeleteCommand(final E object) { - // noop - } - - @Override - public void visitInsertCommand(final E object) { - // noop - } - - @Override - public void visitKeepCommand(final E object) { - sequence.add(object); - } - } - - /** - * 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 (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 boolean isEmpty() { - return list.isEmpty(); - } - - @Override - public int size() { - return (int) Math.ceil((double) list.size() / (double) size); - } - } - - /** - * 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 {@code null} - * @since 4.0 - */ - public static List defaultIfNull(final List list, final List defaultList) { - return list == null ? defaultList : list; - } - - /** - * Returns an immutable empty list if the argument is {@code null}, - * or the argument itself otherwise. - * - * @param the element type - * @param list the list, possibly {@code null} - * @return an empty list if the argument is {@code null} - */ - public static List emptyIfNull(final List list) { - return list == null ? Collections.emptyList() : list; - } - - /** - * 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 NullPointerException if the List is null - */ - public static List fixedSizeList(final List list) { - return FixedSizeList.fixedSizeList(list); - } - - /** - * Gets the first element of a list. - *

- * Shorthand for {@code list.get(0)} - *

- * @param The list type. - * @param list The list. - * @return the first element of a list. - * @see List#get(int) - * @since 4.5 - */ - public static T getFirst(final List list) { - return Objects.requireNonNull(list, "list").get(0); - } - - /** - * Gets the last element of a list. - *

- * Shorthand for {@code list.get(list.size() - 1)} - *

- * @param The list type. - * @param list The list. - * @return the last element of a list. - * @see List#get(int) - * @since 4.5 - */ - public static T getLast(final List list) { - return Objects.requireNonNull(list, "list").get(list.size() - 1); - } - - /** - * Generates a hash code using the algorithm specified in - * {@link java.util.List#hashCode()}. - *

- * This method is useful for implementing {@code 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; - - for (final Object obj : list) { - hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode()); - } - return hashCode; - } - - /** - * 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 CollectionUtils.INDEX_NOT_FOUND; - } - - /** - * 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; - } - - /** - * Tests two lists for value-equality as per the equality contract in - * {@link java.util.List#equals(Object)}. - *

- * This method is useful for implementing {@code 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 - * {@code 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 {@code e1} and - * {@code 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 {@code List} interface. - *
- * - * Note: The behavior 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(); - - while (it1.hasNext() && it2.hasNext()) { - final Object obj1 = it1.next(); - final Object obj2 = it2.next(); - - if (!Objects.equals(obj1, obj2)) { - return false; - } - } - - return !(it1.hasNext() || it2.hasNext()); - } - - /** - * 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, {@code date} will refer to - * a new {@code Date} instance. Furthermore, that {@code Date} - * instance is the fourth element in the list. The first, second, - * and third element are all set to {@code 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 NullPointerException if the List or Factory is null - */ - public static List lazyList(final List list, final Factory factory) { - return LazyList.lazyList(list, factory); - } - - /** - * 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 transformer will be used - * to create a new object and that object will be inserted at that index. - *

- * For instance: - * - *

-     * List<Integer> hours = Arrays.asList(7, 5, 8, 2);
-     * Transformer<Integer,Date> transformer = input -> LocalDateTime.now().withHour(hours.get(input));
-     * List<LocalDateTime> lazy = ListUtils.lazyList(new ArrayList<LocalDateTime>(), transformer);
-     * Date date = lazy.get(3);
-     * 
- * - * After the above code is executed, {@code date} will refer to - * a new {@code Date} instance. Furthermore, that {@code Date} - * instance is the fourth element in the list. The first, second, - * and third element are all set to {@code null}. - * - * @param the element type - * @param list the list to make lazy, must not be null - * @param transformer the transformer for creating new objects, must not be null - * @return a lazy list backed by the given list - * @throws NullPointerException if the List or Transformer is null - */ - public static List lazyList(final List list, final Transformer transformer) { - return LazyList.lazyList(list, transformer); - } - - /** - * 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 charSequenceA the first sequence - * @param charSequenceB the second sequence - * @return the longest common subsequence as {@link String} - * @throws NullPointerException if either sequence is {@code null} - * @since 4.0 - */ - public static String longestCommonSubsequence(final CharSequence charSequenceA, final CharSequence charSequenceB) { - Objects.requireNonNull(charSequenceA, "charSequenceA"); - Objects.requireNonNull(charSequenceB, "charSequenceB"); - final List lcs = longestCommonSubsequence(new CharSequenceAsList(charSequenceA), - new CharSequenceAsList(charSequenceB)); - final StringBuilder sb = new StringBuilder(); - for (final Character ch : lcs) { - sb.append(ch); - } - return sb.toString(); - } - - /** - * 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 NullPointerException 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 listA the first list - * @param listB the second list - * @param equator the equator used to test object equality - * @return the longest common subsequence - * @throws NullPointerException if either list or the equator is {@code null} - * @since 4.0 - */ - public static List longestCommonSubsequence(final List listA, final List listB, - final Equator equator) { - Objects.requireNonNull(listA, "listA"); - Objects.requireNonNull(listB, "listB"); - Objects.requireNonNull(equator, "equator"); - - final SequencesComparator comparator = new SequencesComparator<>(listA, listB, equator); - final EditScript script = comparator.getScript(); - final LcsVisitor visitor = new LcsVisitor<>(); - script.visit(visitor); - return visitor.getSubSequence(); - } - - /** - * 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 https://github.com/google/guava - * - * @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 NullPointerException if list is null - * @throws IllegalArgumentException if size is not strictly positive - * @since 4.0 - */ - public static List> partition(final List list, final int size) { - Objects.requireNonNull(list, "list"); - if (size <= 0) { - throw new IllegalArgumentException("Size must be greater than 0"); - } - return new Partition<>(list, size); - } - - /** - * 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 NullPointerException if the List or Predicate is null - */ - public static List predicatedList(final List list, final Predicate predicate) { - return PredicatedList.predicatedList(list, predicate); - } - - /** - * Removes the elements in {@code remove} from {@code collection}. That is, this - * method returns a list containing all the elements in {@code collection} - * that are not in {@code remove}. The cardinality of an element {@code e} - * in the returned collection is the same as the cardinality of {@code e} - * in {@code collection} unless {@code remove} contains {@code e}, in which - * case the cardinality is zero. This method is useful if you do not wish to modify - * {@code collection} and thus cannot call {@code collection.removeAll(remove);}. - *

- * This implementation iterates over {@code collection}, checking each element in - * turn to see if it's contained in {@code 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 - * {@code 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 {@code collection} - * @return a {@code List} containing all the elements of {@code c} except - * any elements that also occur in {@code remove}. - * @throws NullPointerException if either parameter is null - * @since 3.2 - */ - public static List removeAll(final Collection collection, final Collection remove) { - Objects.requireNonNull(collection, "collection"); - Objects.requireNonNull(remove, "remove"); - final List list = new ArrayList<>(); - for (final E obj : collection) { - if (!remove.contains(obj)) { - list.add(obj); - } - } - return list; - } - - /** - * Returns a List containing all the elements in {@code collection} - * that are also in {@code retain}. The cardinality of an element {@code e} - * in the returned list is the same as the cardinality of {@code e} - * in {@code collection} unless {@code retain} does not contain {@code e}, in which - * case the cardinality is zero. This method is useful if you do not wish to modify - * the collection {@code c} and thus cannot call {@code collection.retainAll(retain);}. - *

- * This implementation iterates over {@code collection}, checking each element in - * turn to see if it's contained in {@code retain}. If it's contained, it's added - * to the returned list. As a consequence, it is advised to use a collection type for - * {@code 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 {@code List} containing all the elements of {@code c} - * that occur at least once in {@code 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; - } - - /** - * Selects all elements from input collection which match the given - * predicate into an output list. - *

- * A {@code 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 {@code 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())); - } - - /** - * 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 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 NullPointerException if the list is null - */ - public static List synchronizedList(final List list) { - return Collections.synchronizedList(list); - } - - /** - * 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 behavior, 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 NullPointerException if the List or Transformer is null - */ - public static List transformedList(final List list, - final Transformer transformer) { - return TransformedList.transformingList(list, transformer); - } - - /** - * 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.size() + list2.size()); - result.addAll(list1); - result.addAll(list2); - return result; - } - - /** - * 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 NullPointerException if the list is null - */ - public static List unmodifiableList(final List list) { - return UnmodifiableList.unmodifiableList(list); - } - - /** - * Don't allow instances. - */ - private ListUtils() {} -} diff --git a/src/main/java/repack/apache/commons/collections4/ListValuedMap.java b/src/main/java/repack/apache/commons/collections4/ListValuedMap.java deleted file mode 100644 index f2168b1bf6..0000000000 --- a/src/main/java/repack/apache/commons/collections4/ListValuedMap.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.List; - -/** - * Defines a map that holds a list of values against each key. - *

- * A {@code ListValuedMap} is a Map with slightly different semantics: - *

- *
    - *
  • Putting a value into the map will add the value to a {@link List} at that key.
  • - *
  • Getting a value will return a {@link List}, holding all the values put to that key.
  • - *
- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.1 - */ -public interface ListValuedMap extends MultiValuedMap { - - /** - * Gets the list of values associated with the specified key. - *

- * This method will return an empty list if - * {@link #containsKey(Object)} returns {@code false}. Changes to the - * returned list will update the underlying {@code ListValuedMap} and - * vice-versa. - * - * @param key the key to retrieve - * @return the {@code List} of values, implementations should return an - * empty {@code List} for no mapping - * @throws NullPointerException if the key is null and null keys are invalid - */ - @Override - List get(K key); - - /** - * Removes all values associated with the specified key. - *

- * The returned list may be modifiable, but updates will not be - * propagated to this list-valued map. In case no mapping was stored for the - * specified key, an empty, unmodifiable list will be returned. - * - * @param key the key to remove values from - * @return the {@code List} of values removed, implementations - * typically return an empty, unmodifiable {@code List} for no mapping found - * @throws UnsupportedOperationException if the map is unmodifiable - * @throws NullPointerException if the key is null and null keys are invalid - */ - @Override - List remove(Object key); - -} diff --git a/src/main/java/repack/apache/commons/collections4/MapIterator.java b/src/main/java/repack/apache/commons/collections4/MapIterator.java deleted file mode 100644 index 5744b0e98d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/MapIterator.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Iterator; - -/** - * Defines an iterator that operates over a {@code 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 {@code next()}, the {@code getValue()} method provides direct - * access to the value. The value can also be set using {@code setValue()}. - *

- *
{@code
- * 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 - */ -public interface MapIterator extends Iterator { - - /** - * Checks to see if there are more entries still to be iterated. - * - * @return {@code true} if the iterator has more elements - */ - @Override - boolean hasNext(); - - /** - * Gets the next key from the {@code Map}. - * - * @return the next key in the iteration - * @throws java.util.NoSuchElementException if the iteration is finished - */ - @Override - K next(); - - /** - * Gets the current key, which is the key returned by the last call - * to {@code next()}. - * - * @return the current key - * @throws IllegalStateException if {@code next()} has not yet been called - */ - K getKey(); - - /** - * Gets the current value, which is the value associated with the last key - * returned by {@code next()}. - * - * @return the current value - * @throws IllegalStateException if {@code next()} has not yet been called - */ - V getValue(); - - /** - * Removes the last returned key from the underlying {@code Map} (optional operation). - *

- * This method can be called once per call to {@code next()}. - * - * @throws UnsupportedOperationException if remove is not supported by the map - * @throws IllegalStateException if {@code next()} has not yet been called - * @throws IllegalStateException if {@code remove()} has already been called - * since the last call to {@code next()} - */ - @Override - 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 {@code next()} has not yet been called - * @throws IllegalStateException if {@code remove()} has been called since the - * last call to {@code next()} - */ - V setValue(V value); - -} diff --git a/src/main/java/repack/apache/commons/collections4/MapUtils.java b/src/main/java/repack/apache/commons/collections4/MapUtils.java deleted file mode 100644 index 71ca9cbed3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/MapUtils.java +++ /dev/null @@ -1,2031 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.io.PrintStream; -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.ArrayDeque; -import java.util.Collection; -import java.util.Collections; -import java.util.Deque; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Properties; -import java.util.ResourceBundle; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.function.BiFunction; -import java.util.function.Function; - -import repack.apache.commons.collections4.map.AbstractMapDecorator; -import repack.apache.commons.collections4.map.AbstractSortedMapDecorator; -import repack.apache.commons.collections4.map.FixedSizeMap; -import repack.apache.commons.collections4.map.FixedSizeSortedMap; -import repack.apache.commons.collections4.map.LazyMap; -import repack.apache.commons.collections4.map.LazySortedMap; -import repack.apache.commons.collections4.map.ListOrderedMap; -import repack.apache.commons.collections4.map.MultiValueMap; -import repack.apache.commons.collections4.map.PredicatedMap; -import repack.apache.commons.collections4.map.PredicatedSortedMap; -import repack.apache.commons.collections4.map.TransformedMap; -import repack.apache.commons.collections4.map.TransformedSortedMap; -import repack.apache.commons.collections4.map.UnmodifiableMap; -import repack.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 - */ -@SuppressWarnings("deprecation") -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 = " "; - - /** - * Applies the {@code getFunction} and returns its result if non-null, if null returns the result of applying the - * default function. - * - * @param The key type. - * @param The result type. - * @param map The map to query. - * @param key The key into the map. - * @param getFunction The get function. - * @param defaultFunction The function to provide a default value. - * @return The result of applying a function. - */ - private static R applyDefaultFunction(final Map map, final K key, - final BiFunction, K, R> getFunction, final Function defaultFunction) { - return applyDefaultFunction(map, key, getFunction, defaultFunction, null); - } - - /** - * Applies the {@code getFunction} and returns its result if non-null, if null returns the result of applying the - * default function. - * - * @param The key type. - * @param The result type. - * @param map The map to query. - * @param key The key into the map. - * @param getFunction The get function. - * @param defaultFunction The function to provide a default value. - * @param defaultValue The default value. - * @return The result of applying a function. - */ - private static R applyDefaultFunction(final Map map, final K key, - final BiFunction, K, R> getFunction, final Function defaultFunction, - final R defaultValue) { - R value = map != null && getFunction != null ? getFunction.apply(map, key) : null; - if (value == null) { - value = defaultFunction != null ? defaultFunction.apply(key) : null; - } - return value != null ? value : defaultValue; - } - - /** - * Applies the {@code getFunction} and returns its result if non-null, if null returns the {@code defaultValue}. - * - * @param The key type. - * @param The result type. - * @param map The map to query. - * @param key The key into the map. - * @param getFunction The get function. - * @param defaultValue The default value. - * @return The result of applying a function. - */ - private static R applyDefaultValue(final Map map, final K key, - final BiFunction, K, R> getFunction, final R defaultValue) { - final R value = map != null && getFunction != null ? getFunction.apply(map, key) : null; - return value == null ? defaultValue : value; - } - - /** - * 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 behavior 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 {@code null}. If {@code 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 {@code null}. If {@code null}, the text 'null' is output. - * @throws NullPointerException if the stream is {@code null} - */ - public static void debugPrint(final PrintStream out, final Object label, final Map map) { - verbosePrintInternal(out, label, map, new ArrayDeque<>(), true); - } - - /** - * Returns an immutable empty map if the argument is {@code null}, or the argument itself otherwise. - * - * @param the key type - * @param the value type - * @param map the map, possibly {@code null} - * @return an empty map if the argument is {@code null} - */ - public static Map emptyIfNull(final Map map) { - return map == null ? Collections.emptyMap() : map; - } - - /** - * 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 NullPointerException if the Map is null - */ - public static IterableMap fixedSizeMap(final Map map) { - return FixedSizeMap.fixedSizeMap(map); - } - - /** - * 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 NullPointerException if the SortedMap is null - */ - public static SortedMap fixedSizeSortedMap(final SortedMap map) { - return FixedSizeSortedMap.fixedSizeSortedMap(map); - } - - /** - * Gets a Boolean from a Map in a null-safe manner. - *

- * If the value is a {@code Boolean} it is returned directly. If the value is a {@code String} and it - * equals 'true' ignoring case then {@code true} is returned, otherwise {@code false}. If the value is a - * {@code Number} an integer zero value returns {@code false} and non-zero returns {@code true}. - * Otherwise, {@code 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, {@code 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; - } - - /** - * Looks up the given key in the given map, converting the result into a boolean, using the default value if 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) { - return applyDefaultValue(map, key, MapUtils::getBoolean, defaultValue); - } - - /** - * Looks up the given key in the given map, converting the result into a boolean, using the defaultFunction to - * produce the default value if 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 defaultFunction what to produce the default value if the value is null or if the conversion fails - * @return the value in the map as a boolean, or defaultValue produced by the defaultFunction if the original value - * is null, the map is null or the boolean conversion fails - * @since 4.5 - */ - public static Boolean getBoolean(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getBoolean, defaultFunction); - } - - /** - * Gets a boolean from a Map in a null-safe manner. - *

- * If the value is a {@code Boolean} its value is returned. If the value is a {@code String} and it equals - * 'true' ignoring case then {@code true} is returned, otherwise {@code false}. If the value is a - * {@code Number} an integer zero value returns {@code false} and non-zero returns {@code true}. - * Otherwise, {@code 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, {@code false} if null map input - */ - public static boolean getBooleanValue(final Map map, final K key) { - return Boolean.TRUE.equals(getBoolean(map, key)); - } - - /** - * Gets a boolean from a Map in a null-safe manner, using the default value if the conversion fails. - *

- * If the value is a {@code Boolean} its value is returned. If the value is a {@code String} and it equals - * 'true' ignoring case then {@code true} is returned, otherwise {@code false}. If the value is a - * {@code Number} an integer zero value returns {@code false} and non-zero returns {@code true}. - * Otherwise, {@code 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, {@code defaultValue} if null map input - */ - public static boolean getBooleanValue(final Map map, final K key, final boolean defaultValue) { - return applyDefaultValue(map, key, MapUtils::getBoolean, defaultValue).booleanValue(); - } - - /** - * Gets a boolean from a Map in a null-safe manner, using the default value produced by the defaultFunction if the - * conversion fails. - *

- * If the value is a {@code Boolean} its value is returned. If the value is a {@code String} and it equals - * 'true' ignoring case then {@code true} is returned, otherwise {@code false}. If the value is a - * {@code Number} an integer zero value returns {@code false} and non-zero returns {@code true}. - * Otherwise, defaultValue produced by the {@code defaultFunction} is returned. - *

- * - * @param the key type - * @param map the map to use - * @param key the key to look up - * @param defaultFunction produce the default value to return if the value is null or if the conversion fails - * @return the value in the Map as a Boolean, default value produced by the {@code defaultFunction} if null map - * input - * @since 4.5 - */ - public static boolean getBooleanValue(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getBoolean, defaultFunction, false).booleanValue(); - } - - /** - * Gets a Byte from a Map in a null-safe manner. - *

- * The Byte is obtained from the results of {@link #getNumber(Map,Object)}. - *

- * - * @param 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, {@code 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()); - } - - /** - * Looks up the given key in the given map, converting the result into a byte, using the default value if 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) { - return applyDefaultValue(map, key, MapUtils::getByte, defaultValue); - } - - /** - * Looks up the given key in the given map, converting the result into a byte, using the defaultFunction to produce - * the default value if 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 defaultFunction what to produce the default value if the value is null or if the conversion fails - * @return the value in the map as a number, or defaultValue produced by the defaultFunction if the original value - * is null, the map is null or the number conversion fails - * @since 4.5 - */ - public static Byte getByte(final Map map, final K key, final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getByte, defaultFunction); - } - - /** - * 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, {@code 0} if null map input - */ - public static byte getByteValue(final Map map, final K key) { - return applyDefaultValue(map, key, MapUtils::getByte, 0).byteValue(); - } - - /** - * Gets a byte from a Map in a null-safe manner, using the default value if 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, {@code defaultValue} if null map input - */ - public static byte getByteValue(final Map map, final K key, final byte defaultValue) { - return applyDefaultValue(map, key, MapUtils::getByte, defaultValue).byteValue(); - } - - /** - * Gets a byte from a Map in a null-safe manner, using the default value produced by the defaultFunction if 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 defaultFunction produce the default value to return if the value is null or if the conversion fails - * @return the value in the Map as a byte, default value produced by the {@code defaultFunction} if null map - * input - * @since 4.5 - */ - public static byte getByteValue(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getByte, defaultFunction, (byte) 0).byteValue(); - } - - /** - * 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, {@code 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()); - } - - /** - * Looks up the given key in the given map, converting the result into a double, using the default value if 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) { - return applyDefaultValue(map, key, MapUtils::getDouble, defaultValue); - } - - /** - * Looks up the given key in the given map, converting the result into a double, using the defaultFunction to - * produce the default value if 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 defaultFunction what to produce the default value if the value is null or if the conversion fails - * @return the value in the map as a number, or defaultValue produced by the defaultFunction if the original value - * is null, the map is null or the number conversion fails - * @since 4.5 - */ - public static Double getDouble(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getDouble, defaultFunction); - } - - /** - * 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, {@code 0.0} if null map input - */ - public static double getDoubleValue(final Map map, final K key) { - return applyDefaultValue(map, key, MapUtils::getDouble, 0d).doubleValue(); - } - - /** - * Gets a double from a Map in a null-safe manner, using the default value if 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, {@code defaultValue} if null map input - */ - public static double getDoubleValue(final Map map, final K key, final double defaultValue) { - return applyDefaultValue(map, key, MapUtils::getDouble, defaultValue).doubleValue(); - } - - /** - * Gets a double from a Map in a null-safe manner, using the default value produced by the defaultFunction if 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 defaultFunction produce the default value to return if the value is null or if the conversion fails - * @return the value in the Map as a double, default value produced by the {@code defaultFunction} if null map - * input - * @since 4.5 - */ - public static double getDoubleValue(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getDouble, defaultFunction, 0d).doubleValue(); - } - - /** - * 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, {@code 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()); - } - - /** - * Looks up the given key in the given map, converting the result into a float, using the default value if 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) { - return applyDefaultValue(map, key, MapUtils::getFloat, defaultValue); - } - - /** - * Looks up the given key in the given map, converting the result into a float, using the defaultFunction to produce - * the default value if 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 defaultFunction what to produce the default value if the value is null or if the conversion fails - * @return the value in the map as a number, or defaultValue produced by the defaultFunction if the original value - * is null, the map is null or the number conversion fails - * @since 4.5 - */ - public static Float getFloat(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getFloat, defaultFunction); - } - - /** - * 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, {@code 0.0F} if null map input - */ - public static float getFloatValue(final Map map, final K key) { - return applyDefaultValue(map, key, MapUtils::getFloat, 0f).floatValue(); - } - - /** - * Gets a float from a Map in a null-safe manner, using the default value if 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, {@code defaultValue} if null map input - */ - public static float getFloatValue(final Map map, final K key, final float defaultValue) { - return applyDefaultValue(map, key, MapUtils::getFloat, defaultValue).floatValue(); - } - - /** - * Gets a float from a Map in a null-safe manner, using the default value produced by the defaultFunction if 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 defaultFunction produce the default value to return if the value is null or if the conversion fails - * @return the value in the Map as a float, default value produced by the {@code defaultFunction} if null map - * input - * @since 4.5 - */ - public static float getFloatValue(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getFloat, defaultFunction, 0f).floatValue(); - } - - /** - * Gets an 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 an Integer, {@code 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()); - } - - /** - * Looks up the given key in the given map, converting the result into an integer, using the defaultFunction to - * produce the default value if 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 defaultFunction what to produce the default value if the value is null or if the conversion fails - * @return the value in the map as a number, or defaultValue produced by the defaultFunction if the original value - * is null, the map is null or the number conversion fails - * @since 4.5 - */ - public static Integer getInteger(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getInteger, defaultFunction); - } - - /** - * Looks up the given key in the given map, converting the result into an integer, using the default value if 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) { - return applyDefaultValue(map, key, MapUtils::getInteger, defaultValue); - } - - /** - * 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, {@code 0} if null map input - */ - public static int getIntValue(final Map map, final K key) { - return applyDefaultValue(map, key, MapUtils::getInteger, 0).intValue(); - } - - /** - * Gets an int from a Map in a null-safe manner, using the default value produced by the defaultFunction if 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 defaultFunction produce the default value to return if the value is null or if the conversion fails - * @return the value in the Map as an int, default value produced by the {@code defaultFunction} if null map - * input - * @since 4.5 - */ - public static int getIntValue(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getInteger, defaultFunction, 0).byteValue(); - } - - /** - * Gets an int from a Map in a null-safe manner, using the default value if 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, {@code defaultValue} if null map input - */ - public static int getIntValue(final Map map, final K key, final int defaultValue) { - return applyDefaultValue(map, key, MapUtils::getInteger, defaultValue).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, {@code 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()); - } - - /** - * Looks up the given key in the given map, converting the result into a Long, using the defaultFunction to produce - * the default value if 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 defaultFunction what to produce the default value if the value is null or if the conversion fails - * @return the value in the map as a number, or defaultValue produced by the defaultFunction if the original value - * is null, the map is null or the number conversion fails - * @since 4.5 - */ - public static Long getLong(final Map map, final K key, final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getLong, defaultFunction); - } - - /** - * Looks up the given key in the given map, converting the result into a long, using the default value if 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) { - return applyDefaultValue(map, key, MapUtils::getLong, defaultValue); - } - - /** - * 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, {@code 0L} if null map input - */ - public static long getLongValue(final Map map, final K key) { - return applyDefaultValue(map, key, MapUtils::getLong, 0L).longValue(); - } - - /** - * Gets a long from a Map in a null-safe manner, using the default value produced by the defaultFunction if 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 defaultFunction produce the default value to return if the value is null or if the conversion fails - * @return the value in the Map as a long, default value produced by the {@code defaultFunction} if null map - * input - * @since 4.5 - */ - public static long getLongValue(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getLong, defaultFunction, 0L).byteValue(); - } - - /** - * Gets a long from a Map in a null-safe manner, using the default value if 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, {@code defaultValue} if null map input - */ - public static long getLongValue(final Map map, final K key, final long defaultValue) { - return applyDefaultValue(map, key, MapUtils::getLong, defaultValue).longValue(); - } - - /** - * Gets a Map from a Map in a null-safe manner. - *

- * If the value returned from the specified map is not a Map then {@code 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, {@code 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 instanceof Map) { - return (Map) answer; - } - } - return null; - } - - /** - * Looks up the given key in the given map, converting the result into a map, using the defaultFunction to produce - * the default value if 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 defaultFunction what to produce the default value if the value is null or if the conversion fails - * @return the value in the map as a number, or defaultValue produced by the defaultFunction if the original value - * is null, the map is null or the map conversion fails - * @since 4.5 - */ - public static Map getMap(final Map map, final K key, - final Function> defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getMap, defaultFunction); - } - - /** - * Looks up the given key in the given map, converting the result into a map, using the default value if 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) { - return applyDefaultValue(map, key, MapUtils::getMap, defaultValue); - } - - /** - * Gets a Number from a Map in a null-safe manner. - *

- * If the value is a {@code Number} it is returned directly. If the value is a {@code String} it is - * converted using {@link NumberFormat#parse(String)} on the system default formatter returning {@code null} if - * the conversion fails. Otherwise, {@code 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, {@code 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; - } - - /** - * Looks up the given key in the given map, converting the result into a number, using the defaultFunction to - * produce the default value if 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 defaultFunction what to produce the default value if the value is null or if the conversion fails - * @return the value in the map as a number, or defaultValue produced by the defaultFunction if the original value - * is null, the map is null or the number conversion fails - * @since 4.5 - */ - public static Number getNumber(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getNumber, defaultFunction); - } - - /** - * Looks up the given key in the given map, converting the result into a number, using the default value if 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) { - return applyDefaultValue(map, key, MapUtils::getNumber, defaultValue); - } - - /** - * 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, {@code null} if null map input - */ - public static V getObject(final Map map, final K key) { - if (map != null) { - return map.get(key); - } - return null; - } - - /** - * 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; - } - - /** - * 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, {@code 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()); - } - - /** - * Looks up the given key in the given map, converting the result into a short, using the defaultFunction to produce - * the default value if 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 defaultFunction what to produce the default value if the value is null or if the conversion fails - * @return the value in the map as a number, or defaultValue produced by the defaultFunction if the original value - * is null, the map is null or the number conversion fails - * @since 4.5 - */ - public static Short getShort(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getShort, defaultFunction); - } - - /** - * Looks up the given key in the given map, converting the result into a short, using the default value if 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) { - return applyDefaultValue(map, key, MapUtils::getShort, defaultValue); - } - - /** - * 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, {@code 0} if null map input - */ - public static short getShortValue(final Map map, final K key) { - return applyDefaultValue(map, key, MapUtils::getShort, 0).shortValue(); - } - - /** - * Gets a short from a Map in a null-safe manner, using the default value produced by the defaultFunction if 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 defaultFunction produce the default value to return if the value is null or if the conversion fails - * @return the value in the Map as a short, default value produced by the {@code defaultFunction} if null map - * input - * @since 4.5 - */ - public static short getShortValue(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getShort, defaultFunction, (short) 0).shortValue(); - } - - /** - * Gets a short from a Map in a null-safe manner, using the default value if 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, {@code defaultValue} if null map input - */ - public static short getShortValue(final Map map, final K key, final short defaultValue) { - return applyDefaultValue(map, key, MapUtils::getShort, defaultValue).shortValue(); - } - - /** - * Gets a String from a Map in a null-safe manner. - *

- * The String is obtained via {@code 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, {@code 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; - } - - /** - * Looks up the given key in the given map, converting the result into a string, using the defaultFunction to - * produce the default value if 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 defaultFunction what to produce the default value if the value is null or if the conversion fails - * @return the value in the map as a string, or defaultValue produced by the defaultFunction if the original value - * is null, the map is null or the string conversion fails - * @since 4.5 - */ - public static String getString(final Map map, final K key, - final Function defaultFunction) { - return applyDefaultFunction(map, key, MapUtils::getString, defaultFunction); - } - - /** - * Looks up the given key in the given map, converting the result into a string, using the default value if 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) { - return applyDefaultValue(map, key, MapUtils::getString, defaultValue); - } - - /** - * 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, must 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) { - Objects.requireNonNull(map, "map"); - final Map out = new HashMap<>(map.size()); - for (final Entry entry : map.entrySet()) { - out.put(entry.getValue(), entry.getKey()); - } - return out; - } - - /** - * 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); - } - - /** - * 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<K, V> - * @throws NullPointerException if map is null - * @since 4.0 - */ - public static IterableMap iterableMap(final Map map) { - Objects.requireNonNull(map, "map"); - return map instanceof IterableMap ? (IterableMap) map : new AbstractMapDecorator(map) { - // empty - }; - } - - /** - * 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}<K, V> - * @throws NullPointerException if sortedMap is null - * @since 4.0 - */ - public static IterableSortedMap iterableSortedMap(final SortedMap sortedMap) { - Objects.requireNonNull(sortedMap, "sortedMap"); - return sortedMap instanceof IterableSortedMap ? (IterableSortedMap) sortedMap - : new AbstractSortedMapDecorator(sortedMap) { - // empty - }; - } - - /** - * 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, {@code obj} will contain a new {@code Date} instance. Furthermore, - * that {@code Date} instance is the value for the {@code "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 NullPointerException 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, {@code obj} will contain a new {@code File} instance for the C drive - * dev directory. Furthermore, that {@code File} instance is the value for the {@code "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 NullPointerException if the Map or Transformer is null - */ - public static IterableMap lazyMap(final Map map, - final Transformer transformerFactory) { - return LazyMap.lazyMap(map, transformerFactory); - } - - /** - * 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, {@code obj} will contain a new {@code Date} instance. Furthermore, - * that {@code Date} instance is the value for the {@code "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 NullPointerException 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, {@code obj} will contain a new {@code File} instance for the C drive - * dev directory. Furthermore, that {@code File} instance is the value for the {@code "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 NullPointerException if the Map or Transformer is null - */ - public static SortedMap lazySortedMap(final SortedMap map, - final Transformer transformerFactory) { - return LazySortedMap.lazySortedMap(map, transformerFactory); - } - - /** - * Creates a multi-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 - * @deprecated since 4.1, use {@link MultiValuedMap} instead - */ - @Deprecated - 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 - * @deprecated since 4.1, use {@link MultiValuedMap} instead - */ - @Deprecated - 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 - * @deprecated since 4.1, use {@link MultiValuedMap} instead - */ - @Deprecated - public static > MultiValueMap multiValueMap(final Map map, - final Factory collectionFactory) { - return MultiValueMap.multiValueMap(map, collectionFactory); - } - - /** - * 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 NullPointerException if the Map is null - */ - public static OrderedMap orderedMap(final Map map) { - return ListOrderedMap.listOrderedMap(map); - } - - /** - * Populates a Map using the supplied {@code Transformer}s 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 {@code Map} to populate. - * @param elements the {@code Iterable} containing the input values for the map. - * @param keyTransformer the {@code Transformer} used to transform the element into a key value - * @param valueTransformer the {@code 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) { - for (final E temp : elements) { - map.put(keyTransformer.transform(temp), valueTransformer.transform(temp)); - } - } - - /** - * Populates a Map using the supplied {@code Transformer} to transform the elements into keys, using the - * unaltered element as the value in the {@code Map}. - * - * @param the key type - * @param the value type - * @param map the {@code Map} to populate. - * @param elements the {@code Iterable} containing the input values for the map. - * @param keyTransformer the {@code 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 MultiMap using the supplied {@code Transformer}s 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 {@code MultiMap} to populate. - * @param elements the {@code Iterable} containing the input values for the map. - * @param keyTransformer the {@code Transformer} used to transform the element into a key value - * @param valueTransformer the {@code 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) { - for (final E temp : elements) { - map.put(keyTransformer.transform(temp), valueTransformer.transform(temp)); - } - } - - /** - * Populates a MultiMap using the supplied {@code Transformer} to transform the elements into keys, using the - * unaltered element as the value in the {@code MultiMap}. - * - * @param the key type - * @param the value type - * @param map the {@code MultiMap} to populate. - * @param elements the {@code Iterable} to use as input values for the map. - * @param keyTransformer the {@code 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()); - } - - /** - * 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 NullPointerException 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 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 NullPointerException if the SortedMap is null - */ - public static SortedMap predicatedSortedMap(final SortedMap map, - final Predicate keyPred, final Predicate valuePred) { - return PredicatedSortedMap.predicatedSortedMap(map, keyPred, valuePred); - } - - /** - * Writes indentation to the given stream. - * - * @param out the stream to indent - * @param indent the index of the indentation - */ - private static void printIndent(final PrintStream out, final int indent) { - for (int i = 0; i < indent; i++) { - out.print(INDENT_STRING); - } - } - - /** - * 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) { - Objects.requireNonNull(map, "map"); - 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; - } - - /** - * 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, must 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 { - Objects.requireNonNull(map, "map"); - map.put(key, value == null ? "" : value); - } - - /** - * Gets the given map size or 0 if the map is null - * - * @param map a Map or null - * @return the given map size or 0 if the map is null - */ - public static int size(final Map map) { - return map == null ? 0 : map.size(); - } - - /** - * 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 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 NullPointerException if the map is null - */ - public static SortedMap synchronizedSortedMap(final SortedMap map) { - return Collections.synchronizedSortedMap(map); - } - - /** - * Creates a new HashMap using data copied from a ResourceBundle. - * - * @param resourceBundle the resource bundle to convert, must not be null - * @return the HashMap containing the data - * @throws NullPointerException if the bundle is null - */ - public static Map toMap(final ResourceBundle resourceBundle) { - Objects.requireNonNull(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; - } - - /** - * Gets a new Properties object initialized with the values from a Map. A null input will return an empty properties - * object. - *

- * A Properties object may only store non-null keys and values, thus if the provided map contains either a key or - * value which is {@code null}, a {@link NullPointerException} will be thrown. - *

- * - * @param the key type - * @param the value type - * @param map the map to convert to a Properties object - * @return the properties object - * @throws NullPointerException if a key or value in the provided map is {@code null} - */ - 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; - } - - /** - * 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 behavior, 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 NullPointerException 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 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 behavior, 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 NullPointerException 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 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 NullPointerException if the map is null - */ - public static Map unmodifiableMap(final Map map) { - return UnmodifiableMap.unmodifiableMap(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 NullPointerException if the map is null - */ - public static SortedMap unmodifiableSortedMap(final SortedMap map) { - return UnmodifiableSortedMap.unmodifiableSortedMap(map); - } - - /** - * 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 behavior 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 {@code null}. If {@code 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 {@code null}. If {@code null}, the text 'null' is output. - * @throws NullPointerException if the stream is {@code null} - */ - public static void verbosePrint(final PrintStream out, final Object label, final Map map) { - verbosePrintInternal(out, label, map, new ArrayDeque<>(), false); - } - - /** - * 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 text (ancestor[i] Map) is printed, where it 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 {@code null}. If {@code 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 {@code null}. If {@code 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 {@code null} - */ - private static void verbosePrintInternal(final PrintStream out, final Object label, final Map map, - final Deque> 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.addLast(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 = IterableUtils.indexOf(lineage, PredicateUtils.equalPredicate(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.removeLast(); - - printIndent(out, lineage.size()); - out.println(debug ? "} " + map.getClass().getName() : "}"); - } - - /** - * Don't allow instances. - */ - private MapUtils() { - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/MultiMap.java b/src/main/java/repack/apache/commons/collections4/MultiMap.java deleted file mode 100644 index c1cbf23bd6..0000000000 --- a/src/main/java/repack/apache/commons/collections4/MultiMap.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Collection; - -/** - * Defines a map that holds a collection of values against each key. - *

- * A {@code 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);
- *

- * {@code 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 {@code Map} anyway. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * - * @since 2.0 - * @deprecated since 4.1, use {@link MultiValuedMap} instead - */ -@Deprecated -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 {@code null} from a subsequent {@code 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 - */ - @Override - int size(); - - /** - * Gets the collection of values associated with the specified key. - *

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

- * Implementations typically return {@code 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 {@code Collection} of values, implementations should - * return {@code 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 - */ - @Override - 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 - */ - @Override - boolean containsValue(Object value); - - /** - * Adds the value to the collection associated with the specified key. - *

- * Unlike a normal {@code 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 {@code List}, {@code 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 - */ - @Override - Object put(K key, Object value); - - /** - * Removes all values associated with the specified key. - *

- * Implementations typically return {@code null} from a subsequent - * {@code get(Object)}, however they may choose to return an empty collection. - * - * @param key the key to remove values from - * @return the {@code Collection} of values removed, implementations should - * return {@code 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 - */ - @Override - 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 - */ - @Override - Collection values(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/MultiMapUtils.java b/src/main/java/repack/apache/commons/collections4/MultiMapUtils.java deleted file mode 100644 index 07da0ca40f..0000000000 --- a/src/main/java/repack/apache/commons/collections4/MultiMapUtils.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import repack.apache.commons.collections4.bag.HashBag; -import repack.apache.commons.collections4.multimap.ArrayListValuedHashMap; -import repack.apache.commons.collections4.multimap.HashSetValuedHashMap; -import repack.apache.commons.collections4.multimap.TransformedMultiValuedMap; -import repack.apache.commons.collections4.multimap.UnmodifiableMultiValuedMap; - -/** - * Provides utility methods and decorators for {@link MultiValuedMap} instances. - *

- * It contains various type safe and null safe methods. Additionally, it provides - * the following decorators: - *

- *
    - *
  • {@link #unmodifiableMultiValuedMap(MultiValuedMap)}
  • - *
  • {@link #transformedMultiValuedMap(MultiValuedMap, Transformer, Transformer)}
  • - *
- * - * @since 4.1 - */ -public class MultiMapUtils { - - /** - * Don't allow instances. - */ - private MultiMapUtils() {} - - /** - * An empty {@link UnmodifiableMultiValuedMap}. - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static final MultiValuedMap EMPTY_MULTI_VALUED_MAP = - UnmodifiableMultiValuedMap.unmodifiableMultiValuedMap(new ArrayListValuedHashMap(0, 0)); - - /** - * Returns immutable EMPTY_MULTI_VALUED_MAP with generic type safety. - * - * @param the type of key in the map - * @param the type of value in the map - * @return immutable and empty {@code MultiValuedMap} - */ - @SuppressWarnings("unchecked") - public static MultiValuedMap emptyMultiValuedMap() { - return EMPTY_MULTI_VALUED_MAP; - } - - // Null safe methods - - /** - * Returns an immutable empty {@code MultiValuedMap} if the argument is - * {@code null}, or the argument itself otherwise. - * - * @param the type of key in the map - * @param the type of value in the map - * @param map the map, may be null - * @return an empty {@link MultiValuedMap} if the argument is null - */ - @SuppressWarnings("unchecked") - public static MultiValuedMap emptyIfNull(final MultiValuedMap map) { - return map == null ? EMPTY_MULTI_VALUED_MAP : map; - } - - /** - * Null-safe check if the specified {@code MultiValuedMap} is empty. - *

- * If the provided map is null, returns true. - * - * @param map the map to check, may be null - * @return true if the map is empty or null - */ - public static boolean isEmpty(final MultiValuedMap map) { - return map == null || map.isEmpty(); - } - - /** - * Gets a Collection from {@code MultiValuedMap} in a null-safe manner. - * - * @param the key type - * @param the value type - * @param map the {@link MultiValuedMap} to use - * @param key the key to look up - * @return the Collection in the {@link MultiValuedMap}, or null if input map is null - */ - public static Collection getCollection(final MultiValuedMap map, final K key) { - if (map != null) { - return map.get(key); - } - return null; - } - - // TODO: review the getValuesAsXXX methods - depending on the actual MultiValuedMap type, changes - // to the returned collection might update the backing map. This should be clarified and/or prevented. - - /** - * Gets a List from {@code MultiValuedMap} in a null-safe manner. - * - * @param the key type - * @param the value type - * @param map the {@link MultiValuedMap} to use - * @param key the key to look up - * @return the Collection in the {@link MultiValuedMap} as List, or null if input map is null - */ - public static List getValuesAsList(final MultiValuedMap map, final K key) { - if (map != null) { - final Collection col = map.get(key); - if (col instanceof List) { - return (List) col; - } - return new ArrayList<>(col); - } - return null; - } - - /** - * Gets a Set from {@code MultiValuedMap} in a null-safe manner. - * - * @param the key type - * @param the value type - * @param map the {@link MultiValuedMap} to use - * @param key the key to look up - * @return the Collection in the {@link MultiValuedMap} as Set, or null if input map is null - */ - public static Set getValuesAsSet(final MultiValuedMap map, final K key) { - if (map != null) { - final Collection col = map.get(key); - if (col instanceof Set) { - return (Set) col; - } - return new HashSet<>(col); - } - return null; - } - - /** - * Gets a Bag from {@code MultiValuedMap} in a null-safe manner. - * - * @param the key type - * @param the value type - * @param map the {@link MultiValuedMap} to use - * @param key the key to look up - * @return the Collection in the {@link MultiValuedMap} as Bag, or null if input map is null - */ - public static Bag getValuesAsBag(final MultiValuedMap map, final K key) { - if (map != null) { - final Collection col = map.get(key); - if (col instanceof Bag) { - return (Bag) col; - } - return new HashBag<>(col); - } - return null; - } - - /** - * Creates a {@link ListValuedMap} with an {@link java.util.ArrayList ArrayList} as - * collection class to store the values mapped to a key. - * - * @param the key type - * @param the value type - * @return a new {@code ListValuedMap} - */ - public static ListValuedMap newListValuedHashMap() { - return new ArrayListValuedHashMap<>(); - } - - /** - * Creates a {@link SetValuedMap} with an {@link java.util.HashSet HashSet} as - * collection class to store the values mapped to a key. - * - * @param the key type - * @param the value type - * @return a new {@link SetValuedMap} - */ - public static SetValuedMap newSetValuedHashMap() { - return new HashSetValuedHashMap<>(); - } - - /** - * Returns an {@code UnmodifiableMultiValuedMap} backed by the given - * map. - * - * @param the key type - * @param the value type - * @param map the {@link MultiValuedMap} to decorate, must not be null - * @return an unmodifiable {@link MultiValuedMap} backed by the provided map - * @throws NullPointerException if map is null - */ - public static MultiValuedMap unmodifiableMultiValuedMap( - final MultiValuedMap map) { - return UnmodifiableMultiValuedMap.unmodifiableMultiValuedMap(map); - } - - /** - * Returns a {@code TransformedMultiValuedMap} backed by the given map. - *

- * This method returns a new {@code MultiValuedMap} (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 - * behavior, see {@link TransformedMultiValuedMap#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 back door 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 {@link MultiValuedMap} 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 {@code MultiValuedMap} backed by the given map - * @throws NullPointerException if map is null - */ - public static MultiValuedMap transformedMultiValuedMap(final MultiValuedMap map, - final Transformer keyTransformer, - final Transformer valueTransformer) { - return TransformedMultiValuedMap.transformingMap(map, keyTransformer, valueTransformer); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/MultiSet.java b/src/main/java/repack/apache/commons/collections4/MultiSet.java deleted file mode 100644 index 66876ad54c..0000000000 --- a/src/main/java/repack/apache/commons/collections4/MultiSet.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 MultiSet that contains {@code {a, a, b, c}}. - * Calling {@link #getCount(Object)} on {@code a} would return 2, while - * calling {@link #uniqueSet()} would return {@code {a, b, c}}. - *

- * - * @param the type held in the multiset - * @since 4.1 - */ -public interface MultiSet extends Collection { - - /** - * Returns the number of occurrences of the given object currently - * in the MultiSet. If the object does not exist in the multiset, - * 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); - - /** - * Sets the number of occurrences of the specified object in the MultiSet - * to the given count. - *

- * If the provided count is zero, the object will be removed from the - * {@link #uniqueSet()}. - * - * @param object the object to update - * @param count the number of occurrences of the object - * @return the number of occurrences of the object before this operation, zero - * if the object was not contained in the multiset - * @throws IllegalArgumentException if count is negative - */ - int setCount(E object, int count); - - /** - * Adds one copy of the specified object to the MultiSet. - *

- * 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. - * - * @param object the object to add - * @return {@code true} always, as the size of the MultiSet is increased - * in any case - */ - @Override - boolean add(E object); - - /** - * Adds a number of occurrences of the specified object to the MultiSet. - *

- * 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 {@code occurrences}. - * - * @param object the object to add - * @param occurrences the number of occurrences to add, may be zero, - * in which case no change is made to the multiset - * @return the number of occurrences of the object in the multiset before - * this operation; possibly zero - * @throws IllegalArgumentException if occurrences is negative - */ - int add(E object, int occurrences); - - /** - * Removes one occurrence of the given object from the MultiSet. - *

- * If the number of occurrences after this operation is reduced - * to zero, the object will be removed from the {@link #uniqueSet()}. - * - * @param object the object to remove - * @return {@code true} if this call changed the collection - */ - @Override - boolean remove(Object object); - - /** - * Removes a number of occurrences of the specified object from the MultiSet. - *

- * If the number of occurrences to remove is greater than the actual number of - * occurrences in the multiset, the object will be removed from the multiset. - * - * @param object the object to remove - * @param occurrences the number of occurrences to remove, may be zero, - * in which case no change is made to the multiset - * @return the number of occurrences of the object in the multiset - * before the operation; possibly zero - * @throws IllegalArgumentException if occurrences is negative - */ - int remove(Object object, int occurrences); - - /** - * Returns a {@link Set} of unique elements in the MultiSet. - *

- * Uniqueness constraints are the same as those in {@link java.util.Set}. - *

- * The returned set is backed by this multiset, so any change to either - * is immediately reflected in the other. Only removal operations are - * supported, in which case all occurrences of the element are removed - * from the backing multiset. - * - * @return the Set of unique MultiSet elements - */ - Set uniqueSet(); - - /** - * Returns a {@link Set} of all entries contained in the MultiSet. - *

- * The returned set is backed by this multiset, so any change to either - * is immediately reflected in the other. - * - * @return the Set of MultiSet entries - */ - Set> entrySet(); - - /** - * 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 MultiSet - */ - @Override - Iterator iterator(); - - /** - * Returns the total number of items in the MultiSet. - * - * @return the total size of the multiset - */ - @Override - int size(); - - /** - * Returns {@code true} if the MultiSet contains at least one - * occurrence for each element contained in the given collection. - * - * @param coll the collection to check against - * @return {@code true} if the MultiSet contains all the collection - */ - @Override - boolean containsAll(Collection coll); - - /** - * Remove all occurrences of all elements from this MultiSet represented - * in the given collection. - * - * @param coll the collection of elements to remove - * @return {@code true} if this call changed the multiset - */ - @Override - boolean removeAll(Collection coll); - - /** - * Remove any elements of this MultiSet that are not contained in the - * given collection. - * - * @param coll the collection of elements to retain - * @return {@code true} if this call changed the multiset - */ - @Override - boolean retainAll(Collection coll); - - /** - * Compares this MultiSet to another object. - *

- * This MultiSet equals another object if it is also a MultiSet - * that contains the same number of occurrences of the same elements. - * - * @param obj the object to compare to - * @return true if equal - */ - @Override - boolean equals(Object obj); - - /** - * Gets a hash code for the MultiSet 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 - * {@code (e==null ? 0 : e.hashCode()) ^ noOccurrences)}. - * - * @return the hash code of the MultiSet - */ - @Override - int hashCode(); - - /** - * An unmodifiable entry for an element and its occurrence as contained in a MultiSet. - *

- * The {@link MultiSet#entrySet()} method returns a view of the multiset whose elements - * implement this interface. - * - * @param the element type - */ - interface Entry { - - /** - * Returns the element corresponding to this entry. - * - * @return the element corresponding to this entry - */ - E getElement(); - - /** - * Returns the number of occurrences for the element of this entry. - * - * @return the number of occurrences of the element - */ - int getCount(); - - /** - * Compares the specified object with this entry for equality. - * Returns true if the given object is also a multiset entry - * and the two entries represent the same element with the same - * number of occurrences. - *

- * More formally, two entries {@code e1} and {@code e2} represent - * the same mapping if - *

-         *     (e1.getElement()==null ? e2.getElement()==null
-         *                            : e1.getElement().equals(e2.getElement())) &&
-         *     (e1.getCount()==e2.getCount())
-         * 
- * - * @param o object to be compared for equality with this multiset entry - * @return true if the specified object is equal to this multiset entry - */ - @Override - boolean equals(Object o); - - /** - * Returns the hash code value for this multiset entry. - *

- * The hash code of a multiset entry {@code e} is defined to be: - *

-         *      (e==null ? 0 : e.hashCode()) ^ noOccurrences)
-         * 
- * - * @return the hash code value for this multiset entry - */ - @Override - int hashCode(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/MultiSetUtils.java b/src/main/java/repack/apache/commons/collections4/MultiSetUtils.java deleted file mode 100644 index 0dd5c306cf..0000000000 --- a/src/main/java/repack/apache/commons/collections4/MultiSetUtils.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import repack.apache.commons.collections4.multiset.HashMultiSet; -import repack.apache.commons.collections4.multiset.PredicatedMultiSet; -import repack.apache.commons.collections4.multiset.SynchronizedMultiSet; -import repack.apache.commons.collections4.multiset.UnmodifiableMultiSet; - -/** - * Provides utility methods and decorators for {@link MultiSet} instances. - * - * @since 4.1 - */ -public class MultiSetUtils { - - /** - * An empty unmodifiable multiset. - */ - @SuppressWarnings("rawtypes") // OK, empty multiset is compatible with any type - public static final MultiSet EMPTY_MULTISET = - UnmodifiableMultiSet.unmodifiableMultiSet(new HashMultiSet<>()); - - /** - * Don't allow instances. - */ - private MultiSetUtils() {} - - /** - * Returns a synchronized (thread-safe) multiset backed by the given multiset. - * In order to guarantee serial access, it is critical that all access to the - * backing multiset is accomplished through the returned multiset. - *

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

-     * MultiSet multiset = MultiSetUtils.synchronizedMultiSet(new HashMultiSet());
-     * ...
-     * synchronized(multiset) {
-     *     Iterator i = multiset.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 multiset the multiset to synchronize, must not be null - * @return a synchronized multiset backed by that multiset - * @throws NullPointerException if the MultiSet is null - */ - public static MultiSet synchronizedMultiSet(final MultiSet multiset) { - return SynchronizedMultiSet.synchronizedMultiSet(multiset); - } - - /** - * Returns an unmodifiable view of the given multiset. Any modification attempts - * to the returned multiset will raise an {@link UnsupportedOperationException}. - * - * @param the element type - * @param multiset the multiset whose unmodifiable view is to be returned, must not be null - * @return an unmodifiable view of that multiset - * @throws NullPointerException if the MultiSet is null - */ - public static MultiSet unmodifiableMultiSet(final MultiSet multiset) { - return UnmodifiableMultiSet.unmodifiableMultiSet(multiset); - } - - /** - * Returns a predicated (validating) multiset backed by the given multiset. - *

- * Only objects that pass the test in the given predicate can be added to - * the multiset. Trying to add an invalid object results in an - * IllegalArgumentException. It is important not to use the original multiset - * after invoking this method, as it is a backdoor for adding invalid - * objects. - * - * @param the element type - * @param multiset the multiset to predicate, must not be null - * @param predicate the predicate for the multiset, must not be null - * @return a predicated multiset backed by the given multiset - * @throws NullPointerException if the MultiSet or Predicate is null - */ - public static MultiSet predicatedMultiSet(final MultiSet multiset, - final Predicate predicate) { - return PredicatedMultiSet.predicatedMultiSet(multiset, predicate); - } - - /** - * Get an empty {@code MultiSet}. - * - * @param the element type - * @return an empty MultiSet - */ - @SuppressWarnings("unchecked") // OK, empty multiset is compatible with any type - public static MultiSet emptyMultiSet() { - return EMPTY_MULTISET; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/MultiValuedMap.java b/src/main/java/repack/apache/commons/collections4/MultiValuedMap.java deleted file mode 100644 index d19cd088dd..0000000000 --- a/src/main/java/repack/apache/commons/collections4/MultiValuedMap.java +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -/** - * Defines a map that holds a collection of values against each key. - *

- * A {@code MultiValuedMap} is a Map with slightly different semantics: - *

- *
    - *
  • Putting a value into the map will add the value to a {@link Collection} at that key.
  • - *
  • Getting a value will return a {@link Collection}, holding all the values put to that key.
  • - *
- *

- * For example: - *

- *
{@code
- * MultiValuedMap map = new ArrayListValuedHashMap<>();
- * map.put(1, "A");
- * map.put(1, "B");
- * map.put(1, "C");
- * Collection coll = map.get(1);
- * }
- *

- * {@code coll} will be a collection containing "A", "B", "C". - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.1 - */ -public interface MultiValuedMap { - // Query operations - - /** - * Gets the total size of the map. - *

- * Implementations would return the total size of the map which is the count - * of the values from all keys. - * - * @return the total size of the map - */ - int size(); - - /** - * Returns {@code true} if this map contains no key-value mappings. - * - * @return {@code true} if this map contains no key-value mappings - */ - boolean isEmpty(); - - /** - * Returns {@code true} if this map contains a mapping for the specified - * key. More formally, returns {@code true} if and only if this map contains - * a mapping for a key {@code k} such that {@code (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 NullPointerException if the specified key is null and this map - * does not permit null keys (optional) - */ - boolean containsKey(Object key); - - /** - * Checks whether the map contains at least one mapping for the specified value. - * - * @param value the value to search for - * @return true if the map contains the value - * @throws NullPointerException if the value is null and null values are not supported - * by the used collection types (optional) - */ - boolean containsValue(Object value); - - /** - * Checks whether the map contains a mapping for the specified key and value. - * - * @param key the key to search for - * @param value the value to search for - * @return true if the map contains the value - */ - boolean containsMapping(Object key, Object value); - - /** - * Returns a view collection of the values associated with the specified key. - *

- * This method will return an empty collection if {@link #containsKey(Object)} - * returns {@code false}. Changes to the returned collection will update the underlying - * {@code MultiValuedMap} and vice-versa. - * - * @param key the key to retrieve - * @return the {@code Collection} of values, implementations should - * return an empty collection for no mapping - * @throws NullPointerException if the key is null and null keys are invalid (optional) - */ - Collection get(K key); - - // Modification operations - - /** - * Adds a key-value mapping to this multivalued map. - *

- * Unlike a normal {@code Map} the previous value is not replaced. - * Instead the new value is added to the collection stored against the key. - * Depending on the collection type used, duplicate key-value mappings may - * be allowed. - *

- * The method will return {@code true} if the size of the multivalued map - * has been increased because of this operation. - * - * @param key the key to store against - * @param value the value to add to the collection at the key - * @return true if the map changed as a result of this put operation, or false - * if the map already contained the key-value mapping and the collection - * type does not allow duplicate values, e.g. when using a Set - * @throws UnsupportedOperationException if the put operation is not supported by - * this multivalued map, e.g. if it is unmodifiable - * @throws NullPointerException if the key or value is null and null is invalid (optional) - * @throws IllegalArgumentException if some aspect of the specified key or value prevents - * it from being stored in this multivalued map - */ - boolean put(K key, V value); - - /** - * Adds a mapping to the specified key for all values contained in the given Iterable. - * - * @param key the key to store against - * @param values the values to add to the collection at the key, may not be null - * @return true if the map changed as a result of this operation - * @throws NullPointerException if the specified iterable is null, or if this map - * does not permit null keys or values, and the specified key or values contain - * null (optional) - */ - boolean putAll(K key, Iterable values); - - /** - * Copies all mappings from the specified map to this multivalued 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 {@code k} to value {@code v} in the specified map. - *

- * The behavior of this operation is undefined if the specified map is modified - * while the operation is in progress. - * - * @param map mappings to be stored in this map, may not be null - * @return true if the map changed as a result of this operation - * @throws UnsupportedOperationException if the {@code putAll} operation is - * not supported by this map - * @throws NullPointerException if the specified map is null, or if this map - * does not permit null keys or values, and the specified map - * contains null keys or values (optional) - * @throws IllegalArgumentException if some property of a key or value in - * the specified map prevents it from being stored in this map - */ - boolean putAll(Map map); - - /** - * Copies all mappings from the specified map to this multivalued 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 {@code k} to value {@code v} in the specified map. - *

- * The behavior of this operation is undefined if the specified map is modified - * while the operation is in progress. - * - * @param map mappings to be stored in this map, may not be null - * @return true if the map changed as a result of this operation - * @throws UnsupportedOperationException if the {@code putAll} operation is - * not supported by this map - * @throws NullPointerException if the specified map is null, or if this map - * does not permit null keys or values, and the specified map - * contains null keys or values (optional) - * @throws IllegalArgumentException if some property of a key or value in - * the specified map prevents it from being stored in this map - */ - boolean putAll(MultiValuedMap map); - - /** - * Removes all values associated with the specified key. - *

- * The returned collection may be modifiable, but updates will not be propagated - * to this multivalued map. In case no mapping was stored for the specified - * key, an empty, unmodifiable collection will be returned. - * - * @param key the key to remove values from - * @return the values that were removed - * @throws UnsupportedOperationException if the map is unmodifiable - * @throws NullPointerException if the key is null and null keys are invalid (optional) - */ - Collection remove(Object key); - - /** - * Removes a key-value mapping from the 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 - * an empty collection from a subsequent {@code get(Object)}. - * - * @param key the key to remove from - * @param item the item to remove - * @return true if the mapping was removed, false otherwise - * @throws UnsupportedOperationException if the map is unmodifiable - * @throws NullPointerException if the key or value is null and null is invalid (optional) - */ - boolean removeMapping(Object key, Object item); - - /** - * Removes all of the mappings from this map (optional operation). - *

- * The map will be empty after this call returns. - * - * @throws UnsupportedOperationException if the map is unmodifiable - */ - void clear(); - - // Views - - /** - * Returns a {@link Collection} view of the mappings contained in this multivalued map. - *

- * The collection is backed by the map, so changes to the map are reflected - * in the collection, and vice-versa. - * - * @return a set view of the mappings contained in this map - */ - Collection> entries(); - - /** - * Returns a {@link MultiSet} view of the keys contained in this multivalued map. - *

- * The {@link MultiSet#getCount(Object)} method of the returned multiset will give - * the same result a calling {@code get(Object).size()} for the same key. - *

- * This multiset is backed by the map, so any changes in the map are reflected in - * the multiset. - * - * @return a multiset view of the keys contained in this map - */ - MultiSet keys(); - - /** - * Returns a {@link Set} view of the keys contained in this multivalued 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 {@code remove} operation), - * the result of the iteration is undefined. The set supports element - * removal, which removes the corresponding mapping from the map, via the - * {@code Iterator.remove}, {@code Set.remove}, {@code removeAll}, - * {@code retainAll}, and {@code clear} operations. It does not support - * the {@code add} or {@code addAll} operations. - * - * @return a set view of the keys contained in this map - */ - Set keySet(); - - /** - * Gets a {@link Collection} view of all values contained in this multivalued map. - *

- * Implementations typically return a collection containing the combination - * of values from all keys. - * - * @return a collection view of the values contained in this multivalued map - */ - Collection values(); - - /** - * Returns a view of this multivalued map as a {@code Map} from each distinct - * key to the non-empty collection of that key's associated values. - *

- * Note that {@code this.asMap().get(k)} is equivalent to {@code this.get(k)} - * only when {@code k} is a key contained in the multivalued map; otherwise it - * returns {@code null} as opposed to an empty collection. - *

- * Changes to the returned map or the collections that serve as its values - * will update the underlying multivalued map, and vice versa. The map does - * not support {@code put} or {@code putAll}, nor do its entries support - * {@link java.util.Map.Entry#setValue(Object) setValue}. - * - * @return a map view of the mappings in this multivalued map - */ - Map> asMap(); - - // Iterators - - /** - * Obtains a {@code MapIterator} over this multivalued map. - *

- * A map iterator is an efficient way of iterating over maps. There is no - * need to access the entries collection or use {@code Map.Entry} objects. - * - * @return a map iterator - */ - MapIterator mapIterator(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/OrderedBidiMap.java b/src/main/java/repack/apache/commons/collections4/OrderedBidiMap.java deleted file mode 100644 index 6ab47b34cd..0000000000 --- a/src/main/java/repack/apache/commons/collections4/OrderedBidiMap.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -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 {@code AbstractMap.values()} etc. Calling this - * method on the inverse map should return the original. - *

- * Implementations must return an {@code OrderedBidiMap} instance, - * usually by forwarding to {@code inverseOrderedBidiMap()}. - * - * @return an inverted bidirectional map - */ - @Override - OrderedBidiMap inverseBidiMap(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/OrderedIterator.java b/src/main/java/repack/apache/commons/collections4/OrderedIterator.java deleted file mode 100644 index f2866918b7..0000000000 --- a/src/main/java/repack/apache/commons/collections4/OrderedIterator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 of elements returned by this iterator. - * @since 3.0 - */ -public interface OrderedIterator extends Iterator { - - /** - * Checks to see if there is a previous element that can be iterated to. - * - * @return {@code 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(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/OrderedMap.java b/src/main/java/repack/apache/commons/collections4/OrderedMap.java deleted file mode 100644 index 66334dd7b1..0000000000 --- a/src/main/java/repack/apache/commons/collections4/OrderedMap.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -public interface OrderedMap extends IterableMap { - - /** - * Obtains an {@code OrderedMapIterator} over the map. - *

- * An ordered map iterator is an efficient way of iterating over maps - * in both directions. - * - * @return a map iterator - */ - @Override - 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); - -} diff --git a/src/main/java/repack/apache/commons/collections4/OrderedMapIterator.java b/src/main/java/repack/apache/commons/collections4/OrderedMapIterator.java deleted file mode 100644 index 6442c5d410..0000000000 --- a/src/main/java/repack/apache/commons/collections4/OrderedMapIterator.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -/** - * Defines an iterator that operates over an ordered {@code 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 - */ -public interface OrderedMapIterator extends MapIterator, OrderedIterator { - - /** - * Checks to see if there is a previous entry that can be iterated to. - * - * @return {@code true} if the iterator has a previous element - */ - @Override - boolean hasPrevious(); - - /** - * Gets the previous key from the {@code Map}. - * - * @return the previous key in the iteration - * @throws java.util.NoSuchElementException if the iteration is finished - */ - @Override - K previous(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/Predicate.java b/src/main/java/repack/apache/commons/collections4/Predicate.java deleted file mode 100644 index 2a39cea65b..0000000000 --- a/src/main/java/repack/apache/commons/collections4/Predicate.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -/** - * Defines a functor interface implemented by classes that perform a predicate - * test on an object. - *

- * A {@code Predicate} is the object equivalent of an {@code 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 invocation and null testing. - *

- * - * @param the type that the predicate queries - * - * @since 1.0 - */ -@FunctionalInterface -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); - -} diff --git a/src/main/java/repack/apache/commons/collections4/PredicateUtils.java b/src/main/java/repack/apache/commons/collections4/PredicateUtils.java deleted file mode 100644 index 3c8e6ebaf2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/PredicateUtils.java +++ /dev/null @@ -1,526 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Collection; - -import repack.apache.commons.collections4.functors.AllPredicate; -import repack.apache.commons.collections4.functors.AndPredicate; -import repack.apache.commons.collections4.functors.AnyPredicate; -import repack.apache.commons.collections4.functors.EqualPredicate; -import repack.apache.commons.collections4.functors.ExceptionPredicate; -import repack.apache.commons.collections4.functors.FalsePredicate; -import repack.apache.commons.collections4.functors.IdentityPredicate; -import repack.apache.commons.collections4.functors.InstanceofPredicate; -import repack.apache.commons.collections4.functors.InvokerTransformer; -import repack.apache.commons.collections4.functors.NonePredicate; -import repack.apache.commons.collections4.functors.NotNullPredicate; -import repack.apache.commons.collections4.functors.NotPredicate; -import repack.apache.commons.collections4.functors.NullIsExceptionPredicate; -import repack.apache.commons.collections4.functors.NullIsFalsePredicate; -import repack.apache.commons.collections4.functors.NullIsTruePredicate; -import repack.apache.commons.collections4.functors.NullPredicate; -import repack.apache.commons.collections4.functors.OnePredicate; -import repack.apache.commons.collections4.functors.OrPredicate; -import repack.apache.commons.collections4.functors.TransformedPredicate; -import repack.apache.commons.collections4.functors.TransformerPredicate; -import repack.apache.commons.collections4.functors.TruePredicate; -import repack.apache.commons.collections4.functors.UniquePredicate; - -/** - * {@code 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 - */ -public class PredicateUtils { - - /** - * Don't allow instances. - */ - private PredicateUtils() {} - - /** - * 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 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 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 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 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 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 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 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 {@code null} input - * object will return {@code false}. - * - * @param type the type to check for, may not be null - * @return the predicate - * @throws NullPointerException if the class is null - * @see 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 {@code 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 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, {@code PredicateUtils.invokerPredicate("isEmpty");} - * will call the {@code 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 NullPointerException if the methodName is null. - * @see InvokerTransformer - * @see 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, {@code PredicateUtils.invokerPredicate("isEmpty");} - * will call the {@code 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 NullPointerException if the method name is null - * @throws IllegalArgumentException if the paramTypes and args don't match - * @see InvokerTransformer - * @see 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)); - } - - /** - * 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 {@code and} predicate - * @throws NullPointerException if either predicate is null - * @see 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 {@code all} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException if any predicate in the array is null - * @see 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 {@code all} predicate - * @throws NullPointerException if the predicates collection is null - * @throws NullPointerException if any predicate in the collection is null - * @see 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 {@code or} predicate - * @throws NullPointerException if either predicate is null - * @see 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 {@code any} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException if any predicate in the array is null - * @see 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 {@code any} predicate - * @throws NullPointerException if the predicates collection is null - * @throws NullPointerException if any predicate in the collection is null - * @see 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 {@code either} predicate - * @throws NullPointerException if either predicate is null - * @see 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 {@code one} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException if any predicate in the array is null - * @see 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 {@code one} predicate - * @throws NullPointerException if the predicates collection is null - * @throws NullPointerException if any predicate in the collection is null - * @see 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 {@code neither} predicate - * @throws NullPointerException if either predicate is null - * @see 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 {@code none} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException if any predicate in the array is null - * @see 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 {@code none} predicate - * @throws NullPointerException if the predicates collection is null - * @throws NullPointerException if any predicate in the collection is null - * @see 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 {@code not} predicate - * @throws NullPointerException if the predicate is null - * @see NotPredicate - */ - public static Predicate notPredicate(final Predicate predicate) { - return NotPredicate.notPredicate(predicate); - } - - /** - * 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 NullPointerException if the transformer is null - * @see TransformerPredicate - */ - public static Predicate asPredicate(final Transformer transformer) { - return TransformerPredicate.transformerPredicate(transformer); - } - - /** - * Gets a Predicate that throws an exception if the input object is null, - * otherwise it calls the specified Predicate. This allows null handling - * behavior 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 NullPointerException if the predicate is null. - * @see 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 behavior 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 NullPointerException if the predicate is null. - * @see 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 behavior 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 NullPointerException if the predicate is null. - * @see 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 NullPointerException if the transformer or the predicate is null - * @see TransformedPredicate - * @since 3.1 - */ - public static Predicate transformedPredicate( - final Transformer transformer, final Predicate predicate) { - return TransformedPredicate.transformedPredicate(transformer, predicate); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/Put.java b/src/main/java/repack/apache/commons/collections4/Put.java deleted file mode 100644 index 69d105d29b..0000000000 --- a/src/main/java/repack/apache/commons/collections4/Put.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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}. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * - * @since 4.0 - * @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. - * - * @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 associated with {@code key}, or - * {@code null} if there was no mapping for {@code key}. - * (A {@code null} return can also indicate that the map - * previously associated {@code null} with {@code key}, - * if the implementation supports {@code null} values.) - * @see Map#put(Object, Object) - */ - Object put(K key, V value); - - /** - * @param t mappings to be stored in this map - * @see Map#putAll(Map) - */ - void putAll(Map t); - -} diff --git a/src/main/java/repack/apache/commons/collections4/QueueUtils.java b/src/main/java/repack/apache/commons/collections4/QueueUtils.java deleted file mode 100644 index aea3b5b6b4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/QueueUtils.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.LinkedList; -import java.util.Queue; - -import repack.apache.commons.collections4.queue.PredicatedQueue; -import repack.apache.commons.collections4.queue.SynchronizedQueue; -import repack.apache.commons.collections4.queue.TransformedQueue; -import repack.apache.commons.collections4.queue.UnmodifiableQueue; - -/** - * Provides utility methods and decorators for {@link Queue} instances. - * - * @since 4.0 - */ -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<>()); - - /** - * Don't allow instances. - */ - private QueueUtils() {} - - - /** - * Returns a synchronized (thread-safe) queue backed by the given queue. - * In order to guarantee serial access, it is critical that all access to the - * backing queue is accomplished through the returned queue. - *

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

-     * Queue queue = QueueUtils.synchronizedQueue(new CircularFifoQueue());
-     * ...
-     * synchronized(queue) {
-     *     Iterator i = queue.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 queue the queue to synchronize, must not be null - * @return a synchronized queue backed by that queue - * @throws NullPointerException if the queue is null - * @since 4.2 - */ - public static Queue synchronizedQueue(final Queue queue) { - return SynchronizedQueue.synchronizedQueue(queue); - } - - /** - * 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 NullPointerException 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 NullPointerException 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 behavior, 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 NullPointerException 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 {@code 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 EMPTY_QUEUE; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/ResettableIterator.java b/src/main/java/repack/apache/commons/collections4/ResettableIterator.java deleted file mode 100644 index 33acaa6ab0..0000000000 --- a/src/main/java/repack/apache/commons/collections4/ResettableIterator.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 of elements returned by this iterator. - * @since 3.0 - */ -public interface ResettableIterator extends Iterator { - - /** - * Resets the iterator back to the position at which the iterator - * was created. - */ - void reset(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/ResettableListIterator.java b/src/main/java/repack/apache/commons/collections4/ResettableListIterator.java deleted file mode 100644 index 4ebf665439..0000000000 --- a/src/main/java/repack/apache/commons/collections4/ResettableListIterator.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 of elements returned by this iterator. - * @since 3.0 - */ -public interface ResettableListIterator extends ListIterator, ResettableIterator, OrderedIterator { - // empty -} diff --git a/src/main/java/repack/apache/commons/collections4/SetUtils.java b/src/main/java/repack/apache/commons/collections4/SetUtils.java deleted file mode 100644 index 7df316a0a6..0000000000 --- a/src/main/java/repack/apache/commons/collections4/SetUtils.java +++ /dev/null @@ -1,657 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.AbstractSet; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.NavigableSet; -import java.util.Objects; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import repack.apache.commons.collections4.set.ListOrderedSet; -import repack.apache.commons.collections4.set.PredicatedNavigableSet; -import repack.apache.commons.collections4.set.PredicatedSet; -import repack.apache.commons.collections4.set.PredicatedSortedSet; -import repack.apache.commons.collections4.set.TransformedNavigableSet; -import repack.apache.commons.collections4.set.TransformedSet; -import repack.apache.commons.collections4.set.TransformedSortedSet; -import repack.apache.commons.collections4.set.UnmodifiableNavigableSet; -import repack.apache.commons.collections4.set.UnmodifiableSet; -import repack.apache.commons.collections4.set.UnmodifiableSortedSet; - -/** - * Provides utility methods and decorators for - * {@link Set} and {@link SortedSet} instances. - * - * @since 2.1 - */ -public class SetUtils { - - /** - * An unmodifiable view of a set that may be backed by other sets. - *

- * If the decorated sets change, this view will change as well. The contents - * of this view can be transferred to another instance via the {@link #copyInto(Set)} - * and {@link #toSet()} methods. - * - * @param the element type - * @since 4.1 - */ - public abstract static class SetView extends AbstractSet { - - /** - * Copies the contents of this view into the provided set. - * - * @param the set type - * @param set the set for copying the contents - */ - public > void copyInto(final S set) { - CollectionUtils.addAll(set, this); - } - - /** - * Return an iterator for this view; the returned iterator is - * not required to be unmodifiable. - * @return a new iterator for this view - */ - protected abstract Iterator createIterator(); - - @Override - public Iterator iterator() { - return IteratorUtils.unmodifiableIterator(createIterator()); - } - - @Override - public int size() { - return IteratorUtils.size(iterator()); - } - - /** - * Returns a new set containing the contents of this view. - * - * @return a new set containing all elements of this view - */ - public Set toSet() { - final Set set = new HashSet<>(size()); - copyInto(set); - return set; - } - } - - /** - * 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<>()); - - /** - * Returns an unmodifiable view containing the difference of the given - * {@link Set}s, denoted by {@code a \ b} (or {@code a - b}). - *

- * The returned view contains all elements of {@code a} that are not a member - * of {@code b}. - * - * @param the generic type that is able to represent the types contained - * in both input sets. - * @param setA the set to subtract from, must not be null - * @param setB the set to subtract, must not be null - * @return a view of the relative complement of the two sets - * @since 4.1 - */ - public static SetView difference(final Set setA, final Set setB) { - Objects.requireNonNull(setA, "setA"); - Objects.requireNonNull(setB, "setB"); - - final Predicate notContainedInB = object -> !setB.contains(object); - - return new SetView() { - @Override - public boolean contains(final Object o) { - return setA.contains(o) && !setB.contains(o); - } - - @Override - public Iterator createIterator() { - return IteratorUtils.filteredIterator(setA.iterator(), notContainedInB); - } - }; - } - - /** - * Returns an unmodifiable view of the symmetric difference of the given - * {@link Set}s. - *

- * The returned view contains all elements of {@code a} and {@code b} that are - * not a member of the other set. - *

- * This is equivalent to {@code union(difference(a, b), difference(b, a))}. - * - * @param the generic type that is able to represent the types contained - * in both input sets. - * @param setA the first set, must not be null - * @param setB the second set, must not be null - * @return a view of the symmetric difference of the two sets - * @since 4.1 - */ - public static SetView disjunction(final Set setA, final Set setB) { - Objects.requireNonNull(setA, "setA"); - Objects.requireNonNull(setB, "setB"); - - final SetView aMinusB = difference(setA, setB); - final SetView bMinusA = difference(setB, setA); - - return new SetView() { - @Override - public boolean contains(final Object o) { - return setA.contains(o) ^ setB.contains(o); - } - - @Override - public Iterator createIterator() { - return IteratorUtils.chainedIterator(aMinusB.iterator(), bMinusA.iterator()); - } - - @Override - public boolean isEmpty() { - return aMinusB.isEmpty() && bMinusA.isEmpty(); - } - - @Override - public int size() { - return aMinusB.size() + bMinusA.size(); - } - }; - } - - /** - * Returns an immutable empty set if the argument is {@code null}, - * or the argument itself otherwise. - * - * @param the element type - * @param set the set, possibly {@code null} - * @return an empty set if the argument is {@code null} - */ - public static Set emptyIfNull(final Set set) { - return set == null ? Collections.emptySet() : set; - } - - - /** - * Get a typed empty unmodifiable Set. - * @param the element type - * @return an empty Set - */ - public static Set emptySet() { - return Collections.emptySet(); - } - - /** - * 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 EMPTY_SORTED_SET; - } - - /** - * Generates a hash code using the algorithm specified in - * {@link java.util.Set#hashCode()}. - *

- * This method is useful for implementing {@code 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; - } - - /** - * Creates a set from the given items. If the passed var-args argument is {@code - * null}, then the method returns {@code null}. - * @param the element type - * @param items the elements that make up the new set - * @return a set - * @since 4.3 - */ - public static HashSet hashSet(final E... items) { - if (items == null) { - return null; - } - return new HashSet<>(Arrays.asList(items)); - } - - /** - * Returns an unmodifiable view of the intersection of the given {@link Set}s. - *

- * The returned view contains all elements that are members of both input sets - * ({@code a} and {@code b}). - * - * @param the generic type that is able to represent the types contained - * in both input sets. - * @param setA the first set, must not be null - * @param setB the second set, must not be null - * @return a view of the intersection of the two sets - * @since 4.1 - */ - public static SetView intersection(final Set setA, final Set setB) { - Objects.requireNonNull(setA, "setA"); - Objects.requireNonNull(setB, "setB"); - - final Predicate containedInB = setB::contains; - - return new SetView() { - @Override - public boolean contains(final Object o) { - return setA.contains(o) && setB.contains(o); - } - - @Override - public Iterator createIterator() { - return IteratorUtils.filteredIterator(setA.iterator(), containedInB); - } - }; - } - - /** - * Tests two sets for equality as per the {@code equals()} contract - * in {@link java.util.Set#equals(java.lang.Object)}. - *

- * This method is useful for implementing {@code 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 {@code equals} method works - * properly across different implementations of the {@code Set} - * interface.

- * - *

- * This implementation first checks if the two sets are the same object: - * if so it returns {@code true}. Then, it checks if the two sets are - * identical in size; if not, it returns false. If so, it returns - * {@code 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); - } - - /** - * Returns a new hash set that matches elements based on {@code ==} not - * {@code equals()}. - *

- * This set will violate the detail of various Set contracts. - * As a general rule, don't compare this set to other sets. In particular, you can't - * use decorators like {@link ListOrderedSet} on it, which silently assume that these - * contracts are fulfilled. - *

- * Note that the returned set is not synchronized and is not thread-safe. - * If you wish to use this set from multiple threads concurrently, you must use - * appropriate synchronization. The simplest approach is to wrap this map - * using {@link java.util.Collections#synchronizedSet(Set)}. This class may throw - * exceptions when accessed by concurrent threads without synchronization. - * - * @param the element type - * @return a new identity hash set - * @since 4.1 - */ - public static Set newIdentityHashSet() { - return Collections.newSetFromMap(new IdentityHashMap<>()); - } - - /** - * 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 NullPointerException if the set is null - */ - public static Set orderedSet(final Set set) { - return ListOrderedSet.listOrderedSet(set); - } - - /** - * Returns a predicated (validating) navigable set backed by the given navigable 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 navigable set to predicate, must not be null - * @param predicate the predicate for the navigable set, must not be null - * @return a predicated navigable set backed by the given navigable set - * @throws NullPointerException if the set or predicate is null - * @since 4.1 - */ - public static SortedSet predicatedNavigableSet(final NavigableSet set, - final Predicate predicate) { - return PredicatedNavigableSet.predicatedNavigableSet(set, predicate); - } - - /** - * 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 NullPointerException if the set or predicate is null - */ - public static Set predicatedSet(final Set set, final Predicate predicate) { - return PredicatedSet.predicatedSet(set, predicate); - } - - /** - * 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 NullPointerException if the set or predicate is null - */ - public static SortedSet predicatedSortedSet(final SortedSet set, - final Predicate predicate) { - return PredicatedSortedSet.predicatedSortedSet(set, predicate); - } - - // Set - /** - * 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 NullPointerException if the set is null - */ - public static Set synchronizedSet(final Set set) { - return Collections.synchronizedSet(set); - } - - // SortedSet - /** - * 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.synchronizedSortedSet(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 NullPointerException if the set is null - */ - public static SortedSet synchronizedSortedSet(final SortedSet set) { - return Collections.synchronizedSortedSet(set); - } - - /** - * Returns a transformed navigable set backed by the given navigable 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 behavior, see {@link TransformedNavigableSet#transformedNavigableSet}. - * - * @param the element type - * @param set the navigable 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 NullPointerException if the set or transformer is null - * @since 4.1 - */ - public static SortedSet transformedNavigableSet(final NavigableSet set, - final Transformer transformer) { - return TransformedNavigableSet.transformingNavigableSet(set, transformer); - } - - /** - * 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 behavior, 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 NullPointerException if the set or transformer is null - */ - public static Set transformedSet(final Set set, - final Transformer transformer) { - return TransformedSet.transformingSet(set, transformer); - } - - /** - * 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 behavior, 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 NullPointerException if the set or transformer is null - */ - public static SortedSet transformedSortedSet(final SortedSet set, - final Transformer transformer) { - return TransformedSortedSet.transformingSortedSet(set, transformer); - } - - // Set operations - - /** - * Returns an unmodifiable view of the union of the given {@link Set}s. - *

- * The returned view contains all elements of {@code a} and {@code b}. - * - * @param the generic type that is able to represent the types contained - * in both input sets. - * @param setA the first set, must not be null - * @param setB the second set, must not be null - * @return a view of the union of the two set - * @throws NullPointerException if either input set is null - * @since 4.1 - */ - public static SetView union(final Set setA, final Set setB) { - Objects.requireNonNull(setA, "setA"); - Objects.requireNonNull(setB, "setB"); - - final SetView bMinusA = difference(setB, setA); - - return new SetView() { - @Override - public boolean contains(final Object o) { - return setA.contains(o) || setB.contains(o); - } - - @Override - public Iterator createIterator() { - return IteratorUtils.chainedIterator(setA.iterator(), bMinusA.iterator()); - } - - @Override - public boolean isEmpty() { - return setA.isEmpty() && setB.isEmpty(); - } - - @Override - public int size() { - return setA.size() + bMinusA.size(); - } - }; - } - - // NavigableSet - /** - * Returns an unmodifiable navigable set backed by the given navigable set. - *

- * This method uses the implementation in the decorators subpackage. - * - * @param the element type - * @param set the navigable set to make unmodifiable, must not be null - * @return an unmodifiable set backed by the given set - * @throws NullPointerException if the set is null - * @since 4.1 - */ - public static SortedSet unmodifiableNavigableSet(final NavigableSet set) { - return UnmodifiableNavigableSet.unmodifiableNavigableSet(set); - } - - /** - * Creates an unmodifiable set from the given items. If the passed var-args argument is {@code - * null}, then the method returns {@code null}. - * @param the element type - * @param items the elements that make up the new set - * @return a set - * @since 4.3 - */ - public static Set unmodifiableSet(final E... items) { - if (items == null) { - return null; - } - return UnmodifiableSet.unmodifiableSet(hashSet(items)); - } - - /** - * 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 NullPointerException if the set is null - */ - public static Set unmodifiableSet(final Set set) { - return UnmodifiableSet.unmodifiableSet(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 NullPointerException if the set is null - */ - public static SortedSet unmodifiableSortedSet(final SortedSet set) { - return UnmodifiableSortedSet.unmodifiableSortedSet(set); - } - - /** - * Don't allow instances. - */ - private SetUtils() {} -} diff --git a/src/main/java/repack/apache/commons/collections4/SetValuedMap.java b/src/main/java/repack/apache/commons/collections4/SetValuedMap.java deleted file mode 100644 index c9801acf86..0000000000 --- a/src/main/java/repack/apache/commons/collections4/SetValuedMap.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Set; - -/** - * Defines a map that holds a set of values against each key. - *

- * A {@code SetValuedMap} is a Map with slightly different semantics: - *

- *
    - *
  • Putting a value into the map will add the value to a {@link Set} at that key.
  • - *
  • Getting a value will return a {@link Set}, holding all the values put to that key.
  • - *
- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.1 - */ -public interface SetValuedMap extends MultiValuedMap { - - /** - * Gets the set of values associated with the specified key. - *

- * Implementations typically return an empty {@code Set} if no values - * have been mapped to the key. - *

- * - * @param key the key to retrieve - * @return the {@code Set} of values, implementations should return an - * empty {@code Set} for no mapping - * @throws NullPointerException if the key is null and null keys are invalid - */ - @Override - Set get(K key); - - /** - * Removes all values associated with the specified key. - *

- * The returned set may be modifiable, but updates will not be - * propagated to this set-valued map. In case no mapping was stored for the - * specified key, an empty, unmodifiable set will be returned. - * - * @param key the key to remove values from - * @return the {@code Set} 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 NullPointerException if the key is null and null keys are invalid - */ - @Override - Set remove(Object key); -} diff --git a/src/main/java/repack/apache/commons/collections4/SortedBag.java b/src/main/java/repack/apache/commons/collections4/SortedBag.java deleted file mode 100644 index c232f31573..0000000000 --- a/src/main/java/repack/apache/commons/collections4/SortedBag.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Comparator; - -/** - * Defines a type of {@code Bag} that maintains a sorted order among - * its unique representative members. - * - * @param the type of elements in this bag - * @since 2.0 - */ -public interface SortedBag extends Bag { - - /** - * Returns the comparator associated with this sorted set, or null - * if it uses its elements' natural ordering. - * - * @return the comparator in use, or null if natural ordering - */ - 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(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/SortedBidiMap.java b/src/main/java/repack/apache/commons/collections4/SortedBidiMap.java deleted file mode 100644 index 94e52ed619..0000000000 --- a/src/main/java/repack/apache/commons/collections4/SortedBidiMap.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -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 {@code AbstractMap.values()} etc. Calling this - * method on the inverse map should return the original. - *

- * Implementations must return a {@code SortedBidiMap} instance, - * usually by forwarding to {@code inverseSortedBidiMap()}. - * - * @return an inverted bidirectional map - */ - @Override - SortedBidiMap inverseBidiMap(); - - /** - * Get the comparator used for the values in the value-to-key map aspect. - * @return Comparator<? super V> - */ - Comparator valueComparator(); -} diff --git a/src/main/java/repack/apache/commons/collections4/SplitMapUtils.java b/src/main/java/repack/apache/commons/collections4/SplitMapUtils.java deleted file mode 100644 index eee2ec1740..0000000000 --- a/src/main/java/repack/apache/commons/collections4/SplitMapUtils.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Collection; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.collection.UnmodifiableCollection; -import repack.apache.commons.collections4.iterators.UnmodifiableMapIterator; -import repack.apache.commons.collections4.map.EntrySetToMapIteratorAdapter; -import repack.apache.commons.collections4.map.UnmodifiableEntrySet; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Utilities for working with "split maps:" objects that implement {@link Put} - * and/or {@link Get} but not {@link Map}. - * - * @since 4.0 - * - * @see Get - * @see Put - */ -public class SplitMapUtils { - - /** - * Don't allow instances. - */ - private SplitMapUtils() {} - - - private static class WrappedGet implements IterableMap, Unmodifiable { - private final Get get; - - private WrappedGet(final Get get) { - this.get = get; - } - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean containsKey(final Object key) { - return get.containsKey(key); - } - - @Override - public boolean containsValue(final Object value) { - return get.containsValue(value); - } - - @Override - 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); - } - - @Override - public V get(final Object key) { - return get.get(key); - } - - @Override - public int hashCode() { - return "WrappedGet".hashCode() << 4 | get.hashCode(); - } - - @Override - public boolean isEmpty() { - return get.isEmpty(); - } - - @Override - public Set keySet() { - return UnmodifiableSet.unmodifiableSet(get.keySet()); - } - - @Override - public V put(final K key, final V value) { - throw new UnsupportedOperationException(); - } - - @Override - public void putAll(final Map t) { - throw new UnsupportedOperationException(); - } - - @Override - public V remove(final Object key) { - return get.remove(key); - } - - @Override - public int size() { - return get.size(); - } - - @Override - public Collection values() { - return UnmodifiableCollection.unmodifiableCollection(get.values()); - } - - @Override - public MapIterator mapIterator() { - final 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; - } - - @Override - public void clear() { - put.clear(); - } - - @Override - public boolean containsKey(final Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean containsValue(final Object value) { - throw new UnsupportedOperationException(); - } - - @Override - 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); - } - - @Override - public V get(final Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public int hashCode() { - return "WrappedPut".hashCode() << 4 | put.hashCode(); - } - - @Override - public boolean isEmpty() { - throw new UnsupportedOperationException(); - } - - @Override - public Set keySet() { - throw new UnsupportedOperationException(); - } - - @Override - @SuppressWarnings("unchecked") - public V put(final K key, final V value) { - return (V) put.put(key, value); - } - - @Override - public void putAll(final Map t) { - put.putAll(t); - } - - @Override - public V remove(final Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public int size() { - throw new UnsupportedOperationException(); - } - - @Override - public Collection values() { - throw new UnsupportedOperationException(); - } - } - - - /** - * Get the specified {@link Get} as an instance of {@link IterableMap}. - * If {@code get} implements {@link IterableMap} directly, no conversion will take place. - * If {@code 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} - * @throws NullPointerException if the argument is null - */ - @SuppressWarnings("unchecked") - public static IterableMap readableMap(final Get get) { - Objects.requireNonNull(get, "get"); - 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 {@code 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 {@code V} at runtime. - * - * @param the key type - * @param the element type - * @param put to wrap, must not be null - * @return {@link Map} - * @throws NullPointerException if the argument is null - */ - @SuppressWarnings("unchecked") - public static Map writableMap(final Put put) { - Objects.requireNonNull(put, "put"); - if (put instanceof Map) { - return (Map) put; - } - return new WrappedPut<>(put); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/Transformer.java b/src/main/java/repack/apache/commons/collections4/Transformer.java deleted file mode 100644 index 33123793bc..0000000000 --- a/src/main/java/repack/apache/commons/collections4/Transformer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -/** - * Defines a functor interface implemented by classes that transform one - * object into another. - *

- * A {@code 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 - */ -@FunctionalInterface -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); - -} diff --git a/src/main/java/repack/apache/commons/collections4/TransformerUtils.java b/src/main/java/repack/apache/commons/collections4/TransformerUtils.java deleted file mode 100644 index 6452ca9e21..0000000000 --- a/src/main/java/repack/apache/commons/collections4/TransformerUtils.java +++ /dev/null @@ -1,485 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.Collection; -import java.util.Map; -import java.util.Objects; - -import repack.apache.commons.collections4.functors.ChainedTransformer; -import repack.apache.commons.collections4.functors.CloneTransformer; -import repack.apache.commons.collections4.functors.ClosureTransformer; -import repack.apache.commons.collections4.functors.ConstantTransformer; -import repack.apache.commons.collections4.functors.EqualPredicate; -import repack.apache.commons.collections4.functors.ExceptionTransformer; -import repack.apache.commons.collections4.functors.FactoryTransformer; -import repack.apache.commons.collections4.functors.IfTransformer; -import repack.apache.commons.collections4.functors.InstantiateTransformer; -import repack.apache.commons.collections4.functors.InvokerTransformer; -import repack.apache.commons.collections4.functors.MapTransformer; -import repack.apache.commons.collections4.functors.NOPTransformer; -import repack.apache.commons.collections4.functors.PredicateTransformer; -import repack.apache.commons.collections4.functors.StringValueTransformer; -import repack.apache.commons.collections4.functors.SwitchTransformer; - -/** - * {@code 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 - *
  • If - calls one transformer or another based on a predicate - *
  • 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 {@code java.lang.String} representation of the input object - *
- *

- * Since v4.1 only transformers which are considered to be safe are - * Serializable. Transformers considered to be unsafe for serialization are: - *

- *
    - *
  • Invoker - *
  • Clone - *
  • Instantiate - *
- * - * @since 3.0 - */ -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 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 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 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 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 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 NullPointerException if the closure is null - * @see 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 NullPointerException if the predicate is null - * @see 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 NullPointerException if the factory is null - * @see 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 NullPointerException if the transformers array or any of the transformers is null - * @see 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 NullPointerException if the transformers collection or any of the transformers is null - * @see ChainedTransformer - */ - public static Transformer chainedTransformer( - final Collection> transformers) { - return ChainedTransformer.chainedTransformer(transformers); - } - - /** - * Create a new Transformer that calls the transformer if the predicate is true, - * otherwise the input object is returned unchanged. - * - * @param the input / output type - * @param predicate the predicate to switch on - * @param trueTransformer the transformer called if the predicate is true - * @return the transformer - * @throws NullPointerException if either the predicate or transformer is null - * @see IfTransformer - * @since 4.1 - */ - public static Transformer ifTransformer(final Predicate predicate, - final Transformer trueTransformer) { - return IfTransformer.ifTransformer(predicate, trueTransformer); - } - - /** - * 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 NullPointerException if either the predicate or transformer is null - * @see IfTransformer - * @since 4.1 - */ - public static Transformer ifTransformer(final Predicate predicate, - final Transformer trueTransformer, - final Transformer falseTransformer) { - return IfTransformer.ifTransformer(predicate, trueTransformer, falseTransformer); - } - - /** - * 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 NullPointerException if either the predicate or transformer is null - * @see SwitchTransformer - * @deprecated as of 4.1, use {@link #ifTransformer(Predicate, Transformer, Transformer)} - */ - @SuppressWarnings("unchecked") - @Deprecated - 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 NullPointerException if either array is null - * @throws NullPointerException if any element in the arrays is null - * @throws IllegalArgumentException if the arrays have different sizes - * @see 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 NullPointerException if either array is null - * @throws NullPointerException if any element in the arrays is null - * @throws IllegalArgumentException if the arrays have different sizes - * @see 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 NullPointerException if the map is null - * @throws NullPointerException if any transformer in the map is null - * @throws ClassCastException if the map elements are of the wrong type - * @see 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 NullPointerException if the map is null - * @throws NullPointerException if any transformer in the map is null - * @see SwitchTransformer - */ - @SuppressWarnings("unchecked") - public static Transformer switchMapTransformer( - final Map> objectsAndTransformers) { - - Objects.requireNonNull(objectsAndTransformers, "objectsAndTransformers"); - 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 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 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 {@link ConstantTransformer#nullTransformer()} if the - * {@code map} is {@code null} - * @see 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 {@code null}, - * {@code null} is returned. - * - *

- * For example, {@code TransformerUtils.invokerTransformer("getName");} - * will call the {@code getName} 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 NullPointerException if the methodName is null. - * @see 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 NullPointerException if the method name is null - * @throws IllegalArgumentException if the paramTypes and args don't match - * @see 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 {@code java.lang.String} - * representation of the input object. This is achieved via the - * {@code toString} method, {@code null} returns 'null'. - * - * @param the input type - * @return the transformer - * @see StringValueTransformer - */ - public static Transformer stringValueTransformer() { - return StringValueTransformer.stringValueTransformer(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/Trie.java b/src/main/java/repack/apache/commons/collections4/Trie.java deleted file mode 100644 index cc1a5a7bd4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/Trie.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import java.util.SortedMap; - -/** - * Defines the interface for a prefix tree, an ordered tree data structure. For - * more information, see Tries. - * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.0 - */ -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); - -} diff --git a/src/main/java/repack/apache/commons/collections4/TrieUtils.java b/src/main/java/repack/apache/commons/collections4/TrieUtils.java deleted file mode 100644 index 55ebf44c5a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/TrieUtils.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4; - -import repack.apache.commons.collections4.trie.UnmodifiableTrie; - -/** - * A collection of {@link Trie} utilities. - * - * @since 4.0 - */ -public class TrieUtils { - - /** - * Don't allow instances. - */ - 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 - * @throws NullPointerException if trie is null - * - * @see java.util.Collections#unmodifiableMap(java.util.Map) - */ - public static Trie unmodifiableTrie(final Trie trie) { - return UnmodifiableTrie.unmodifiableTrie(trie); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/Unmodifiable.java b/src/main/java/repack/apache/commons/collections4/Unmodifiable.java deleted file mode 100644 index e33f6bf70b..0000000000 --- a/src/main/java/repack/apache/commons/collections4/Unmodifiable.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -public interface Unmodifiable { - // marker interface - no methods to implement -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/AbstractBagDecorator.java b/src/main/java/repack/apache/commons/collections4/bag/AbstractBagDecorator.java deleted file mode 100644 index 2e018a540d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/AbstractBagDecorator.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bag; - -import java.util.Set; - -import repack.apache.commons.collections4.Bag; -import repack.apache.commons.collections4.collection.AbstractCollectionDecorator; - -/** - * Decorates another {@code Bag} to provide additional behavior. - *

- * Methods are forwarded directly to the decorated bag. - *

- * - * @param the type of elements in this bag - * @since 3.0 - */ -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() { - } - - /** - * Constructor that wraps (not copies). - * - * @param bag the bag to decorate, must not be null - * @throws NullPointerException if bag 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(); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - - - @Override - public int getCount(final Object object) { - return decorated().getCount(object); - } - - @Override - public boolean add(final E object, final int count) { - return decorated().add(object, count); - } - - @Override - public boolean remove(final Object object, final int count) { - return decorated().remove(object, count); - } - - @Override - public Set uniqueSet() { - return decorated().uniqueSet(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/AbstractMapBag.java b/src/main/java/repack/apache/commons/collections4/bag/AbstractMapBag.java deleted file mode 100644 index 935ad8c94c..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/AbstractMapBag.java +++ /dev/null @@ -1,604 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.Bag; -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Abstract implementation of the {@link Bag} interface to simplify the creation - * of subclass implementations. - *

- * Subclasses specify a Map implementation to use as the internal storage. The - * map will be used to map bag elements to a number; the number represents the - * number of occurrences of that element in the bag. - *

- * - * @param the type of elements in this bag - * @since 3.0 (previously DefaultMapBag v2.0) - */ -public abstract class AbstractMapBag implements Bag { - - /** The map to use to store the data */ - private transient Map map; - /** The current total size of the bag */ - private int size; - /** The modification count for fail fast iterators */ - private transient int modCount; - /** Unique view of the elements */ - private transient Set uniqueSet; - - /** - * Constructor needed for subclass serialisation. - */ - protected AbstractMapBag() { - } - - /** - * 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) { - 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 - */ - @Override - public int size() { - return size; - } - - /** - * Returns true if the underlying map is empty. - * - * @return true if bag is empty - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 {@code true} if the Bag contains all the collection - */ - @Override - public boolean containsAll(final Collection coll) { - if (coll instanceof Bag) { - return containsAll((Bag) coll); - } - return containsAll(new HashBag<>(coll)); - } - - /** - * Returns {@code true} if the bag contains all elements in the given - * collection, respecting cardinality. - * - * @param other the bag to check against - * @return {@code true} if the Bag contains all the collection - */ - boolean containsAll(final Bag other) { - for (final Object current : other.uniqueSet()) { - 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 - */ - @Override - 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 - */ - BagIterator(final AbstractMapBag parent) { - this.parent = parent; - this.entryIterator = parent.map.entrySet().iterator(); - this.current = null; - this.mods = parent.modCount; - this.canRemove = false; - } - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return itemCount > 0 || entryIterator.hasNext(); - } - - /** {@inheritDoc} */ - @Override - 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} */ - @Override - public void remove() { - if (parent.modCount != mods) { - throw new ConcurrentModificationException(); - } - if (!canRemove) { - 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 {@code true} if the object was not already in the {@code uniqueSet} - */ - @Override - 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 {@code true} if the object was not already in the {@code uniqueSet} - */ - @Override - 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; - } - - /** - * Invokes {@link #add(Object)} for each element in the given collection. - * - * @param coll the collection to add - * @return {@code true} if this call changed the bag - */ - @Override - public boolean addAll(final Collection coll) { - boolean changed = false; - for (final E current : coll) { - final boolean added = add(current); - changed = changed || added; - } - return changed; - } - - /** - * Clears the bag by clearing the underlying map. - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - public boolean removeAll(final Collection coll) { - boolean result = false; - if (coll != null) { - for (final Object current : coll) { - final boolean changed = remove(current, 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 - */ - @Override - 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 {@code true} if this call changed the collection - */ - boolean retainAll(final Bag other) { - boolean result = false; - final Bag excess = new HashBag<>(); - for (final E current : uniqueSet()) { - 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)) { - 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 - */ - @Override - public Object[] toArray() { - final Object[] result = new Object[size()]; - int i = 0; - for (final E current : map.keySet()) { - 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 - */ - @Override - 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; - for (final E current : map.keySet()) { - 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 - */ - @Override - 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)) { - 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 - * {@code (e==null ? 0 : e.hashCode()) ^ noOccurrences)}. 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 (isEmpty()) { - return "[]"; - } - final StringBuilder buf = new StringBuilder(); - buf.append(CollectionUtils.DEFAULT_TOSTRING_PREFIX); - final Iterator it = uniqueSet().iterator(); - while (it.hasNext()) { - final Object current = it.next(); - final int count = getCount(current); - buf.append(count); - buf.append(CollectionUtils.COLON); - buf.append(current); - if (it.hasNext()) { - buf.append(CollectionUtils.COMMA); - } - } - buf.append(CollectionUtils.DEFAULT_TOSTRING_SUFFIX); - return buf.toString(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/AbstractSortedBagDecorator.java b/src/main/java/repack/apache/commons/collections4/bag/AbstractSortedBagDecorator.java deleted file mode 100644 index 55aecf1ee9..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/AbstractSortedBagDecorator.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bag; - -import java.util.Comparator; - -import repack.apache.commons.collections4.SortedBag; - -/** - * Decorates another {@code SortedBag} to provide additional behavior. - *

- * Methods are forwarded directly to the decorated bag. - *

- * - * @param the type of elements in this bag - * @since 3.0 - */ -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() { - } - - /** - * Constructor that wraps (not copies). - * - * @param bag the bag to decorate, must not be null - * @throws NullPointerException if bag 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(); - } - - - @Override - public E first() { - return decorated().first(); - } - - @Override - public E last() { - return decorated().last(); - } - - @Override - public Comparator comparator() { - return decorated().comparator(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/CollectionBag.java b/src/main/java/repack/apache/commons/collections4/bag/CollectionBag.java deleted file mode 100644 index 3c597d2ae4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/CollectionBag.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.Bag; - -/** - * Decorates another {@link Bag} to comply with the Collection contract. - *

- * By decorating an existing {@link Bag} instance with a {@link CollectionBag}, - * it can be safely passed on to methods that require Collection types that - * are fully compliant with the Collection contract. - *

- *

- * The method javadoc highlights the differences compared to the original Bag interface. - *

- * - * @see Bag - * @param the type of elements in this bag - * @since 4.0 - */ -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 NullPointerException 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 NullPointerException 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 if an error occurs while writing to the 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 error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @throws ClassCastException if deserialized 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 - - /** - * (Change) - * Returns {@code true} if the bag contains all elements in - * the given collection, not respecting cardinality. That is, - * if the given collection {@code coll} contains at least one of - * every object contained in this object. - * - * @param coll the collection to check against - * @return {@code true} if the Bag contains at least one of every object in the collection - */ - @Override - public boolean containsAll(final Collection coll) { - return coll.stream().allMatch(this::contains); - } - - /** - * (Change) - * Adds one copy of the specified object to the Bag. - *

- * Since this method always increases the size of the bag, it - * will always return {@code true}. - * - * @param object the object to add - * @return {@code true}, always - */ - @Override - public boolean add(final E object) { - return add(object, 1); - } - - @Override - public boolean addAll(final Collection coll) { - boolean changed = false; - for (final E current : coll) { - final boolean added = add(current, 1); - changed = changed || added; - } - return changed; - } - - /** - * (Change) - * Removes the first occurrence of the given object from the bag. - *

- * This will also remove the object from the {@link #uniqueSet()} if the - * bag contains no occurrence anymore of the object after this operation. - * - * @param object the object to remove - * @return {@code true} if this call changed the collection - */ - @Override - public boolean remove(final Object object) { - return remove(object, 1); - } - - /** - * (Change) - * Remove all elements represented in the given collection, - * not respecting cardinality. That is, remove all - * occurrences of every object contained in the given collection. - * - * @param coll the collection to remove - * @return {@code true} if this call changed the collection - */ - @Override - public boolean removeAll(final Collection coll) { - if (coll != null) { - boolean result = false; - for (final Object obj : coll) { - final boolean changed = remove(obj, getCount(obj)); - result = result || changed; - } - return result; - } - // let the decorated bag handle the case of null argument - return decorated().removeAll(null); - } - - /** - * (Change) - * Remove any members of the bag that are not in the given collection, - * not respecting cardinality. That is, any object in the given - * collection {@code coll} will be retained in the bag with the same - * number of copies prior to this operation. All other objects will be - * completely removed from this bag. - *

- * This implementation iterates over the elements of this bag, checking - * each element in turn to see if it's contained in {@code coll}. - * If it's not contained, it's removed from this bag. As a consequence, - * it is advised to use a collection type for {@code coll} that provides - * a fast (e.g. O(1)) implementation of {@link Collection#contains(Object)}. - * - * @param coll the collection to retain - * @return {@code true} if this call changed the collection - */ - @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; - } - // let the decorated bag handle the case of null argument - return decorated().retainAll(null); - } - - // Bag interface - - /** - * (Change) - * Adds {@code count} copies of the specified object to the Bag. - *

- * Since this method always increases the size of the bag, it - * will always return {@code true}. - * - * @param object the object to add - * @param count the number of copies to add - * @return {@code true}, always - */ - @Override - public boolean add(final E object, final int count) { - decorated().add(object, count); - return true; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/CollectionSortedBag.java b/src/main/java/repack/apache/commons/collections4/bag/CollectionSortedBag.java deleted file mode 100644 index c07feab603..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/CollectionSortedBag.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.SortedBag; - -/** - * Decorates another {@link SortedBag} to comply with the Collection contract. - * - * @param the type of elements in this bag - * @since 4.0 - */ -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 NullPointerException 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 NullPointerException 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 if an error occurs while writing to the 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 error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @throws ClassCastException if deserialized 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) { - return coll.stream().allMatch(this::contains); - } - - @Override - public boolean add(final E object) { - return add(object, 1); - } - - @Override - public boolean addAll(final Collection coll) { - boolean changed = false; - for (final E current : coll) { - final boolean added = add(current, 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; - for (final Object obj : coll) { - final boolean changed = remove(obj, getCount(obj)); - result = result || changed; - } - return result; - } - // 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; - } - // 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/HashBag.java b/src/main/java/repack/apache/commons/collections4/bag/HashBag.java deleted file mode 100644 index 78340f154b..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/HashBag.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 {@code Bag}, using a {@link HashMap} to provide the - * data storage. This is the standard implementation of a bag. - *

- * A {@code 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. - *

- * - * @param the type of elements in this bag - * @since 3.0 (previously in main package v2.0) - */ -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. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - super.doWriteObject(out); - } - - /** - * Read the bag in using a custom routine. - * - * @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 - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - super.doReadObject(new HashMap<>(), in); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/PredicatedBag.java b/src/main/java/repack/apache/commons/collections4/bag/PredicatedBag.java deleted file mode 100644 index c28bf0d3a1..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/PredicatedBag.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bag; - -import java.util.Set; - -import repack.apache.commons.collections4.Bag; -import repack.apache.commons.collections4.Predicate; -import repack.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.predicatedBag(new HashBag(), NotNullPredicate.INSTANCE);
- * 
- *

- * This class is Serializable from Commons Collections 3.1. - *

- * - * @param the type of elements in this bag - * @since 3.0 - */ -public class PredicatedBag extends PredicatedCollection implements Bag { - - /** Serialization version */ - private static final long serialVersionUID = -2575833140344736876L; - - /** - * Factory method to create a predicated (validating) bag. - *

- * If there are any elements already in the bag being decorated, they - * are validated. - * - * @param 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 NullPointerException 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 NullPointerException 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(); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - - - @Override - public boolean add(final E object, final int count) { - validate(object); - return decorated().add(object, count); - } - - @Override - public boolean remove(final Object object, final int count) { - return decorated().remove(object, count); - } - - @Override - public Set uniqueSet() { - return decorated().uniqueSet(); - } - - @Override - public int getCount(final Object object) { - return decorated().getCount(object); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/PredicatedSortedBag.java b/src/main/java/repack/apache/commons/collections4/bag/PredicatedSortedBag.java deleted file mode 100644 index 59168021a0..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/PredicatedSortedBag.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bag; - -import java.util.Comparator; - -import repack.apache.commons.collections4.Predicate; -import repack.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.predicatedSortedBag(new TreeBag(), NotNullPredicate.INSTANCE);
- * 
- *

- * This class is Serializable from Commons Collections 3.1. - *

- * - * @param the type of elements in this bag - * @since 3.0 - */ -public class PredicatedSortedBag extends PredicatedBag implements SortedBag { - - /** Serialization version */ - private static final long serialVersionUID = 3448581314086406616L; - - /** - * Factory method to create a predicated (validating) bag. - *

- * If there are any elements already in the bag being decorated, they - * are validated. - * - * @param 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 NullPointerException 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 NullPointerException 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(); - } - - - @Override - public E first() { - return decorated().first(); - } - - @Override - public E last() { - return decorated().last(); - } - - @Override - public Comparator comparator() { - return decorated().comparator(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/SynchronizedBag.java b/src/main/java/repack/apache/commons/collections4/bag/SynchronizedBag.java deleted file mode 100644 index af3b877632..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/SynchronizedBag.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bag; - -import java.util.Set; - -import repack.apache.commons.collections4.Bag; -import repack.apache.commons.collections4.collection.SynchronizedCollection; - -/** - * Decorates another {@link Bag} to synchronize its behavior - * for a multithreaded 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. - *

- * - * @param the type of elements in this bag - * @since 3.0 - */ -public class SynchronizedBag extends SynchronizedCollection implements Bag { - - /** Serialization version */ - private static final long serialVersionUID = 8084674570753837109L; - - /** - * Factory method to create a synchronized bag. - * - * @param the type of the elements in the bag - * @param bag the bag to decorate, must not be null - * @return a new synchronized Bag - * @throws NullPointerException 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 NullPointerException 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 NullPointerException if bag or lock 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(); - } - - @Override - public boolean equals(final Object object) { - if (object == this) { - return true; - } - synchronized (lock) { - return getBag().equals(object); - } - } - - @Override - public int hashCode() { - synchronized (lock) { - return getBag().hashCode(); - } - } - - - @Override - public boolean add(final E object, final int count) { - synchronized (lock) { - return getBag().add(object, count); - } - } - - @Override - public boolean remove(final Object object, final int count) { - synchronized (lock) { - return getBag().remove(object, count); - } - } - - @Override - public Set uniqueSet() { - synchronized (lock) { - final Set set = getBag().uniqueSet(); - return new SynchronizedBagSet(set, lock); - } - } - - @Override - 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); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/SynchronizedSortedBag.java b/src/main/java/repack/apache/commons/collections4/bag/SynchronizedSortedBag.java deleted file mode 100644 index 4ea5629a1a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/SynchronizedSortedBag.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bag; - -import java.util.Comparator; - -import repack.apache.commons.collections4.Bag; -import repack.apache.commons.collections4.SortedBag; - -/** - * Decorates another {@link SortedBag} to synchronize its behavior - * for a multithreaded 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. - *

- * - * @param the type of elements in this bag - * @since 3.0 - */ -public class SynchronizedSortedBag extends SynchronizedBag implements SortedBag { - - /** Serialization version */ - private static final long serialVersionUID = 722374056718497858L; - - /** - * Factory method to create a synchronized sorted bag. - * - * @param the type of the elements in the bag - * @param bag the bag to decorate, must not be null - * @return a new synchronized SortedBag - * @throws NullPointerException 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 NullPointerException 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 NullPointerException if bag or lock 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(); - } - - - @Override - public synchronized E first() { - synchronized (lock) { - return getSortedBag().first(); - } - } - - @Override - public synchronized E last() { - synchronized (lock) { - return getSortedBag().last(); - } - } - - @Override - public synchronized Comparator comparator() { - synchronized (lock) { - return getSortedBag().comparator(); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/TransformedBag.java b/src/main/java/repack/apache/commons/collections4/bag/TransformedBag.java deleted file mode 100644 index a89a8f69aa..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/TransformedBag.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bag; - -import java.util.Set; - -import repack.apache.commons.collections4.Bag; -import repack.apache.commons.collections4.Transformer; -import repack.apache.commons.collections4.collection.TransformedCollection; -import repack.apache.commons.collections4.set.TransformedSet; - -/** - * 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. - *

- * - * @param the type of elements in this bag - * @since 3.0 - */ -public class TransformedBag extends TransformedCollection implements Bag { - - /** Serialization version */ - private static final long serialVersionUID = 5421170911299074185L; - - /** - * Factory method to create a transforming bag. - *

- * If there are any elements already in the bag being decorated, they - * are NOT transformed. 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 NullPointerException 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 NullPointerException 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 (!bag.isEmpty()) { - @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 NullPointerException 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(); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - - - @Override - public int getCount(final Object object) { - return getBag().getCount(object); - } - - @Override - public boolean remove(final Object object, final int nCopies) { - return getBag().remove(object, nCopies); - } - - - @Override - public boolean add(final E object, final int nCopies) { - return getBag().add(transform(object), nCopies); - } - - @Override - public Set uniqueSet() { - final Set set = getBag().uniqueSet(); - return TransformedSet.transformingSet(set, transformer); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/TransformedSortedBag.java b/src/main/java/repack/apache/commons/collections4/bag/TransformedSortedBag.java deleted file mode 100644 index 12178b3ab4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/TransformedSortedBag.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bag; - -import java.util.Comparator; - -import repack.apache.commons.collections4.SortedBag; -import repack.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. - *

- * - * @param the type of elements in this bag - * @since 3.0 - */ -public class TransformedSortedBag extends TransformedBag implements SortedBag { - - /** Serialization version */ - private static final long serialVersionUID = -251737742649401930L; - - /** - * Factory method to create a transforming sorted bag. - *

- * If there are any elements already in the bag being decorated, they - * are NOT transformed. 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 NullPointerException 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 NullPointerException 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 (!bag.isEmpty()) { - @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 NullPointerException 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(); - } - - - @Override - public E first() { - return getSortedBag().first(); - } - - @Override - public E last() { - return getSortedBag().last(); - } - - @Override - public Comparator comparator() { - return getSortedBag().comparator(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/TreeBag.java b/src/main/java/repack/apache/commons/collections4/bag/TreeBag.java deleted file mode 100644 index e55c7e5f62..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/TreeBag.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.Objects; -import java.util.SortedMap; -import java.util.TreeMap; - -import repack.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 repack.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. - *

- * - * @param the type of elements in this bag - * @since 3.0 (previously in main package v2.0) - */ -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 - * @throws NullPointerException if the specified key is null and this bag uses - * natural ordering, or its comparator does not permit null keys - */ - @Override - public boolean add(final E object) { - if (comparator() == null && !(object instanceof Comparable)) { - Objects.requireNonNull(object, "object"); - 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); - } - - - @Override - public E first() { - return getMap().firstKey(); - } - - @Override - public E last() { - return getMap().lastKey(); - } - - @Override - public Comparator comparator() { - return getMap().comparator(); - } - - @Override - protected SortedMap getMap() { - return (SortedMap) super.getMap(); - } - - /** - * Write the bag out using a custom routine. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - out.writeObject(comparator()); - super.doWriteObject(out); - } - - /** - * Read the bag in using a custom routine. - * - * @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 - */ - 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/UnmodifiableBag.java b/src/main/java/repack/apache/commons/collections4/bag/UnmodifiableBag.java deleted file mode 100644 index a7e5da3545..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/UnmodifiableBag.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.function.Predicate; - -import repack.apache.commons.collections4.Bag; -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableIterator; -import repack.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. - *

- * - * @param the type of elements in this bag - * @since 3.0 - */ -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 NullPointerException 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 NullPointerException 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 if an error occurs while writing to the 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 error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @throws ClassCastException if deserialized 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/UnmodifiableSortedBag.java b/src/main/java/repack/apache/commons/collections4/bag/UnmodifiableSortedBag.java deleted file mode 100644 index f5dc92f350..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/UnmodifiableSortedBag.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.function.Predicate; - -import repack.apache.commons.collections4.SortedBag; -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableIterator; -import repack.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. - *

- * - * @param the type of elements in this bag - * @since 3.0 - */ -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 NullPointerException 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 NullPointerException 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 if an error occurs while writing to the 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 error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @throws ClassCastException if deserialized 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bag/package-info.java b/src/main/java/repack/apache/commons/collections4/bag/package-info.java deleted file mode 100644 index 90ac485843..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bag/package-info.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 repack.apache.commons.collections4.Bag Bag} and - * {@link repack.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 multithreaded 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 - *
- * - */ -package repack.apache.commons.collections4.bag; diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/AbstractBidiMapDecorator.java b/src/main/java/repack/apache/commons/collections4/bidimap/AbstractBidiMapDecorator.java deleted file mode 100644 index ca270f56ba..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/AbstractBidiMapDecorator.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bidimap; - -import java.util.Set; - -import repack.apache.commons.collections4.BidiMap; -import repack.apache.commons.collections4.MapIterator; -import repack.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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public abstract class AbstractBidiMapDecorator - extends AbstractMapDecorator implements BidiMap { - - /** - * Constructor that wraps (not copies). - * - * @param map the map to decorate, must not be null - * @throws NullPointerException 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(); - } - - @Override - public K getKey(final Object value) { - return decorated().getKey(value); - } - - @Override - public K removeValue(final Object value) { - return decorated().removeValue(value); - } - - @Override - public BidiMap inverseBidiMap() { - return decorated().inverseBidiMap(); - } - - @Override - public Set values() { - return decorated().values(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/AbstractDualBidiMap.java b/src/main/java/repack/apache/commons/collections4/bidimap/AbstractDualBidiMap.java deleted file mode 100644 index 5b99fe40df..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/AbstractDualBidiMap.java +++ /dev/null @@ -1,815 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bidimap; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.BidiMap; -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.ResettableIterator; -import repack.apache.commons.collections4.collection.AbstractCollectionDecorator; -import repack.apache.commons.collections4.iterators.AbstractIteratorDecorator; -import repack.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. - *

- * - * @param the type of the keys in the map - * @param the type of the values in the map - * - * @see DualHashBidiMap - * @see DualTreeBidiMap - * @since 3.0 - */ -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; - - /** - * View of the keys. - */ - transient Set keySet; - - /** - * View of the values. - */ - transient Set values; - - /** - * View of the entries. - */ - transient Set> entrySet; - - /** - * Creates an empty map, initialized by {@code createMap}. - *

- * This constructor remains in place for deserialization. - * All other usage is deprecated in favour of - * {@link #AbstractDualBidiMap(Map, Map)}. - */ - protected AbstractDualBidiMap() { - } - - /** - * 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 {@code 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) { - this.normalMap = normalMap; - this.reverseMap = reverseMap; - } - - /** - * Constructs a map that decorates the specified maps, - * used by the subclass {@code 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) { - 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 bidi map - */ - protected abstract BidiMap createBidiMap(Map normalMap, Map reverseMap, BidiMap inverseMap); - - // Map delegation - - @Override - public V get(final Object key) { - return normalMap.get(key); - } - - @Override - public int size() { - return normalMap.size(); - } - - @Override - public boolean isEmpty() { - return normalMap.isEmpty(); - } - - @Override - 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 - - @Override - 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; - } - - @Override - public void putAll(final Map map) { - for (final Map.Entry entry : map.entrySet()) { - put(entry.getKey(), entry.getValue()); - } - } - - @Override - public V remove(final Object key) { - V value = null; - if (normalMap.containsKey(key)) { - value = normalMap.remove(key); - reverseMap.remove(value); - } - return value; - } - - @Override - public void clear() { - normalMap.clear(); - reverseMap.clear(); - } - - @Override - public boolean containsValue(final Object value) { - return reverseMap.containsKey(value); - } - - // BidiMap - /** - * Obtains a {@code MapIterator} over the map. - * The iterator implements {@link BidiMapIterator}. - * This implementation relies on the entrySet iterator. - *

- * - * @return a map iterator - */ - @Override - public MapIterator mapIterator() { - return new BidiMapIterator<>(this); - } - - @Override - public K getKey(final Object value) { - return reverseMap.get(value); - } - - @Override - public K removeValue(final Object value) { - K key = null; - if (reverseMap.containsKey(value)) { - key = reverseMap.remove(value); - normalMap.remove(key); - } - return key; - } - - @Override - 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 - */ - @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. - * - * @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 - */ - @Override - 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 - */ - @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. - * - * @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 abstract static class View extends AbstractCollectionDecorator { - - /** Generated serial version ID. */ - private static final long serialVersionUID = 4621510560119690639L; - - /** The parent map */ - protected final AbstractDualBidiMap parent; - - /** - * Constructor. - * - * @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 equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - if (parent.isEmpty() || Objects.isNull(filter)) { - return false; - } - boolean modified = false; - final Iterator it = iterator(); - while (it.hasNext()) { - @SuppressWarnings("unchecked") - final E e = (E) it.next(); - if (filter.test(e)) { - it.remove(); - modified = true; - } - } - return modified; - } - - @Override - public boolean removeAll(final Collection coll) { - if (parent.isEmpty() || coll.isEmpty()) { - return false; - } - boolean modified = false; - for (final Object current : coll) { - modified |= remove(current); - } - 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 {@code 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 - * {@code 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())) { - 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; - - /** - * Constructor. - * - * @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; - - /** Whether remove is allowed at present */ - protected boolean canRemove; - - /** - * 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) { - 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; - - /** - * Constructor. - * - * @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; - - /** Whether remove is allowed at present */ - protected boolean canRemove; - - /** - * 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) { - 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; - - /** - * Constructor. - * - * @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)) { - 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; - - /** Whether remove is allowed at present */ - protected boolean canRemove; - - /** - * 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) { - throw new IllegalStateException("Iterator remove() can only be called once after next()"); - } - // store value as remove may change the entry in the decorator (e.g. 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 = 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; - - /** Whether remove is allowed at present */ - protected boolean canRemove; - - /** - * Constructor. - * @param parent the parent map - */ - protected BidiMapIterator(final AbstractDualBidiMap parent) { - this.parent = parent; - this.iterator = parent.normalMap.entrySet().iterator(); - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public K next() { - last = iterator.next(); - canRemove = true; - return last.getKey(); - } - - @Override - public void remove() { - if (!canRemove) { - throw new IllegalStateException("Iterator remove() can only be called once after next()"); - } - // store value as remove may change the entry in the decorator (e.g. TreeMap) - final V value = last.getValue(); - iterator.remove(); - parent.reverseMap.remove(value); - last = null; - canRemove = false; - } - - @Override - public K getKey() { - if (last == null) { - throw new IllegalStateException( - "Iterator getKey() can only be called after next() and before remove()"); - } - return last.getKey(); - } - - @Override - public V getValue() { - if (last == null) { - throw new IllegalStateException( - "Iterator getValue() can only be called after next() and before remove()"); - } - return last.getValue(); - } - - @Override - 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); - } - - @Override - 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[]"; - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/AbstractOrderedBidiMapDecorator.java b/src/main/java/repack/apache/commons/collections4/bidimap/AbstractOrderedBidiMapDecorator.java deleted file mode 100644 index 0b8e7ba954..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/AbstractOrderedBidiMapDecorator.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bidimap; - -import repack.apache.commons.collections4.OrderedBidiMap; -import repack.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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public abstract class AbstractOrderedBidiMapDecorator - extends AbstractBidiMapDecorator - implements OrderedBidiMap { - - /** - * Constructor that wraps (not copies). - * - * @param map the map to decorate, must not be null - * @throws NullPointerException 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(); - } - - @Override - public K firstKey() { - return decorated().firstKey(); - } - - @Override - public K lastKey() { - return decorated().lastKey(); - } - - @Override - public K nextKey(final K key) { - return decorated().nextKey(key); - } - - @Override - public K previousKey(final K key) { - return decorated().previousKey(key); - } - - @Override - public OrderedBidiMap inverseBidiMap() { - return decorated().inverseBidiMap(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/AbstractSortedBidiMapDecorator.java b/src/main/java/repack/apache/commons/collections4/bidimap/AbstractSortedBidiMapDecorator.java deleted file mode 100644 index f7ef12e47d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/AbstractSortedBidiMapDecorator.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bidimap; - -import java.util.Comparator; -import java.util.SortedMap; - -import repack.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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public abstract class AbstractSortedBidiMapDecorator - extends AbstractOrderedBidiMapDecorator implements SortedBidiMap { - - /** - * Constructor that wraps (not copies). - * - * @param map the map to decorate, must not be null - * @throws NullPointerException 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(); - } - - @Override - public Comparator comparator() { - return decorated().comparator(); - } - - @Override - public Comparator valueComparator() { - return decorated().valueComparator(); - } - - @Override - public SortedMap subMap(final K fromKey, final K toKey) { - return decorated().subMap(fromKey, toKey); - } - - @Override - public SortedMap headMap(final K toKey) { - return decorated().headMap(toKey); - } - - @Override - public SortedMap tailMap(final K fromKey) { - return decorated().tailMap(fromKey); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/DualHashBidiMap.java b/src/main/java/repack/apache/commons/collections4/bidimap/DualHashBidiMap.java deleted file mode 100644 index 876410b206..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/DualHashBidiMap.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.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 {@code createMap} method is ignored. - *

- * - * @param the type of the keys in the map - * @param the type of the values in the map - * - * @since 3.0 - */ -public class DualHashBidiMap extends AbstractDualBidiMap implements Serializable { - - /** Ensure serialization compatibility */ - private static final long serialVersionUID = 721969328361808L; - - /** - * Creates an empty {@code HashBidiMap}. - */ - public DualHashBidiMap() { - super(new HashMap<>(), new HashMap<>()); - } - - /** - * Constructs a {@code HashBidiMap} and copies the mappings from - * specified {@code 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 {@code 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/DualLinkedHashBidiMap.java b/src/main/java/repack/apache/commons/collections4/bidimap/DualLinkedHashBidiMap.java deleted file mode 100644 index 002980e205..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/DualLinkedHashBidiMap.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.BidiMap; - -/** - * Implementation of {@link BidiMap} that uses two {@link LinkedHashMap} instances. - *

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

- * - * @param the type of the keys in the map - * @param the type of the values in the map - * - * @since 4.0 - */ -public class DualLinkedHashBidiMap extends AbstractDualBidiMap implements Serializable { - - /** Ensure serialization compatibility */ - private static final long serialVersionUID = 721969328361810L; - - /** - * Creates an empty {@code HashBidiMap}. - */ - public DualLinkedHashBidiMap() { - super(new LinkedHashMap<>(), new LinkedHashMap<>()); - } - - /** - * Constructs a {@code LinkedHashBidiMap} and copies the mappings from - * specified {@link 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 {@code 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); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/DualTreeBidiMap.java b/src/main/java/repack/apache/commons/collections4/bidimap/DualTreeBidiMap.java deleted file mode 100644 index eedd0e0eb4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/DualTreeBidiMap.java +++ /dev/null @@ -1,412 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.BidiMap; -import repack.apache.commons.collections4.OrderedBidiMap; -import repack.apache.commons.collections4.OrderedMap; -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.ResettableIterator; -import repack.apache.commons.collections4.SortedBidiMap; -import repack.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 bidi map. - *

- *

- * 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 {@code createMap} method is ignored. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -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 {@link DualTreeBidiMap}. - */ - public DualTreeBidiMap() { - super(new TreeMap<>(), new TreeMap<>()); - this.comparator = null; - this.valueComparator = null; - } - - /** - * Constructs a {@link DualTreeBidiMap} and copies the mappings from - * specified {@link 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); - } - - - @Override - public Comparator comparator() { - return ((SortedMap) normalMap).comparator(); - } - - @Override - public Comparator valueComparator() { - return ((SortedMap) reverseMap).comparator(); - } - - @Override - public K firstKey() { - return ((SortedMap) normalMap).firstKey(); - } - - @Override - public K lastKey() { - return ((SortedMap) normalMap).lastKey(); - } - - @Override - 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; - } - - @Override - 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 behavior. - * - * @return a new ordered map iterator - */ - @Override - public OrderedMapIterator mapIterator() { - return new BidiOrderedMapIterator<>(this); - } - - public SortedBidiMap inverseSortedBidiMap() { - return inverseBidiMap(); - } - - public OrderedBidiMap inverseOrderedBidiMap() { - return inverseBidiMap(); - } - - - @Override - public SortedMap headMap(final K toKey) { - final SortedMap sub = ((SortedMap) normalMap).headMap(toKey); - return new ViewMap<>(this, sub); - } - - @Override - public SortedMap tailMap(final K fromKey) { - final SortedMap sub = ((SortedMap) normalMap).tailMap(fromKey); - return new ViewMap<>(this, sub); - } - - @Override - 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; - - /** - * Constructor. - * @param parent the parent map - */ - protected BidiOrderedMapIterator(final AbstractDualBidiMap parent) { - this.parent = parent; - iterator = new ArrayList<>(parent.entrySet()).listIterator(); - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public K next() { - last = iterator.next(); - return last.getKey(); - } - - @Override - public boolean hasPrevious() { - return iterator.hasPrevious(); - } - - @Override - public K previous() { - last = iterator.previous(); - return last.getKey(); - } - - @Override - public void remove() { - iterator.remove(); - parent.remove(last.getKey()); - last = null; - } - - @Override - public K getKey() { - if (last == null) { - throw new IllegalStateException( - "Iterator getKey() can only be called after next() and before remove()"); - } - return last.getKey(); - } - - @Override - public V getValue() { - if (last == null) { - throw new IllegalStateException( - "Iterator getValue() can only be called after next() and before remove()"); - } - return last.getValue(); - } - - @Override - 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 - last.setValue(value); - return oldValue; - } - - @Override - 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/TreeBidiMap.java b/src/main/java/repack/apache/commons/collections4/bidimap/TreeBidiMap.java deleted file mode 100644 index 142c9148ce..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/TreeBidiMap.java +++ /dev/null @@ -1,2237 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bidimap; - -import static repack.apache.commons.collections4.bidimap.TreeBidiMap.DataElement.KEY; -import static repack.apache.commons.collections4.bidimap.TreeBidiMap.DataElement.VALUE; - -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.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.KeyValue; -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.OrderedBidiMap; -import repack.apache.commons.collections4.OrderedIterator; -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.iterators.EmptyOrderedMapIterator; -import repack.apache.commons.collections4.keyvalue.UnmodifiableMapEntry; - -/** - * Red-Black tree-based implementation of BidiMap where all objects added - * implement the {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * - * @since 3.0 (previously DoubleOrderedMap v2.0) - */ -public class TreeBidiMap, V extends Comparable> - implements OrderedBidiMap, Serializable { - - enum DataElement { - KEY("key"), VALUE("value"); - - private final String description; - - /** - * Creates a new TreeBidiMap.DataElement. - * - * @param description the description for the element - */ - 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; - private transient int modifications; - private transient Set keySet; - private transient Set valuesSet; - private transient Set> entrySet; - private transient Inverse inverse; - - /** - * Constructs a new empty TreeBidiMap. - */ - @SuppressWarnings("unchecked") - public TreeBidiMap() { - 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 - */ - @Override - public int size() { - return nodeCount; - } - - /** - * Checks whether the map is empty or not. - * - * @return true if the map is empty - */ - @Override - public boolean isEmpty() { - return nodeCount == 0; - } - - /** - * Checks whether this map contains a mapping for the specified key. - *

- * The key must implement {@code 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 - */ - @Override - public boolean containsKey(final Object key) { - checkKey(key); - return lookupKey(key) != null; - } - - /** - * Checks whether this map contains a mapping for the specified value. - *

- * The value must implement {@code 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 - */ - @Override - 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 {@code 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 - */ - @Override - 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 {@code 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 - */ - @Override - 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 {@code Comparable}. - * - * @param map the map to copy from - */ - @Override - 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 {@code 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 - */ - @Override - public V remove(final Object key) { - return doRemoveKey(key); - } - - /** - * Removes all mappings from this map. - */ - @Override - 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 {@code 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 - */ - @Override - 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 {@code 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 {@code Comparable}. - * - * @param key the key to search for next from - * @return the next key, null if no match or at end - */ - @Override - 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 {@code Comparable}. - * - * @param key the key to search for previous from - * @return the previous key, null if no match or at start - */ - @Override - 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. - */ - @Override - 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. - */ - @Override - 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. - */ - @Override - public Set> entrySet() { - if (entrySet == null) { - entrySet = new EntryView(); - } - return entrySet; - } - - @Override - public OrderedMapIterator mapIterator() { - if (isEmpty()) { - return EmptyOrderedMapIterator.emptyOrderedMapIterator(); - } - return new ViewMapIterator(KEY); - } - - /** - * Gets the inverse map for comparison. - * - * @return the inverse map - */ - @Override - 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); - } - - /** - * Puts 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"); - } - if (cmp < 0) { - if (node.getLeft(KEY) == null) { - final Node newNode = new Node<>(key, value); - - insertValue(newNode); - node.setLeft(newNode, KEY); - newNode.setParent(node, KEY); - doRedBlackInsert(newNode, KEY); - grow(); - - break; - } - node = node.getLeft(KEY); - } else { // cmp > 0 - if (node.getRight(KEY) == null) { - final Node newNode = new Node<>(key, value); - - insertValue(newNode); - node.setRight(newNode, KEY); - newNode.setParent(node, KEY); - doRedBlackInsert(newNode, KEY); - grow(); - - break; - } - node = node.getRight(KEY); - } - } - } - } - - 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(); - } - - /** - * Does the actual lookup of a piece of data. - * - * @param data the key or value to be looked up - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @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; - } - 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); - } - - /** - * Gets the next larger node from the specified node. - * - * @param node the node to be searched from - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @return the specified node - */ - private Node nextGreater(final Node node, final DataElement dataElement) { - final 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; - } - - /** - * Gets the next smaller node from the specified node. - * - * @param node the node to be searched from - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @return the specified node - */ - private Node nextSmaller(final Node node, final DataElement dataElement) { - final 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; - } - - - /** - * Compares 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); - } - - /** - * Finds the least node from a given node. - * - * @param node the node from which we will start searching - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @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; - } - - /** - * Finds the greatest node from a given node. - * - * @param node the node from which we will start searching - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @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; - } - - /** - * Copies 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 dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - 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 dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - 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 dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - private static boolean isBlack(final Node node, final DataElement dataElement) { - return node == null || node.isBlack(dataElement); - } - - /** - * Forces a node (if it exists) red. - * - * @param node the node (may be null) in question - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - private static void makeRed(final Node node, final DataElement dataElement) { - if (node != null) { - node.setRed(dataElement); - } - } - - /** - * Forces a node (if it exists) black. - * - * @param node the node (may be null) in question - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - private static void makeBlack(final Node node, final DataElement dataElement) { - if (node != null) { - node.setBlack(dataElement); - } - } - - /** - * Gets 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 dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - private Node getGrandParent(final Node node, final DataElement dataElement) { - return getParent(getParent(node, dataElement), dataElement); - } - - /** - * Gets 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 dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - private Node getParent(final Node node, final DataElement dataElement) { - return node == null ? null : node.getParent(dataElement); - } - - /** - * Gets a node's right child. mind you, the node may not exist. no - * problem. - * - * @param node the node (may be null) in question - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - private Node getRightChild(final Node node, final DataElement dataElement) { - return node == null ? null : node.getRight(dataElement); - } - - /** - * Gets a node's left child. mind you, the node may not exist. no - * problem. - * - * @param node the node (may be null) in question - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - private Node getLeftChild(final Node node, final DataElement dataElement) { - return node == null ? null : node.getLeft(dataElement); - } - - /** - * Does a rotate left. standard fare in the world of balanced trees. - * - * @param node the node to be rotated - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - 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); - } - - /** - * Does a rotate right. standard fare in the world of balanced trees. - * - * @param node the node to be rotated - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - 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 anymore. - * - * @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 anymore. - * - * @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 anymore. 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); - } - - /** - * Swaps 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; - } - } - - /** - * Checks if an object is fit to be proper input ... has to be - * Comparable and non-null. - * - * @param obj the object being checked - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * - * @throws NullPointerException if o is null - * @throws ClassCastException if o is not Comparable - */ - private static void checkNonNullComparable(final Object obj, final DataElement dataElement) { - Objects.requireNonNull(obj, Objects.toString(dataElement)); - if (!(obj instanceof Comparable)) { - throw new ClassCastException(dataElement + " must be Comparable"); - } - } - - /** - * Checks 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); - } - - /** - * Checks 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); - } - - /** - * Checks 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); - } - - /** - * Increments 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++; - } - - /** - * Bumps up the size and note that the map has changed. - */ - private void grow() { - modify(); - nodeCount++; - } - - /** - * Decrements the size and note that the map has changed. - */ - private void shrink() { - modify(); - nodeCount--; - } - - /** - * Inserts 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"); - } - if (cmp < 0) { - if (node.getLeft(VALUE) == null) { - node.setLeft(newNode, VALUE); - newNode.setParent(node, VALUE); - doRedBlackInsert(newNode, VALUE); - - break; - } - node = node.getLeft(VALUE); - } else { // cmp > 0 - if (node.getRight(VALUE) == null) { - node.setRight(newNode, VALUE); - newNode.setParent(node, VALUE); - doRedBlackInsert(newNode, VALUE); - - break; - } - node = node.getRight(VALUE); - } - } - } - - /** - * Compares for equals as per the API. - * - * @param obj the object to compare to - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @return true if equal - */ - private boolean doEquals(final Object obj, final DataElement dataElement) { - if (obj == this) { - return true; - } - if (!(obj instanceof Map)) { - 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))) { - return false; - } - } - } catch (final ClassCastException | NullPointerException ex) { - return false; - } - } - return true; - } - - /** - * Gets the hash code value for this map as per the API. - * - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @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 dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @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. - * - * @param stream 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") // 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]; - final int size = stream.readInt(); - for (int i = 0; i < size; i++){ - final K k =(K) stream.readObject(); - final V v =(V) stream.readObject(); - put(k, v); - } - } - - /** - * Writes the content to the stream for serialization. - * - * @param stream the output stream - * @throws IOException if an error occurs while writing to the stream - */ - 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 - */ - View(final DataElement orderType) { - this.orderType = orderType; - } - - @Override - public int size() { - return TreeBidiMap.this.size(); - } - - @Override - public void clear() { - TreeBidiMap.this.clear(); - } - } - - class KeyView extends View { - - /** - * Creates a new TreeBidiMap.KeyView. - */ - 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 { - - /** - * Creates a new TreeBidiMap.ValueView. - */ - 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)) { - 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)) { - 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)) { - 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)) { - 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 - */ - ViewIterator(final DataElement orderType) { - 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); - } - - @Override - public K getKey() { - if (lastReturnedNode == null) { - throw new IllegalStateException( - "Iterator getKey() can only be called after next() and before remove()"); - } - return lastReturnedNode.getKey(); - } - - @Override - public V getValue() { - if (lastReturnedNode == null) { - throw new IllegalStateException( - "Iterator getValue() can only be called after next() and before remove()"); - } - return lastReturnedNode.getValue(); - } - - @Override - public V setValue(final V obj) { - throw new UnsupportedOperationException(); - } - - @Override - public K next() { - return navigateNext().getKey(); - } - - @Override - public K previous() { - return navigatePrevious().getKey(); - } - } - - /** - * An iterator over the map. - */ - class InverseViewMapIterator extends ViewIterator implements OrderedMapIterator { - - /** - * Creates a new TreeBidiMap.InverseViewMapIterator. - */ - InverseViewMapIterator(final DataElement orderType) { - super(orderType); - } - - @Override - public V getKey() { - if (lastReturnedNode == null) { - throw new IllegalStateException( - "Iterator getKey() can only be called after next() and before remove()"); - } - return lastReturnedNode.getValue(); - } - - @Override - public K getValue() { - if (lastReturnedNode == null) { - throw new IllegalStateException( - "Iterator getValue() can only be called after next() and before remove()"); - } - return lastReturnedNode.getKey(); - } - - @Override - public K setValue(final K obj) { - throw new UnsupportedOperationException(); - } - - @Override - public V next() { - return navigateNext().getValue(); - } - - @Override - public V previous() { - return navigatePrevious().getValue(); - } - } - - /** - * An iterator over the map entries. - */ - class ViewMapEntryIterator extends ViewIterator implements OrderedIterator> { - - /** - * Constructor. - */ - ViewMapEntryIterator() { - super(KEY); - } - - @Override - public Map.Entry next() { - return navigateNext(); - } - - @Override - public Map.Entry previous() { - return navigatePrevious(); - } - } - - /** - * An iterator over the inverse map entries. - */ - class InverseViewMapEntryIterator extends ViewIterator implements OrderedIterator> { - - /** - * Constructor. - */ - InverseViewMapEntryIterator() { - super(VALUE); - } - - @Override - public Map.Entry next() { - return createEntry(navigateNext()); - } - - @Override - 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; - - /** - * Makes a new cell with given key and value, and with null - * links, and black (true) colors. - * - * @param key the key of this node - * @param value the value of this node - */ - @SuppressWarnings("unchecked") - Node(final K key, final V value) { - 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()]; - } - - /** - * Sets this node's parent node. - * - * @param node the new parent node - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - private void setParent(final Node node, final DataElement dataElement) { - parentNode[dataElement.ordinal()] = node; - } - - /** - * Gets the parent node. - * - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @return the parent node, may be null - */ - private Node getParent(final DataElement dataElement) { - return parentNode[dataElement.ordinal()]; - } - - /** - * Exchanges colors with another node. - * - * @param node the node to swap with - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - 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 dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @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 dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - * @return true if non-black - */ - private boolean isRed(final DataElement dataElement) { - return !blackColor[dataElement.ordinal()]; - } - - /** - * Makes this node black. - * - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - private void setBlack(final DataElement dataElement) { - blackColor[dataElement.ordinal()] = true; - } - - /** - * Makes this node red. - * - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - private void setRed(final DataElement dataElement) { - blackColor[dataElement.ordinal()] = false; - } - - /** - * Makes this node the same color as another. - * - * @param node the node whose color we're adopting - * @param dataElement either the {@link DataElement#KEY key} - * or the {@link DataElement#VALUE value}. - */ - 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. - */ - @Override - public K getKey() { - return key; - } - - /** - * Gets the value. - * - * @return the value corresponding to this entry. - */ - @Override - public V getValue() { - return value; - } - - /** - * Optional operation that is not permitted in this implementation. - * - * @param ignored this parameter is ignored. - * @return does not return - * @throws UnsupportedOperationException always - */ - @Override - 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; - - @Override - public int size() { - return TreeBidiMap.this.size(); - } - - @Override - public boolean isEmpty() { - return TreeBidiMap.this.isEmpty(); - } - - @Override - public K get(final Object key) { - return TreeBidiMap.this.getKey(key); - } - - @Override - public V getKey(final Object value) { - return TreeBidiMap.this.get(value); - } - - @Override - public boolean containsKey(final Object key) { - return TreeBidiMap.this.containsValue(key); - } - - @Override - public boolean containsValue(final Object value) { - return TreeBidiMap.this.containsKey(value); - } - - @Override - public V firstKey() { - if (TreeBidiMap.this.nodeCount == 0) { - throw new NoSuchElementException("Map is empty"); - } - return leastNode(TreeBidiMap.this.rootNode[VALUE.ordinal()], VALUE).getValue(); - } - - @Override - public V lastKey() { - if (TreeBidiMap.this.nodeCount == 0) { - throw new NoSuchElementException("Map is empty"); - } - return greatestNode(TreeBidiMap.this.rootNode[VALUE.ordinal()], VALUE).getValue(); - } - - @Override - public V nextKey(final V key) { - checkKey(key); - final Node node = nextGreater(TreeBidiMap.this.lookup(key, VALUE), VALUE); - return node == null ? null : node.getValue(); - } - - @Override - 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(); - } - - @Override - public K put(final V key, final K value) { - final K result = get(key); - TreeBidiMap.this.doPut(value, key); - return result; - } - - @Override - public void putAll(final Map map) { - for (final Map.Entry e : map.entrySet()) { - put(e.getKey(), e.getValue()); - } - } - - @Override - public K remove(final Object key) { - return TreeBidiMap.this.removeValue(key); - } - - @Override - public V removeValue(final Object value) { - return TreeBidiMap.this.remove(value); - } - - @Override - public void clear() { - TreeBidiMap.this.clear(); - } - - @Override - public Set keySet() { - if (inverseKeySet == null) { - inverseKeySet = new ValueView(VALUE); - } - return inverseKeySet; - } - - @Override - public Set values() { - if (inverseValuesSet == null) { - inverseValuesSet = new KeyView(VALUE); - } - return inverseValuesSet; - } - - @Override - public Set> entrySet() { - if (inverseEntrySet == null) { - inverseEntrySet = new InverseEntryView(); - } - return inverseEntrySet; - } - - @Override - public OrderedMapIterator mapIterator() { - if (isEmpty()) { - return EmptyOrderedMapIterator.emptyOrderedMapIterator(); - } - return new InverseViewMapIterator(VALUE); - } - - @Override - public OrderedBidiMap inverseBidiMap() { - return TreeBidiMap.this; - } - - @Override - public boolean equals(final Object obj) { - return TreeBidiMap.this.doEquals(obj, VALUE); - } - - @Override - public int hashCode() { - return TreeBidiMap.this.doHashCode(VALUE); - } - - @Override - public String toString() { - return TreeBidiMap.this.doToString(VALUE); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableBidiMap.java b/src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableBidiMap.java deleted file mode 100644 index 188fe721d1..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableBidiMap.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bidimap; - -import java.util.Map; -import java.util.Set; - -import repack.apache.commons.collections4.BidiMap; -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableMapIterator; -import repack.apache.commons.collections4.map.UnmodifiableEntrySet; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates another {@link BidiMap} to ensure it can't be altered. - *

- * Attempts to modify it will result in an UnsupportedOperationException. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public final class UnmodifiableBidiMap - extends AbstractBidiMapDecorator implements Unmodifiable { - - /** The inverse unmodifiable map */ - private UnmodifiableBidiMap inverse; - - /** - * Factory method to create an unmodifiable map. - *

- * If the map passed in is already unmodifiable, it is returned. - * - * @param the key type - * @param the value type - * @param map the map to decorate, must not be null - * @return an unmodifiable BidiMap - * @throws NullPointerException 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 NullPointerException 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableOrderedBidiMap.java b/src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableOrderedBidiMap.java deleted file mode 100644 index d2c06a1477..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableOrderedBidiMap.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bidimap; - -import java.util.Map; -import java.util.Set; - -import repack.apache.commons.collections4.OrderedBidiMap; -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableOrderedMapIterator; -import repack.apache.commons.collections4.map.UnmodifiableEntrySet; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates another {@link OrderedBidiMap} to ensure it can't be altered. - *

- * Attempts to modify it will result in an UnsupportedOperationException. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public final class UnmodifiableOrderedBidiMap - extends AbstractOrderedBidiMapDecorator implements Unmodifiable { - - /** The inverse unmodifiable map */ - private UnmodifiableOrderedBidiMap inverse; - - /** - * Factory method to create an unmodifiable map. - *

- * If the map passed in is already unmodifiable, it is returned. - * - * @param the key type - * @param the value type - * @param map the map to decorate, must not be null - * @return an unmodifiable OrderedBidiMap - * @throws NullPointerException 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 NullPointerException 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableSortedBidiMap.java b/src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableSortedBidiMap.java deleted file mode 100644 index aa0d06adb5..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/UnmodifiableSortedBidiMap.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bidimap; - -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; - -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.SortedBidiMap; -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableOrderedMapIterator; -import repack.apache.commons.collections4.map.UnmodifiableEntrySet; -import repack.apache.commons.collections4.map.UnmodifiableSortedMap; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates another {@link SortedBidiMap} to ensure it can't be altered. - *

- * Attempts to modify it will result in an {@link UnsupportedOperationException}. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public final class UnmodifiableSortedBidiMap - extends AbstractSortedBidiMapDecorator implements Unmodifiable { - - /** The inverse unmodifiable map */ - private UnmodifiableSortedBidiMap inverse; - - /** - * Factory method to create an unmodifiable map. - *

- * If the map passed in is already unmodifiable, it is returned. - * - * @param the key type - * @param the value type - * @param map the map to decorate, must not be null - * @return an unmodifiable SortedBidiMap - * @throws NullPointerException 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 NullPointerException 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/bidimap/package-info.java b/src/main/java/repack/apache/commons/collections4/bidimap/package-info.java deleted file mode 100644 index 84176040aa..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bidimap/package-info.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 repack.apache.commons.collections4.BidiMap BidiMap}, - * {@link repack.apache.commons.collections4.OrderedBidiMap OrderedBidiMap} and - * {@link repack.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 - *
- * - */ -package repack.apache.commons.collections4.bidimap; diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/ArrayCountingBloomFilter.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/ArrayCountingBloomFilter.java deleted file mode 100644 index be1c547e18..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/ArrayCountingBloomFilter.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.Arrays; -import java.util.Objects; -import java.util.function.IntPredicate; -import java.util.function.LongPredicate; -import java.util.stream.IntStream; - -/** - * A counting Bloom filter using an int array to track counts for each enabled bit - * index. - * - *

Any operation that results in negative counts or integer overflow of - * counts will mark this filter as invalid. This transition is not reversible. - * The operation is completed in full, no exception is raised and the state is - * set to invalid. This allows the counts for the filter immediately prior to the - * operation that created the invalid state to be recovered. See the documentation - * in {@link #isValid()} for details.

- * - *

All the operations in the filter assume the counts are currently valid, - * for example {@code cardinality} or {@code contains} operations. Behavior of an invalid - * filter is undefined. It will no longer function identically to a standard - * Bloom filter that is the merge of all the Bloom filters that have been added - * to and not later subtracted from the counting Bloom filter.

- * - *

The maximum supported number of items that can be stored in the filter is - * limited by the maximum array size combined with the {@link Shape}. For - * example an implementation using a {@link Shape} with a false-positive - * probability of 1e-6 and {@link Integer#MAX_VALUE} bits can reversibly store - * approximately 75 million items using 20 hash functions per item with a memory - * consumption of approximately 8 GB. - * - * @see Shape - * @since 4.5 - */ -public final class ArrayCountingBloomFilter implements CountingBloomFilter { - - /** - * The shape of this Bloom filter. - */ - private final Shape shape; - - /** - * The count of each bit index in the filter. - */ - private final int[] counts; - - /** - * The state flag. This is a bitwise @{code OR} of the entire history of all updated - * counts. If negative then a negative count or integer overflow has occurred on - * one or more counts in the history of the filter and the state is invalid. - * - *

Maintenance of this state flag is branch-free for improved performance. It - * eliminates a conditional check for a negative count during remove/subtract - * operations and a conditional check for integer overflow during merge/add - * operations.

- * - *

Note: Integer overflow is unlikely in realistic usage scenarios. A count - * that overflows indicates that the number of items in the filter exceeds the - * maximum possible size (number of bits) of any Bloom filter constrained by - * integer indices. At this point the filter is most likely full (all bits are - * non-zero) and thus useless.

- * - *

Negative counts are a concern if the filter is used incorrectly by - * removing an item that was never added. It is expected that a user of a - * counting Bloom filter will not perform this action as it is a mistake. - * Enabling an explicit recovery path for negative or overflow counts is a major - * performance burden not deemed necessary for the unlikely scenarios when an - * invalid state is created. Maintenance of the state flag is a concession to - * flag improper use that should not have a major performance impact.

- */ - private int state; - - /** - * Constructs an empty counting Bloom filter with the specified shape. - * - * @param shape the shape of the filter - * - */ - public ArrayCountingBloomFilter(final Shape shape) { - Objects.requireNonNull(shape, "shape"); - this.shape = shape; - counts = new int[shape.getNumberOfBits()]; - } - - private ArrayCountingBloomFilter(final ArrayCountingBloomFilter source) { - this.shape = source.shape; - this.state = source.state; - this.counts = source.counts.clone(); - } - - @Override - public void clear() { - Arrays.fill(counts, 0); - } - - @Override - public ArrayCountingBloomFilter copy() { - return new ArrayCountingBloomFilter(this); - } - - @Override - public int characteristics() { - return SPARSE; - } - - @Override - public int cardinality() { - return (int) IntStream.range(0, counts.length).filter(i -> counts[i] > 0).count(); - } - - @Override - public boolean add(final BitCountProducer other) { - Objects.requireNonNull(other, "other"); - other.forEachCount(this::add); - return isValid(); - } - - @Override - public boolean subtract(final BitCountProducer other) { - Objects.requireNonNull(other, "other"); - other.forEachCount(this::subtract); - return isValid(); - } - - /** - * {@inheritDoc} - * - *

Implementation note - * - *

The state transition to invalid is permanent.

- * - *

This implementation does not correct negative counts to zero or integer - * overflow counts to {@link Integer#MAX_VALUE}. Thus the operation that - * generated invalid counts can be reversed by using the complement of the - * original operation with the same Bloom filter. This will restore the counts - * to the state prior to the invalid operation. Counts can then be extracted - * using {@link #forEachCount(BitCountConsumer)}.

- */ - @Override - public boolean isValid() { - return state >= 0; - } - - @Override - public boolean forEachCount(final BitCountProducer.BitCountConsumer consumer) { - Objects.requireNonNull(consumer, "consumer"); - for (int i = 0; i < counts.length; i++) { - if (counts[i] != 0 && !consumer.test(i, counts[i])) { - return false; - } - } - return true; - } - - @Override - public boolean forEachIndex(final IntPredicate consumer) { - Objects.requireNonNull(consumer, "consumer"); - for (int i = 0; i < counts.length; i++) { - if (counts[i] != 0 && !consumer.test(i)) { - return false; - } - } - return true; - } - - @Override - public boolean forEachBitMap(final LongPredicate consumer) { - Objects.requireNonNull(consumer, "consumer"); - final int blocksm1 = BitMap.numberOfBitMaps(counts.length) - 1; - int i = 0; - long value; - // must break final block separate as the number of bits may not fall on the long boundary - for (int j = 0; j < blocksm1; j++) { - value = 0; - for (int k = 0; k < Long.SIZE; k++) { - if (counts[i++] != 0) { - value |= BitMap.getLongBit(k); - } - } - if (!consumer.test(value)) { - return false; - } - } - // Final block - value = 0; - for (int k = 0; i < counts.length; k++) { - if (counts[i++] != 0) { - value |= BitMap.getLongBit(k); - } - } - return consumer.test(value); - } - - /** - * Add to the count for the bit index. - * - * @param idx the index - * @param addend the amount to add - * @return {@code true} always. - */ - private boolean add(final int idx, final int addend) { - final int updated = counts[idx] + addend; - state |= updated; - counts[idx] = updated; - return true; - } - - /** - * Subtract from the count for the bit index. - * - * @param idx the index - * @param subtrahend the amount to subtract - * @return {@code true} always. - */ - private boolean subtract(final int idx, final int subtrahend) { - final int updated = counts[idx] - subtrahend; - state |= updated; - counts[idx] = updated; - return true; - } - - @Override - public Shape getShape() { - return shape; - } - - @Override - public boolean contains(final IndexProducer indexProducer) { - return indexProducer.forEachIndex(idx -> this.counts[idx] != 0); - } - - @Override - public boolean contains(final BitMapProducer bitMapProducer) { - return contains(IndexProducer.fromBitMapProducer(bitMapProducer)); - } - - @Override - public int[] asIndexArray() { - return IntStream.range(0, counts.length).filter(i -> counts[i] > 0).toArray(); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/BitCountProducer.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/BitCountProducer.java deleted file mode 100644 index ae91720529..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/BitCountProducer.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.function.IntPredicate; - -/* - * Defines a mapping of index to counts. - * - *

Note that a BitCountProducer may return duplicate indices and may be unordered. - * - *

Implementations must guarantee that: - * - *

    - *
  • The mapping of index to counts is the combined sum of counts at each index. - *
  • For every unique value produced by the IndexProducer there will be at least one matching - * index and count produced by the BitCountProducer. - *
  • The BitCountProducer will not generate indices that are not output by the IndexProducer. - *
- * - *

Note that implementations that do not output duplicate indices for BitCountProducer and - * do for IndexProducer, or vice versa, are consistent if the distinct indices from each are - * the same. - * - *

For example the mapping [(1,2),(2,3),(3,1)] can be output with many combinations including: - *

- * [(1,2),(2,3),(3,1)]
- * [(1,1),(1,1),(2,1),(2,1),(2,1),(3,1)]
- * [(1,1),(3,1),(1,1),(2,1),(2,1),(2,1)]
- * [(3,1),(1,1),(2,2),(1,1),(2,1)]
- * ...
- * 
- * - * @since 4.5 - */ -@FunctionalInterface -public interface BitCountProducer extends IndexProducer { - - /** - * Performs the given action for each {@code } pair where the count is non-zero. - * Any exceptions thrown by the action are relayed to the caller. The consumer is applied to each - * index-count pair, if the consumer returns {@code false} the execution is stopped, {@code false} - * is returned, and no further pairs are processed. - * - * Duplicate indices are not required to be aggregated. Duplicates may be output by the producer as - * noted in the class javadoc. - * - * @param consumer the action to be performed for each non-zero bit count - * @return {@code true} if all count pairs return true from consumer, {@code false} otherwise. - * @throws NullPointerException if the specified consumer is null - */ - boolean forEachCount(BitCountConsumer consumer); - - /** - * The default implementation returns indices with ordering and uniqueness of {@code forEachCount()}. - */ - @Override - default boolean forEachIndex(final IntPredicate predicate) { - return forEachCount((i, v) -> predicate.test(i)); - } - - /** - * Creates a BitCountProducer from an IndexProducer. The resulting - * producer will return every index from the IndexProducer with a count of 1. - * - *

Note that the BitCountProducer does not remove duplicates. Any use of the - * BitCountProducer to create an aggregate mapping of index to counts, such as a - * CountingBloomFilter, should use the same BitCountProducer in both add and - * subtract operations to maintain consistency. - *

- * @param idx An index producer. - * @return A BitCountProducer with the same indices as the IndexProducer. - */ - static BitCountProducer from(final IndexProducer idx) { - return new BitCountProducer() { - @Override - public boolean forEachCount(final BitCountConsumer consumer) { - return idx.forEachIndex(i -> consumer.test(i, 1)); - } - - @Override - public int[] asIndexArray() { - return idx.asIndexArray(); - } - - @Override - public boolean forEachIndex(final IntPredicate predicate) { - return idx.forEachIndex(predicate); - } - }; - } - - /** - * Represents an operation that accepts an {@code } pair representing - * the count for a bit index. Returns {@code true} - * if processing should continue, {@code false} otherwise. - * - *

Note: This is a functional interface as a specialization of - * {@link java.util.function.BiPredicate} for {@code int}.

- */ - @FunctionalInterface - interface BitCountConsumer { - /** - * Performs an operation on the given {@code } pair. - * - * @param index the bit index. - * @param count the count at the specified bit index. - * @return {@code true} if processing should continue, {@code false} if processing should stop. - */ - boolean test(int index, int count); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/BitMap.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/BitMap.java deleted file mode 100644 index b0a9445006..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/BitMap.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -/** - * Contains functions to convert {@code int} indices into Bloom filter bit positions and visa versa. - * - *

The functions view an array of longs as a collection of bit maps each containing 64 bits. The bits are arranged - * in memory as a little-endian long value. This matches the requirements of the BitMapProducer interface.

- * - * @since 4.5 - */ -public class BitMap { - /** A bit shift to apply to an integer to divided by 64 (2^6). */ - private static final int DIVIDE_BY_64 = 6; - - /** Do not instantiate. */ - private BitMap() { - } - - /** - * Calculates the number of bit maps (longs) required for the numberOfBits parameter. - * - *

If the input is negative the behavior is not defined.

- * - * @param numberOfBits the number of bits to store in the array of bit maps. - * @return the number of bit maps necessary. - */ - public static int numberOfBitMaps(final int numberOfBits) { - return (numberOfBits - 1 >> DIVIDE_BY_64) + 1; - } - - /** - * Checks if the specified index bit is enabled in the array of bit maps. - * - * If the bit specified by bitIndex is not in the bit map false is returned. - * - * @param bitMaps The array of bit maps. - * @param bitIndex the index of the bit to locate. - * @return {@code true} if the bit is enabled, {@code false} otherwise. - * @throws IndexOutOfBoundsException if bitIndex specifies a bit not in the range being tracked. - */ - public static boolean contains(final long[] bitMaps, final int bitIndex) { - return (bitMaps[getLongIndex(bitIndex)] & getLongBit(bitIndex)) != 0; - } - - /** - * Sets the bit in the bit maps. - *

Does not perform range checking

- * - * @param bitMaps The array of bit maps. - * @param bitIndex the index of the bit to set. - * @throws IndexOutOfBoundsException if bitIndex specifies a bit not in the range being tracked. - */ - public static void set(final long[] bitMaps, final int bitIndex) { - bitMaps[getLongIndex(bitIndex)] |= getLongBit(bitIndex); - } - - /** - * Gets the filter index for the specified bit index assuming the filter is using 64-bit longs - * to store bits starting at index 0. - * - *

The index is assumed to be positive. For a positive index the result will match - * {@code bitIndex / 64}.

- * - *

The divide is performed using bit shifts. If the input is negative the behavior - * is not defined.

- * - * @param bitIndex the bit index (assumed to be positive) - * @return the index of the bit map in an array of bit maps. - */ - public static int getLongIndex(final int bitIndex) { - // An integer divide by 64 is equivalent to a shift of 6 bits if the integer is - // positive. - // We do not explicitly check for a negative here. Instead we use a - // signed shift. Any negative index will produce a negative value - // by sign-extension and if used as an index into an array it will throw an - // exception. - return bitIndex >> DIVIDE_BY_64; - } - - /** - * Gets the filter bit mask for the specified bit index assuming the filter is using 64-bit - * longs to store bits starting at index 0. The returned value is a {@code long} with only - * 1 bit set. - * - *

The index is assumed to be positive. For a positive index the result will match - * {@code 1L << (bitIndex % 64)}.

- * - *

If the input is negative the behavior is not defined.

- * - * @param bitIndex the bit index (assumed to be positive) - * @return the filter bit - */ - public static long getLongBit(final int bitIndex) { - // Bit shifts only use the first 6 bits. Thus it is not necessary to mask this - // using 0x3f (63) or compute bitIndex % 64. - // Note: If the index is negative the shift will be (64 - (bitIndex & 0x3f)) and - // this will identify an incorrect bit. - return 1L << bitIndex; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/BitMapProducer.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/BitMapProducer.java deleted file mode 100644 index 1a035d0ba5..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/BitMapProducer.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.Arrays; -import java.util.Objects; -import java.util.function.LongPredicate; - -/** - * Produces bit map longs for a Bloom filter. - * - * Each bit map is a little-endian long value representing a block of bits of in a filter. - * - *

The returned array will have length {@code ceil(m / 64)} where {@code m} is the - * number of bits in the filter and {@code ceil} is the ceiling function. - * Bits 0-63 are in the first long. A value of 1 at a bit position indicates the bit - * index is enabled. - *

- * The default implementations of the {@code makePredicate()} and {@code asBitMapArray} methods - * are slow and should be reimplemented in the implementing classes where possible.

- * - * @since 4.5 - */ -@FunctionalInterface -public interface BitMapProducer { - - /** - * Each bit map is passed to the predicate in order. The predicate is applied to each - * bit map value, if the predicate returns {@code false} the execution is stopped, {@code false} - * is returned, and no further bit maps are processed. - * - *

If the producer is empty this method will return true.

- * - *

Any exceptions thrown by the action are relayed to the caller.

- * - * @param predicate the function to execute - * @return {@code true} if all bit maps returned {@code true}, {@code false} otherwise. - * @throws NullPointerException if the specified consumer is null - */ - boolean forEachBitMap(LongPredicate predicate); - - /** - * Applies the {@code func} to each bit map pair in order. Will apply all of the bit maps from the other - * BitMapProducer to this producer. If this producer does not have as many bit maps it will provide 0 (zero) - * for all excess calls to the LongBiPredicate. - *

- * The default implementation of this method uses {@code asBitMapArray()}. It is recommended that implementations - * of BitMapProducer that have local arrays reimplement this method.

- * - * @param other The other BitMapProducer that provides the y values in the (x,y) pair. - * @param func The function to apply. - * @return A LongPredicate that tests this BitMapProducers bitmap values in order. - */ - default boolean forEachBitMapPair(final BitMapProducer other, final LongBiPredicate func) { - final CountingLongPredicate p = new CountingLongPredicate(asBitMapArray(), func); - return other.forEachBitMap(p) && p.forEachRemaining(); - } - - /** - * Return a copy of the BitMapProducer data as a bit map array. - *

- * The default implementation of this method is slow. It is recommended - * that implementing classes reimplement this method. - *

- * @return An array of bit map data. - */ - default long[] asBitMapArray() { - class Bits { - private long[] data = new long[16]; - private int size; - - boolean add(final long bits) { - if (size == data.length) { - // This will throw an out-of-memory error if there are too many bits. - // Since bits are addressed using 32-bit signed integer indices - // the maximum length should be ~2^31 / 2^6 = ~2^25. - // Any more is a broken implementation. - data = Arrays.copyOf(data, size * 2); - } - data[size++] = bits; - return true; - } - - long[] toArray() { - // Edge case to avoid a large array copy - return size == data.length ? data : Arrays.copyOf(data, size); - } - } - final Bits bits = new Bits(); - forEachBitMap(bits::add); - return bits.toArray(); - } - - /** - * Creates a BitMapProducer from an array of Long. - * @param bitMaps the bit maps to return. - * @return a BitMapProducer. - */ - static BitMapProducer fromBitMapArray(final long... bitMaps) { - return new BitMapProducer() { - @Override - public boolean forEachBitMap(final LongPredicate predicate) { - for (final long word : bitMaps) { - if (!predicate.test(word)) { - return false; - } - } - return true; - } - - @Override - public long[] asBitMapArray() { - return Arrays.copyOf(bitMaps, bitMaps.length); - } - - @Override - public boolean forEachBitMapPair(final BitMapProducer other, final LongBiPredicate func) { - final CountingLongPredicate p = new CountingLongPredicate(bitMaps, func); - return other.forEachBitMap(p) && p.forEachRemaining(); - } - }; - } - - /** - * Creates a BitMapProducer from an IndexProducer. - * @param producer the IndexProducer that specifies the indexes of the bits to enable. - * @param numberOfBits the number of bits in the Bloom filter. - * @return A BitMapProducer that produces the bit maps equivalent of the Indices from the producer. - */ - static BitMapProducer fromIndexProducer(final IndexProducer producer, final int numberOfBits) { - Objects.requireNonNull(producer, "producer"); - Objects.requireNonNull(numberOfBits, "numberOfBits"); - - final long[] result = new long[BitMap.numberOfBitMaps(numberOfBits)]; - producer.forEachIndex(i -> { - BitMap.set(result, i); - return true; - }); - return fromBitMapArray(result); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/BloomFilter.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/BloomFilter.java deleted file mode 100644 index fa2330e123..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/BloomFilter.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.Objects; - -/** - * The interface that describes a Bloom filter. - *

- * See implementation notes for BitMapProducer and IndexProducer. - *

- * @see BitMapProducer - * @see IndexProducer - * @since 4.5 - */ -public interface BloomFilter extends IndexProducer, BitMapProducer { - - /** - * The sparse characteristic used to determine the best method for matching. - *

For `sparse` implementations - * the {@code forEachIndex(IntConsumer consumer)} method is more efficient. For non `sparse` implementations - * the {@code forEachBitMap(LongConsumer consumer)} is more efficient. Implementers should determine if it is easier - * for the implementation to produce indexes of bit map blocks.

- */ - int SPARSE = 0x1; - - /** - * Creates a new instance of the BloomFilter with the same properties as the current one. - * @return a copy of this BloomFilter - */ - BloomFilter copy(); - - // Query Operations - - /** - * Returns the characteristics of the filter. - *

- * Characteristics are defined as bits within the characteristics integer. - * @return the characteristics for this bloom filter. - */ - int characteristics(); - - /** - * Gets the shape that was used when the filter was built. - * @return The shape the filter was built with. - */ - Shape getShape(); - - /** - * Resets the filter to its initial, unpopulated state. - */ - void clear(); - - /** - * Returns {@code true} if this filter contains the specified filter. - * - *

Specifically this - * returns {@code true} if this filter is enabled for all bits that are enabled in the - * {@code other} filter. Using the bit representations this is - * effectively {@code (this AND other) == other}.

- * - * @param other the other Bloom filter - * @return true if all enabled bits in the other filter are enabled in this filter. - */ - default boolean contains(final BloomFilter other) { - Objects.requireNonNull(other, "other"); - return (characteristics() & SPARSE) != 0 ? contains((IndexProducer) other) : contains((BitMapProducer) other); - } - - /** - * Returns {@code true} if this filter contains the bits specified in the hasher. - * - *

Specifically this returns {@code true} if this filter is enabled for all bit indexes - * identified by the {@code hasher}. Using the bit map representations this is - * effectively {@code (this AND hasher) == hasher}.

- * - * @param hasher the hasher to provide the indexes - * @return true if this filter is enabled for all bits specified by the hasher - */ - default boolean contains(final Hasher hasher) { - Objects.requireNonNull(hasher, "Hasher"); - final Shape shape = getShape(); - return contains(hasher.indices(shape)); - } - - /** - * Returns {@code true} if this filter contains the indices specified IndexProducer. - * - *

Specifically this returns {@code true} if this filter is enabled for all bit indexes - * identified by the {@code IndexProducer}.

- * - * @param indexProducer the IndexProducer to provide the indexes - * @return {@code true} if this filter is enabled for all bits specified by the IndexProducer - */ - boolean contains(IndexProducer indexProducer); - - /** - * Returns {@code true} if this filter contains the bits specified in the bit maps produced by the - * bitMapProducer. - * - * @param bitMapProducer the the {@code BitMapProducer} to provide the bit maps. - * @return {@code true} if this filter is enabled for all bits specified by the bit maps - */ - default boolean contains(final BitMapProducer bitMapProducer) { - return forEachBitMapPair(bitMapProducer, (x, y) -> (x & y) == y); - } - - // update operations - - /** - * Merges the specified Bloom filter into this Bloom filter. - * - *

Specifically all - * bit indexes that are identified by the {@code other} will be enabled in this filter.

- * - *

Note: This method should return {@code true} even if no additional bit indexes were - * enabled. A {@code false} result indicates that this filter may or may not contain - * the {@code other} Bloom filter. This state may occur in complex Bloom filter implementations like - * counting Bloom filters.

- * - * @param other The bloom filter to merge into this one. - * @return true if the merge was successful - */ - default boolean merge(final BloomFilter other) { - return (characteristics() & SPARSE) != 0 ? merge((IndexProducer) other) : merge((BitMapProducer) other); - } - - /** - * Merges the specified hasher into this Bloom filter. Specifically all - * bit indexes that are identified by the {@code hasher} will be enabled in this filter. - * - *

Note: This method should return {@code true} even if no additional bit indexes were - * enabled. A {@code false} result indicates that this filter may or may not contain - * the {@code hasher} values. This state may occur in complex Bloom filter implementations like - * counting Bloom filters.

- * - * @param hasher The hasher to merge. - * @return true if the merge was successful - */ - default boolean merge(final Hasher hasher) { - Objects.requireNonNull(hasher, "hasher"); - return merge(hasher.indices(getShape())); - } - - /** - * Merges the specified IndexProducer into this Bloom filter. Specifically all - * bit indexes that are identified by the {@code producer} will be enabled in this filter. - * - *

Note: This method should return {@code true} even if no additional bit indexes were - * enabled. A {@code false} result indicates that this filter may or may not contain all the indexes of - * the {@code producer}. This state may occur in complex Bloom filter implementations like - * counting Bloom filters.

- * - * @param indexProducer The IndexProducer to merge. - * @return true if the merge was successful - * @throws IllegalArgumentException if producer sends illegal value. - */ - boolean merge(IndexProducer indexProducer); - - /** - * Merges the specified hasher into this Bloom filter. Specifically all - * bit indexes that are identified by the {@code producer} will be enabled in this filter. - * - *

Note: This method should return {@code true} even if no additional bit indexes were - * enabled. A {@code false} result indicates that this filter may or may not contain all the indexes - * enabled in the {@code producer}. This state may occur in complex Bloom filter implementations like - * counting Bloom filters.

- * - * @param bitMapProducer The producer to merge. - * @return true if the merge was successful - * @throws IllegalArgumentException if producer sends illegal value. - */ - boolean merge(BitMapProducer bitMapProducer); - - // Counting Operations - - /** - * Determines if the bloom filter is "full". - * - *

Full is defined as having no unset bits.

- * - * @return {@code true} if the filter is full, {@code false} otherwise. - */ - default boolean isFull() { - return cardinality() == getShape().getNumberOfBits(); - } - - /** - * Gets the cardinality (number of enabled bits) of this Bloom filter. - * - *

This is also known as the Hamming value or Hamming number.

- * - * @return the cardinality of this filter - */ - int cardinality(); - - /** - * Estimates the number of items in the Bloom filter. - * - *

By default this is the rounding of the {@code Shape.estimateN(cardinality)} calculation for the - * shape and cardinality of this filter.

- * - *

This produces an estimate roughly equivalent to the number of Hashers that have been merged into the filter.

- * - * @return an estimate of the number of items in the bloom filter. - * @see Shape#estimateN(int) - */ - default int estimateN() { - return (int) Math.round(getShape().estimateN(cardinality())); - } - - /** - * Estimates the number of items in the union of this Bloom filter with the other bloom filter. - * - *

By default this is the {@code estimateN()} of the merging of this filter with the {@code other} filter.

- * - *

This produces an estimate roughly equivalent to the number of unique Hashers that have been merged into either - * of the filters.

- * - * @param other The other Bloom filter - * @return an estimate of the number of items in the union. - * @see #estimateN() - */ - default int estimateUnion(final BloomFilter other) { - Objects.requireNonNull(other, "other"); - final BloomFilter cpy = this.copy(); - cpy.merge(other); - return cpy.estimateN(); - } - - /** - * Estimates the number of items in the intersection of this Bloom filter with the other bloom filter. - * - *

By default this is the {@code estimateN() + other.estimateN() - estimateUnion(other)}

- * - *

This produces estimate is roughly equivalent to the number of unique Hashers that have been merged into both - * of the filters.

- * - * @param other The other Bloom filter - * @return an estimate of the number of items in the intersection. - */ - default int estimateIntersection(final BloomFilter other) { - Objects.requireNonNull(other, "other"); - return estimateN() + other.estimateN() - estimateUnion(other); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/CountingBloomFilter.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/CountingBloomFilter.java deleted file mode 100644 index 5c9540d74b..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/CountingBloomFilter.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.Objects; - -/** - * The interface that describes a Bloom filter that associates a count with each - * bit index to allow reversal of merge operations with remove operations. - * - *

A counting Bloom filter is expected to function identically to a standard - * Bloom filter that is the merge of all the Bloom filters that have been added - * to and not later subtracted from the counting Bloom filter. The functional - * state of a CountingBloomFilter at the start and end of a series of merge and - * subsequent remove operations of the same Bloom filters, irrespective of - * remove order, is expected to be the same.

- * - *

Removal of a filter that has not previously been merged results in an - * invalid state where the counts no longer represent a sum of merged Bloom - * filters. It is impossible to validate merge and remove exactly without - * explicitly storing all filters. Consequently such an operation may go - * undetected. The CountingBloomFilter maintains a state flag that is used as a - * warning that an operation was performed that resulted in invalid counts and - * thus an invalid state. For example this may occur if a count for an index was - * set to negative following a remove operation.

- * - *

Implementations should document the expected state of the filter after an - * operation that generates invalid counts, and any potential recovery options. - * An implementation may support a reversal of the operation to restore the - * state to that prior to the operation. In the event that invalid counts are - * adjusted to a valid range then it should be documented if there has been - * irreversible information loss.

- * - *

Implementations may choose to throw an exception during an operation that - * generates invalid counts. Implementations should document the expected state - * of the filter after such an operation. For example are the counts not updated, - * partially updated or updated entirely before the exception is raised.

- * - * @since 4.5 - */ -public interface CountingBloomFilter extends BloomFilter, BitCountProducer { - - // Query Operations - - /** - * Returns {@code true} if the internal state is valid. - * - *

This flag is a warning that an addition or - * subtraction of counts from this filter resulted in an invalid count for one or more - * indexes. For example this may occur if a count for an index was - * set to negative following a subtraction operation, or overflows an {@code int} following an - * addition operation.

- * - *

A counting Bloom filter that has an invalid state is no longer ensured to function - * identically to a standard Bloom filter instance that is the merge of all the Bloom filters - * that have been added to and not later subtracted from this counting Bloom filter.

- * - *

Note: The change to an invalid state may or may not be reversible. Implementations - * are expected to document their policy on recovery from an addition or removal operation - * that generated an invalid state.

- * - * @return {@code true} if the state is valid - */ - boolean isValid(); - - // Modification Operations - - /** - * Merges the specified Bloom filter into this Bloom filter. - * - *

Specifically: all counts for the indexes identified by the {@code other} filter will be incremented by 1.

- * - *

Note: If the other filter is a counting Bloom filter the index counts are ignored and it is treated as an - * IndexProducer.

- * - *

This method will return {@code true} if the filter is valid after the operation.

- * - * @param other the other Bloom filter - * @return {@code true} if the removal was successful and the state is valid - * @see #isValid() - * @see #add(BitCountProducer) - */ - @Override - default boolean merge(final BloomFilter other) { - Objects.requireNonNull(other, "other"); - return merge((IndexProducer) other); - } - - /** - * Merges the specified Hasher into this Bloom filter. - * - *

Specifically: all counts for the unique indexes identified by the {@code hasher} will be incremented by 1.

- * - *

This method will return {@code true} if the filter is valid after the operation.

- * - * @param hasher the hasher - * @return {@code true} if the removal was successful and the state is valid - * @see #isValid() - * @see #add(BitCountProducer) - */ - @Override - default boolean merge(final Hasher hasher) { - Objects.requireNonNull(hasher, "hasher"); - return merge(hasher.uniqueIndices(getShape())); - } - - /** - * Merges the specified index producer into this Bloom filter. - * - *

Specifically: all counts for the indexes identified by the {@code indexProducer} will be incremented by 1.

- * - *

This method will return {@code true} if the filter is valid after the operation.

- * - *

Note: Indices that are returned multiple times will be incremented multiple times.

- * - * @param indexProducer the IndexProducer - * @return {@code true} if the removal was successful and the state is valid - * @see #isValid() - * @see #add(BitCountProducer) - */ - @Override - default boolean merge(final IndexProducer indexProducer) { - Objects.requireNonNull(indexProducer, "indexProducer"); - try { - return add(BitCountProducer.from(indexProducer)); - } catch (final IndexOutOfBoundsException e) { - throw new IllegalArgumentException( - String.format("Filter only accepts values in the [0,%d) range", getShape().getNumberOfBits()), e); - } - } - - /** - * Merges the specified BitMap producer into this Bloom filter. - * - *

Specifically: all counts for the indexes identified by the {@code bitMapProducer} will be incremented by 1.

- * - *

This method will return {@code true} if the filter is valid after the operation.

- * - * @param bitMapProducer the BitMapProducer - * @return {@code true} if the removal was successful and the state is valid - * @see #isValid() - * @see #add(BitCountProducer) - */ - @Override - default boolean merge(final BitMapProducer bitMapProducer) { - Objects.requireNonNull(bitMapProducer, "bitMapProducer"); - return merge(IndexProducer.fromBitMapProducer(bitMapProducer)); - } - - /** - * Removes the specified Bloom filter from this Bloom filter. - * - *

Specifically: all counts for the indexes identified by the {@code other} filter will be decremented by 1.

- * - *

Note: If the other filter is a counting Bloom filter the index counts are ignored and it is treated as an - * IndexProducer.

- * - *

This method will return {@code true} if the filter is valid after the operation.

- * - * @param other the other Bloom filter - * @return {@code true} if the removal was successful and the state is valid - * @see #isValid() - * @see #subtract(BitCountProducer) - */ - default boolean remove(final BloomFilter other) { - Objects.requireNonNull(other, "other"); - return remove((IndexProducer) other); - } - - /** - * Removes the unique values from the specified hasher from this Bloom filter. - * - *

Specifically all counts for the unique indices produced by the {@code hasher} will be - * decremented by 1.

- * - *

This method will return {@code true} if the filter is valid after the operation.

- * - * @param hasher the hasher to provide the indexes - * @return {@code true} if the removal was successful and the state is valid - * @see #isValid() - * @see #subtract(BitCountProducer) - */ - default boolean remove(final Hasher hasher) { - Objects.requireNonNull(hasher, "hasher"); - return remove(hasher.uniqueIndices(getShape())); - } - - /** - * Removes the values from the specified IndexProducer from the Bloom filter from this Bloom filter. - * - *

Specifically all counts for the unique indices produced by the {@code hasher} will be - * decremented by 1.

- * - *

This method will return {@code true} if the filter is valid after the operation.

- * - *

Node: This method expects index producers that produce unique values.

- * - * @param indexProducer the IndexProducer to provide the indexes - * @return {@code true} if the removal was successful and the state is valid - * @see #isValid() - * @see #subtract(BitCountProducer) - */ - default boolean remove(final IndexProducer indexProducer) { - Objects.requireNonNull(indexProducer, "indexProducer"); - try { - return subtract(BitCountProducer.from(indexProducer)); - } catch (final IndexOutOfBoundsException e) { - throw new IllegalArgumentException( - String.format("Filter only accepts values in the [0,%d) range", getShape().getNumberOfBits())); - } - } - - /** - * Removes the specified BitMapProducer from this Bloom filter. - * - *

Specifically all counts for the indices produced by the {@code bitMapProducer} will be - * decremented by 1.

- * - *

This method will return {@code true} if the filter is valid after the operation.

- * - * @param bitMapProducer the BitMapProducer to provide the indexes - * @return {@code true} if the removal was successful and the state is valid - * @see #isValid() - * @see #subtract(BitCountProducer) - */ - default boolean remove(final BitMapProducer bitMapProducer) { - Objects.requireNonNull(bitMapProducer, "bitMapProducer"); - return remove(IndexProducer.fromBitMapProducer(bitMapProducer)); - } - - /** - * Adds the specified BitCountProducer to this Bloom filter. - * - *

Specifically - * all counts for the indexes identified by the {@code other} will be incremented - * by their corresponding values in the {@code other}.

- * - *

This method will return {@code true} if the filter is valid after the operation.

- * - * @param other the BitCountProducer to add. - * @return {@code true} if the addition was successful and the state is valid - * @see #isValid() - * @see #subtract(BitCountProducer) - */ - boolean add(BitCountProducer other); - - /** - * Adds the specified BitCountProducer to this Bloom filter. - * - *

Specifically - * all counts for the indexes identified by the {@code other} will be decremented - * by their corresponding values in the {@code other}.

- * - *

This method will return true if the filter is valid after the operation.

- * - * @param other the BitCountProducer to subtract. - * @return {@code true} if the subtraction was successful and the state is valid - * @see #isValid() - * @see #add(BitCountProducer) - */ - boolean subtract(BitCountProducer other); - - - /** - * Creates a new instance of the CountingBloomFilter with the same properties as the current one. - * @return a copy of this CountingBloomFilter - */ - @Override - CountingBloomFilter copy(); -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/CountingLongPredicate.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/CountingLongPredicate.java deleted file mode 100644 index c0533a17fb..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/CountingLongPredicate.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.function.LongPredicate; - -/** - * A long predicate that applies the test func to each member of the @{code ary} in sequence for each call to @{code test()}. - * if the @{code ary} is exhausted, the subsequent calls to @{code test} are executed with a zero value. - * If the calls to @{code test} do not exhaust the @{code ary} the @{code forEachRemaining} method can be called to - * execute the @code{text} with a zero value for each remaining @{code idx} value. - * - */ -class CountingLongPredicate implements LongPredicate { - private int idx = 0; - private final long[] ary; - private final LongBiPredicate func; - - /** - * Constructs an instance that will compare the elements in @{code ary} with the elements returned by @{code func}. - * function is called as @{code func.test( idxValue, otherValue )}. If there are more @{code otherValue} values than - * @{code idxValues} then @{code func} is called as @{code func.test( 0, otherValue )}. - * @param ary The array of long values to compare. - * @param func The function to apply to the pairs of long values. - */ - CountingLongPredicate(final long[] ary, final LongBiPredicate func) { - this.ary = ary; - this.func = func; - } - - @Override - public boolean test(final long other) { - return func.test(idx == ary.length ? 0 : ary[idx++], other); - } - - /** - * Call the long-long consuming bi-predicate for each remaining unpaired long in - * the input array. This method should be invoked after the predicate has been - * passed to {@link BitMapProducer#forEachBitMap(LongPredicate)} to consume any - * unpaired bitmaps. The second argument to the bi-predicate will be zero. - * - * @return true if all calls the predicate were successful - */ - boolean forEachRemaining() { - // uses local references for optimization benefit. - int i = idx; - final long[] a = ary; - final int limit = a.length; - while (i != limit && func.test(a[i], 0)) { - i++; - } - return i == limit; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/EnhancedDoubleHasher.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/EnhancedDoubleHasher.java deleted file mode 100644 index 927c08989c..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/EnhancedDoubleHasher.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.Objects; -import java.util.function.IntPredicate; - -/** - * A Hasher that implements combinatorial hashing as as described by - * Krisch and Mitzenmacher using the enhanced double hashing technique - * described in the wikipedia article Double Hashing. - *

- * Common use for this hasher is to generate bit indices from a byte array output of a hashing - * or MessageDigest algorithm.

- * - *

Thoughts on the hasher input

- * - *

Note that it is worse to create smaller numbers for the {@code initial} and {@code increment}. If the {@code initial} is smaller than - * the number of bits in a filter then hashing will start at the same point when the size increases; likewise the {@code increment} will be - * the same if it remains smaller than the number of bits in the filter and so the first few indices will be the same if the number of bits - * changes (but is still larger than the {@code increment}). In a worse case scenario with small {@code initial} and {@code increment} for - * all items, hashing may not create indices that fill the full region within a much larger filter. Imagine hashers created with {@code initial} - * and {@code increment} values less than 255 with a filter size of 30000 and number of hash functions as 5. Ignoring the - * tetrahedral addition (a maximum of 20 for k=5) the max index is 255 * 4 + 255 = 1275, this covers 4.25% of the filter. This also - * ignores the negative wrapping but the behavior is the same, some bits cannot be reached. - *

- * So this needs to be avoided as the filter probability assumptions will be void. If the {@code initial} and {@code increment} are larger - * than the number of bits then the modulus will create a 'random' position and increment within the size. - *

- * - * @since 4.5 - */ -public class EnhancedDoubleHasher implements Hasher { - - /** - * The initial hash value. - */ - private final long initial; - - /** - * The value to increment the hash value by. - */ - private final long increment; - - /** - * Convert bytes to big-endian long filling with zero bytes as necessary.. - * @param byteArray the byte array to extract the values from. - * @param offset the offset to start extraction from. - * @param len the length of the extraction, may be longer than 8. - * @return - */ - private static long toLong(final byte[] byteArray, final int offset, final int len) { - long val = 0; - int shift = Long.SIZE; - final int end = offset + Math.min(len, Long.BYTES); - for (int i = offset; i < end; i++) { - shift -= Byte.SIZE; - val |= (long) (byteArray[i] & 0xFF) << shift; - } - return val; - } - - /** - * Constructs the EnhancedDoubleHasher from a byte array. - *

- * This method simplifies the conversion from a Digest or hasher algorithm output - * to the two values used by the EnhancedDoubleHasher.

- *

The byte array is split in 2 and the first 8 bytes of each half are interpreted as a big-endian long value. - * Excess bytes are ignored. - * If there are fewer than 16 bytes the following conversions are made. - *

- *
    - *
  1. If there is an odd number of bytes the excess byte is assigned to the increment value
  2. - *
  3. The bytes alloted are read in big-endian order any byte not populated is set to zero.
  4. - *
- *

- * This ensures that small arrays generate the largest possible increment and initial values. - *

- * @param buffer the buffer to extract the longs from. - * @throws IllegalArgumentException is buffer length is zero. - */ - public EnhancedDoubleHasher(final byte[] buffer) { - if (buffer.length == 0) { - throw new IllegalArgumentException("buffer length must be greater than 0"); - } - // divide by 2 - final int segment = buffer.length / 2; - this.initial = toLong(buffer, 0, segment); - this.increment = toLong(buffer, segment, buffer.length - segment); - } - - /** - * Constructs the EnhancedDoubleHasher from 2 longs. The long values will be interpreted as unsigned values. - * @param initial The initial value for the hasher. - * @param increment The value to increment the hash by on each iteration. - */ - public EnhancedDoubleHasher(final long initial, final long increment) { - this.initial = initial; - this.increment = increment; - } - - /** - * Gets the initial value for the hash calculation. - * @return the initial value for the hash calculation. - */ - long getInitial() { - return initial; - } - - /** - * Gets the increment value for the hash calculation. - * @return the increment value for the hash calculation. - */ - long getIncrement() { - return increment; - } - - /** - * Performs a modulus calculation on an unsigned long and an integer divisor. - * @param dividend a unsigned long value to calculate the modulus of. - * @param divisor the divisor for the modulus calculation. - * @return the remainder or modulus value. - */ - static int mod(final long dividend, final int divisor) { - // See Hacker's Delight (2nd ed), section 9.3. - // Assume divisor is positive. - // Divide half the unsigned number and then double the quotient result. - final long quotient = (dividend >>> 1) / divisor << 1; - final long remainder = dividend - quotient * divisor; - // remainder in [0, 2 * divisor) - return (int) (remainder >= divisor ? remainder - divisor : remainder); - } - - @Override - public IndexProducer indices(final Shape shape) { - Objects.requireNonNull(shape, "shape"); - - return new IndexProducer() { - - @Override - public boolean forEachIndex(final IntPredicate consumer) { - Objects.requireNonNull(consumer, "consumer"); - final int bits = shape.getNumberOfBits(); - // Enhanced double hashing: - // hash[i] = ( h1(x) + i*h2(x) + (i*i*i - i)/6 ) mod bits - // See: https://en.wikipedia.org/wiki/Double_hashing#Enhanced_double_hashing - // - // Essentially this is computing a wrapped modulus from a start point and an - // increment and an additional term as a tetrahedral number. - // You only need two modulus operations before the loop. Within the loop - // the modulus is handled using the sign bit to detect wrapping to ensure: - // 0 <= index < bits - // 0 <= inc < bits - // The final hash is: - // hash[i] = ( h1(x) - i*h2(x) - (i*i*i - i)/6 ) wrapped in [0, bits) - - int index = mod(initial, bits); - int inc = mod(increment, bits); - - final int k = shape.getNumberOfHashFunctions(); - if (k > bits) { - for (int j = k; j > 0;) { - // handle k > bits - final int block = Math.min(j, bits); - j -= block; - for (int i = 0; i < block; i++) { - if (!consumer.test(index)) { - return false; - } - // Update index and handle wrapping - index -= inc; - index = index < 0 ? index + bits : index; - - // Incorporate the counter into the increment to create a - // tetrahedral number additional term, and handle wrapping. - inc -= i; - inc = inc < 0 ? inc + bits : inc; - } - } - } else { - for (int i = 0; i < k; i++) { - if (!consumer.test(index)) { - return false; - } - // Update index and handle wrapping - index -= inc; - index = index < 0 ? index + bits : index; - - // Incorporate the counter into the increment to create a - // tetrahedral number additional term, and handle wrapping. - inc -= i; - inc = inc < 0 ? inc + bits : inc; - } - } - return true; - } - - @Override - public int[] asIndexArray() { - final int[] result = new int[shape.getNumberOfHashFunctions()]; - final int[] idx = new int[1]; - - // This method needs to return duplicate indices - - forEachIndex(i -> { - result[idx[0]++] = i; - return true; - }); - return result; - } - }; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/Hasher.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/Hasher.java deleted file mode 100644 index d678808061..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/Hasher.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.Objects; - -/** - * A Hasher creates IndexProducer based on the hash implementation and the - * provided Shape. - * - * @since 4.5 - */ -public interface Hasher { - - /** - * Creates an IndexProducer for this hasher based on the Shape. - * - *

The @{code IndexProducer} will create indices within the range defined by the number of bits in - * the shape. The total number of indices will respect the number of hash functions per item - * defined by the shape. However the count of indices may not be a multiple of the number of - * hash functions if the implementation has removed duplicates.

- * - *

This IndexProducer must be deterministic in that it must return the same indices for the - * same Shape.

- * - *

No guarantee is made as to order of indices.

- *

Duplicates indices for a single item may be produced.

- * - * @param shape the shape of the desired Bloom filter. - * @return the iterator of integers - */ - IndexProducer indices(Shape shape); - - /** - * Creates an IndexProducer of unique indices for this hasher based on the Shape. - * - *

This is like the `indices(Shape)` method except that it adds the guarantee that no - * duplicate values will be returned. The indices produced are equivalent to those returned - * from by a Bloom filter created from this hasher.

- * - * @param shape the shape of the desired Bloom filter. - * @return the iterator of integers - */ - default IndexProducer uniqueIndices(final Shape shape) { - return consumer -> { - Objects.requireNonNull(consumer, "consumer"); - return indices(shape).forEachIndex(IndexFilter.create(shape, consumer)); - }; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/IndexFilter.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/IndexFilter.java deleted file mode 100644 index 440ee811fe..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/IndexFilter.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.function.IntPredicate; - -/** - * A convenience class for Hasher implementations to filter out duplicate indices. - * - *

If the index is negative the behavior is not defined.

- * - *

This is conceptually a unique filter implemented as an {@code IntPredicate}.

- * @since 4.5 - */ -public final class IndexFilter { - private final IntPredicate tracker; - private final int size; - private final IntPredicate consumer; - - /** - * Creates an instance optimized for the specified shape. - * @param shape The shape that is being generated. - * @param consumer The consumer to accept the values. - * @return an IndexFilter optimized for the specified shape. - */ - public static IntPredicate create(final Shape shape, final IntPredicate consumer) { - return new IndexFilter(shape, consumer)::test; - } - - /** - * Creates an instance optimized for the specified shape. - * @param shape The shape that is being generated. - * @param consumer The consumer to accept the values. - */ - private IndexFilter(final Shape shape, final IntPredicate consumer) { - this.size = shape.getNumberOfBits(); - this.consumer = consumer; - if (BitMap.numberOfBitMaps(shape.getNumberOfBits()) * Long.BYTES < (long) shape.getNumberOfHashFunctions() - * Integer.BYTES) { - this.tracker = new BitMapTracker(shape); - } else { - this.tracker = new ArrayTracker(shape); - } - } - - /** - * Test if the number should be processed by the {@code consumer}. - * - *

If the number has not been seen before it is passed to the {@code consumer} and the result returned. - * If the number has been seen before the {@code consumer} is not called and {@code true} returned.

- * - *

If the input is not in the range [0,size) an IndexOutOfBoundsException exception is thrown.

- * - * @param number the number to check. - * @return {@code true} if processing should continue, {@code false} otherwise. - */ - public boolean test(final int number) { - if (number >= size) { - throw new IndexOutOfBoundsException(String.format("number too large %d >= %d", number, size)); - } - return !tracker.test(number) || consumer.test(number); - } - - /** - * An IndexTracker implementation that uses an array of integers to track whether or not a - * number has been seen. Suitable for Shapes that have few hash functions. - * @since 4.5 - */ - static class ArrayTracker implements IntPredicate { - private final int[] seen; - private int populated; - - /** - * Constructs the tracker based on the shape. - * @param shape the shape to build the tracker for. - */ - ArrayTracker(final Shape shape) { - seen = new int[shape.getNumberOfHashFunctions()]; - } - - @Override - public boolean test(final int number) { - if (number < 0) { - throw new IndexOutOfBoundsException("number may not be less than zero. " + number); - } - for (int i = 0; i < populated; i++) { - if (seen[i] == number) { - return false; - } - } - seen[populated++] = number; - return true; - } - } - - /** - * An IndexTracker implementation that uses an array of bit maps to track whether or not a - * number has been seen. - * @since 4.5 - */ - static class BitMapTracker implements IntPredicate { - private final long[] bits; - - /** - * Constructs a bit map based tracker for the specified shape. - * @param shape The shape that is being generated. - */ - BitMapTracker(final Shape shape) { - bits = new long[BitMap.numberOfBitMaps(shape.getNumberOfBits())]; - } - - @Override - public boolean test(final int number) { - final boolean retval = !BitMap.contains(bits, number); - BitMap.set(bits, number); - return retval; - } - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/IndexProducer.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/IndexProducer.java deleted file mode 100644 index cb132a5460..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/IndexProducer.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.BitSet; -import java.util.Objects; -import java.util.function.IntPredicate; -import java.util.function.LongPredicate; - -/** - * An object that produces indices of a Bloom filter. - *

- * The default implementation of {@code asIndexArray} is slow. Implementers should reimplement the - * method where possible.

- * - * @since 4.5 - */ -@FunctionalInterface -public interface IndexProducer { - - /** - * Each index is passed to the predicate. The predicate is applied to each - * index value, if the predicate returns {@code false} the execution is stopped, {@code false} - * is returned, and no further indices are processed. - * - *

Any exceptions thrown by the action are relayed to the caller.

- * - *

Indices ordering and uniqueness is not guaranteed.

- * - * @param predicate the action to be performed for each non-zero bit index. - * @return {@code true} if all indexes return true from consumer, {@code false} otherwise. - * @throws NullPointerException if the specified action is null - */ - boolean forEachIndex(IntPredicate predicate); - - /** - * Creates an IndexProducer from an array of integers. - * @param values the index values - * @return an IndexProducer that uses the values. - */ - static IndexProducer fromIndexArray(final int... values) { - return new IndexProducer() { - - @Override - public boolean forEachIndex(final IntPredicate predicate) { - for (final int value : values) { - if (!predicate.test(value)) { - return false; - } - } - return true; - } - - @Override - public int[] asIndexArray() { - return values.clone(); - } - }; - } - - /** - * Creates an IndexProducer from a {@code BitMapProducer}. - * @param producer the {@code BitMapProducer} - * @return a new {@code IndexProducer}. - */ - static IndexProducer fromBitMapProducer(final BitMapProducer producer) { - Objects.requireNonNull(producer, "producer"); - return consumer -> { - final LongPredicate longPredicate = new LongPredicate() { - int wordIdx = 0; - - @Override - public boolean test(long word) { - int i = wordIdx; - while (word != 0) { - if ((word & 1) == 1 && !consumer.test(i)) { - return false; - } - word >>>= 1; - i++; - } - wordIdx += 64; - return true; - } - }; - return producer.forEachBitMap(longPredicate::test); - }; - } - - /** - * Return a copy of the IndexProducer data as an int array. - * - *

Indices ordering and uniqueness is not guaranteed.

- * - *

- * The default implementation of this method is slow. It is recommended - * that implementing classes reimplement this method. - *

- * - *

- * The default implementation of this method returns unique values in order. - *

- * @return An int array of the data. - */ - default int[] asIndexArray() { - final BitSet result = new BitSet(); - forEachIndex(i -> { - result.set(i); - return true; - }); - return result.stream().toArray(); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/LongBiPredicate.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/LongBiPredicate.java deleted file mode 100644 index 8719b9f9b2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/LongBiPredicate.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -/** - * Represents a function that accepts a two long-valued argument and produces a binary result. - * This is the long-consuming primitive specialization for {@code BiPredicate}. - * - * This is a functional interface whose functional method is {@code test(long,long)}. - * - * @since 4.5 - */ -@FunctionalInterface -public interface LongBiPredicate { - - /** - * A function that takes to long arguments and returns a boolean. - * @param x the first long argument. - * @param y the second long argument. - * @return true or false. - */ - boolean test(long x, long y); -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/SetOperations.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/SetOperations.java deleted file mode 100644 index fb08451bba..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/SetOperations.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.function.LongBinaryOperator; - -/** - * Implementations of set operations on BitMapProducers. - * - * @since 4.5 - */ -public final class SetOperations { - - /** - * Calculates the cardinality of the result of a LongBinaryOperator using the - * {@code BitMapProducer.makePredicate} method. - * @param first the first BitMapProducer - * @param second the second BitMapProducer - * @param op a long binary operation on where x = {@code first} and y = {@code second} bitmap producers. - * @return the calculated cardinality. - */ - private static int cardinality(final BitMapProducer first, final BitMapProducer second, final LongBinaryOperator op) { - final int[] cardinality = new int[1]; - - first.forEachBitMapPair(second, (x, y) -> { - cardinality[0] += Long.bitCount(op.applyAsLong(x, y)); - return true; - }); - return cardinality[0]; - } - - /** - * Calculates the cardinality of a BitMapProducer. By necessity this method will visit each bit map - * created by the producer. - * @param producer the Producer to calculate the cardinality for. - * @return the cardinality of the bit maps produced by the producer. - */ - public static int cardinality(final BitMapProducer producer) { - final int[] cardinality = new int[1]; - producer.forEachBitMap(l -> { - cardinality[0] += Long.bitCount(l); - return true; - }); - return cardinality[0]; - } - - /** - * Calculates the cardinality of the logical {@code AND} of the bit maps for the two filters. - * @param first the first BitMapProducer. - * @param second the second BitMapProducer - * @return the cardinality of the {@code AND} of the filters. - */ - public static int andCardinality(final BitMapProducer first, final BitMapProducer second) { - return cardinality(first, second, (x, y) -> x & y); - } - - /** - * Calculates the cardinality of the logical {@code OR} of the bit maps for the two filters. - * @param first the first BitMapProducer. - * @param second the second BitMapProducer - * @return the cardinality of the {@code OR} of the filters. - */ - public static int orCardinality(final BitMapProducer first, final BitMapProducer second) { - return cardinality(first, second, (x, y) -> x | y); - } - - /** - * Calculates the cardinality of the logical {@code XOR} of the bit maps for the two filters. - * @param first the first BitMapProducer. - * @param second the second BitMapProducer - * @return the cardinality of the {@code XOR} of the filters. - */ - public static int xorCardinality(final BitMapProducer first, final BitMapProducer second) { - return cardinality(first, second, (x, y) -> x ^ y); - } - - /** - * Calculates the Cosine distance between two BitMapProducer. - * - *

Cosine distance is defined as {@code 1 - Cosine similarity}

- * - * @param first the first BitMapProducer. - * @param second the second BitMapProducer. - * @return the jaccard distance. - */ - public static double cosineDistance(final BitMapProducer first, final BitMapProducer second) { - return 1.0 - cosineSimilarity(first, second); - } - - /** - * Calculates the Cosine similarity between two BitMapProducers. - *

Also known as Orchini similarity and the Tucker coefficient of congruence or - * Ochiai similarity.

- * - *

If either producer is empty the result is 0 (zero)

- * - * @param first the first BitMapProducer. - * @param second the second BitMapProducer. - * @return the Cosine similarity. - */ - public static double cosineSimilarity(final BitMapProducer first, final BitMapProducer second) { - final int numerator = andCardinality(first, second); - // Given that the cardinality is an int then the product as a double will not - // overflow, we can use one sqrt: - return numerator == 0 ? 0 : numerator / Math.sqrt(cardinality(first) * cardinality(second)); - } - - /** - * Calculates the Cosine similarity between two Bloom filters. - *

Also known as Orchini similarity and the Tucker coefficient of congruence or - * Ochiai similarity.

- * - *

If either filter is empty (no enabled bits) the result is 0 (zero)

- * - *

This is a version of cosineSimilarity optimized for Bloom filters.

- * - * @param first the first Bloom filter. - * @param second the second Bloom filter. - * @return the Cosine similarity. - */ - public static double cosineSimilarity(final BloomFilter first, final BloomFilter second) { - final int numerator = andCardinality(first, second); - // Given that the cardinality is an int then the product as a double will not - // overflow, we can use one sqrt: - return numerator == 0 ? 0 : numerator / Math.sqrt(first.cardinality() * second.cardinality()); - } - - /** - * Calculates the Hamming distance between two BitMapProducers. - * - * @param first the first BitMapProducer. - * @param second the second BitMapProducer. - * @return the Hamming distance. - */ - public static int hammingDistance(final BitMapProducer first, final BitMapProducer second) { - return xorCardinality(first, second); - } - - /** - * Calculates the Jaccard distance between two BitMapProducer. - * - *

Jaccard distance is defined as {@code 1 - Jaccard similarity}

- * - * @param first the first BitMapProducer. - * @param second the second BitMapProducer. - * @return the Jaccard distance. - */ - public static double jaccardDistance(final BitMapProducer first, final BitMapProducer second) { - return 1.0 - jaccardSimilarity(first, second); - } - - /** - * Calculates the Jaccard similarity between two BitMapProducer. - * - *

Also known as Jaccard index, Intersection over Union, and Jaccard similarity coefficient

- * - * @param first the first BitMapProducer. - * @param second the second BitMapProducer. - * @return the Jaccard similarity. - */ - public static double jaccardSimilarity(final BitMapProducer first, final BitMapProducer second) { - final int[] cardinality = new int[2]; - first.forEachBitMapPair(second, (x, y) -> { - cardinality[0] += Long.bitCount(x & y); - cardinality[1] += Long.bitCount(x | y); - return true; - }); - final int intersection = cardinality[0]; - return intersection == 0 ? 0 : intersection / (double) cardinality[1]; - } - - /** - * Do not instantiate. - */ - private SetOperations() { - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/Shape.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/Shape.java deleted file mode 100644 index f67712119e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/Shape.java +++ /dev/null @@ -1,440 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -/** - * The definition of a Bloom filter shape. - * - *

This class contains the values for the filter configuration and is used to - * convert a Hasher into a BloomFilter as well as verify that two Bloom filters are - * compatible. (i.e. can be compared or merged)

- * - *

Interrelatedness of values

- * - *
- *
Number of Items ({@code n})
- *
{@code n = ceil(m / (-k / ln(1 - exp(ln(p) / k))))}
- *
Probability of False Positives ({@code p})
- *
{@code p = pow(1 - exp(-k / (m / n)), k)}
- *
Number of Bits ({@code m})
- *
{@code m = ceil((n * ln(p)) / ln(1 / pow(2, ln(2))))}
- *
Number of Functions ({@code k})
- *
{@code k = round((m / n) * ln(2))}
- *
- * - * @see Bloom Filter calculator - * @see Bloom filter - * [Wikipedia] - * @since 4.5 - */ -public final class Shape { - - /** - * The natural logarithm of 2. Used in several calculations. Approximately 0.693147180559945. - */ - private static final double LN_2 = Math.log(2.0); - - /** - * ln(1 / 2^ln(2)). Used in calculating the number of bits. Approximately -0.480453013918201. - * - *

ln(1 / 2^ln(2)) = ln(1) - ln(2^ln(2)) = -ln(2) * ln(2) - */ - private static final double DENOMINATOR = -LN_2 * LN_2; - - /** - * Number of hash functions to create a filter ({@code k}). - */ - private final int numberOfHashFunctions; - - /** - * Number of bits in the filter ({@code m}). - */ - private final int numberOfBits; - - /** - * Constructs a filter configuration with the specified number of hashFunctions ({@code k}) and - * bits ({@code m}). - * - * @param numberOfHashFunctions Number of hash functions to use for each item placed in the filter. - * @param numberOfBits The number of bits in the filter - * @throws IllegalArgumentException if {@code numberOfHashFunctions < 1} or {@code numberOfBits < 1} - */ - private Shape(final int numberOfHashFunctions, final int numberOfBits) { - this.numberOfHashFunctions = checkNumberOfHashFunctions(numberOfHashFunctions); - this.numberOfBits = checkNumberOfBits(numberOfBits); - } - - @Override - public boolean equals(final Object obj) { - // Shape is final so no check for the same class as inheritance is not possible - if (obj instanceof Shape) { - final Shape other = (Shape) obj; - return numberOfBits == other.numberOfBits && - numberOfHashFunctions == other.numberOfHashFunctions; - } - return false; - } - - @Override - public int hashCode() { - // Match Arrays.hashCode(new int[] {numberOfBits, numberOfHashFunctions}) - return (31 + numberOfBits) * 31 + numberOfHashFunctions; - } - - /** - * Gets the number of bits in the Bloom filter. - * This is also known as {@code m}. - * - * @return the number of bits in the Bloom filter ({@code m}). - */ - public int getNumberOfBits() { - return numberOfBits; - } - - /** - * Gets the number of hash functions used to construct the filter. - * This is also known as {@code k}. - * - * @return the number of hash functions used to construct the filter ({@code k}). - */ - public int getNumberOfHashFunctions() { - return numberOfHashFunctions; - } - - /** - * Calculates the probability of false positives ({@code p}) given - * numberOfItems ({@code n}), numberOfBits ({@code m}) and numberOfHashFunctions ({@code k}). - *

p = pow(1 - exp(-k / (m / n)), k)
- * - *

This is the probability that a Bloom filter will return true for the presence of an item - * when it does not contain the item.

- * - *

The probability assumes that the Bloom filter is filled with the expected number of - * items. If the filter contains fewer items then the actual probability will be lower. - * Thus, this returns the worst-case false positive probability for a filter that has not - * exceeded its expected number of items.

- * - * @param numberOfItems the number of items hashed into the Bloom filter. - * @return the probability of false positives. - */ - public double getProbability(final int numberOfItems) { - if (numberOfItems < 0) { - throw new IllegalArgumentException("Number of items must be greater than or equal to 0: " + numberOfItems); - } - if (numberOfItems == 0) { - return 0; - } - return Math.pow(-Math.expm1(-1.0 * numberOfHashFunctions * numberOfItems / numberOfBits), - numberOfHashFunctions); - } - - @Override - public String toString() { - return String.format("Shape[k=%s m=%s]", numberOfHashFunctions, numberOfBits); - } - - /** - * Determines if a cardinality is sparse based on the shape. - *

This method assumes that bit maps are 64bits and indexes are 32bits. If the memory - * necessary to store the cardinality as indexes is less than the estimated memory for bit maps, - * the cardinality is determined to be {@code sparse}.

- * @param cardinality the cardinality to check. - * @return true if the cardinality is sparse within the shape. - */ - public boolean isSparse(final int cardinality) { - /* - * Since the size of a bit map is a long and the size of an index is an int, - * there can be 2 indexes for each bit map. In Bloom filters indexes are evenly - * distributed across the range of possible values, Thus if the cardinality - * (number of indexes) is less than or equal to 2*number of bit maps the - * cardinality is sparse within the shape. - */ - return cardinality <= BitMap.numberOfBitMaps(getNumberOfBits()) * 2; - } - - /** - * Estimate the number of items in a Bloom filter with this shape and the specified number of bits enabled. - * - *

Note:

- *
    - *
  • if cardinality == numberOfBits, then result is infinity.
  • - *
  • if cardinality > numberOfBits, then result is NaN.
  • - *
- * - * @param cardinality the number of enabled bits also known as the hamming value. - * @return An estimate of the number of items in the Bloom filter. - */ - public double estimateN(final int cardinality) { - final double c = cardinality; - final double m = numberOfBits; - final double k = numberOfHashFunctions; - return -(m / k) * Math.log1p(-c / m); - } - - /** - * Constructs a filter configuration with a desired false-positive probability ({@code p}) and the - * specified number of bits ({@code m}) and hash functions ({@code k}). - * - *

The number of items ({@code n}) to be stored in the filter is computed. - *

n = ceil(m / (-k / ln(1 - exp(ln(p) / k))))
- * - *

The actual probability will be approximately equal to the - * desired probability but will be dependent upon the calculated Bloom filter capacity - * (number of items). An exception is raised if this is greater than or equal to 1 (i.e. the - * shape is invalid for use as a Bloom filter). - * - * @param probability The desired false-positive probability in the range {@code (0, 1)} - * @param numberOfBits The number of bits in the filter - * @param numberOfHashFunctions The number of hash functions in the filter - * @return a valid Shape. - * @throws IllegalArgumentException if the desired probability is not in the range {@code (0, 1)}, - * {@code numberOfBits < 1}, {@code numberOfHashFunctions < 1}, or the actual - * probability is {@code >= 1.0} - */ - public static Shape fromPMK(final double probability, final int numberOfBits, final int numberOfHashFunctions) { - checkProbability(probability); - checkNumberOfBits(numberOfBits); - checkNumberOfHashFunctions(numberOfHashFunctions); - - // Number of items (n): - // n = ceil(m / (-k / ln(1 - exp(ln(p) / k)))) - final double n = Math.ceil(numberOfBits - / (-numberOfHashFunctions / Math.log(-Math.expm1(Math.log(probability) / numberOfHashFunctions)))); - - // log of probability is always < 0 - // number of hash functions is >= 1 - // e^x where x < 0 = [0,1) - // log 1-e^x = [log1, log0) = <0 with an effective lower limit of -53 - // numberOfBits/ (-numberOfHashFunctions / [-53,0) ) >0 - // ceil( >0 ) >= 1 - // so we can not produce a negative value thus we don't check for it. - // - // similarly we can not produce a number greater than numberOfBits so we - // do not have to check for Integer.MAX_VALUE either. - - final Shape shape = new Shape(numberOfHashFunctions, numberOfBits); - // check that probability is within range - checkCalculatedProbability(shape.getProbability((int) n)); - return shape; - } - - /** - * Constructs a filter configuration with the specified number of items ({@code n}) and - * desired false-positive probability ({@code p}). - * - *

The number of bits ({@code m}) for the filter is computed. - *

m = ceil(n * ln(p) / ln(1 / 2^ln(2)))
- * - *

The optimal number of hash functions ({@code k}) is computed. - *

k = round((m / n) * ln(2))
- * - *

The actual probability will be approximately equal to the - * desired probability but will be dependent upon the calculated number of bits and hash - * functions. An exception is raised if this is greater than or equal to 1 (i.e. the - * shape is invalid for use as a Bloom filter). - * - * @param numberOfItems Number of items to be placed in the filter - * @param probability The desired false-positive probability in the range {@code (0, 1)} - * @return a valid Shape - * @throws IllegalArgumentException if {@code numberOfItems < 1}, if the desired probability - * is not in the range {@code (0, 1)} or if the actual probability is {@code >= 1.0}. - */ - public static Shape fromNP(final int numberOfItems, final double probability) { - checkNumberOfItems(numberOfItems); - checkProbability(probability); - - // Number of bits (m) - final double m = Math.ceil(numberOfItems * Math.log(probability) / DENOMINATOR); - if (m > Integer.MAX_VALUE) { - throw new IllegalArgumentException("Resulting filter has more than " + Integer.MAX_VALUE + " bits: " + m); - } - final int numberOfBits = (int) m; - - final int numberOfHashFunctions = calculateNumberOfHashFunctions(numberOfItems, numberOfBits); - final Shape shape = new Shape(numberOfHashFunctions, numberOfBits); - // check that probability is within range - checkCalculatedProbability(shape.getProbability(numberOfItems)); - return shape; - } - - /** - * Constructs a filter configuration with the specified number of hashFunctions ({@code k}) and - * bits ({@code m}). - * - * @param numberOfHashFunctions Number of hash functions to use for each item placed in the filter. - * @param numberOfBits The number of bits in the filter - * @return a valid Shape. - * @throws IllegalArgumentException if {@code numberOfHashFunctions < 1} or {@code numberOfBits < 1} - */ - public static Shape fromKM(final int numberOfHashFunctions, final int numberOfBits) { - return new Shape(numberOfHashFunctions, numberOfBits); - } - - /** - * Constructs a filter configuration with the specified number of items ({@code n}) and - * bits ({@code m}). - * - *

The optimal number of hash functions ({@code k}) is computed. - *

k = round((m / n) * ln(2))
- * - *

The false-positive probability is computed using the number of items, bits and hash - * functions. An exception is raised if this is greater than or equal to 1 (i.e. the - * shape is invalid for use as a Bloom filter). - * - * @param numberOfItems Number of items to be placed in the filter - * @param numberOfBits The number of bits in the filter - * @return a valid Shape. - * @throws IllegalArgumentException if {@code numberOfItems < 1}, {@code numberOfBits < 1}, - * the calculated number of hash function is {@code < 1}, or if the actual probability is {@code >= 1.0} - */ - public static Shape fromNM(final int numberOfItems, final int numberOfBits) { - checkNumberOfItems(numberOfItems); - checkNumberOfBits(numberOfBits); - final int numberOfHashFunctions = calculateNumberOfHashFunctions(numberOfItems, numberOfBits); - final Shape shape = new Shape(numberOfHashFunctions, numberOfBits); - // check that probability is within range - checkCalculatedProbability(shape.getProbability(numberOfItems)); - return shape; - } - - /** - * Constructs a filter configuration with the specified number of items, bits - * and hash functions. - * - *

The false-positive probability is computed using the number of items, bits and hash - * functions. An exception is raised if this is greater than or equal to 1 (i.e. the - * shape is invalid for use as a Bloom filter). - * - * @param numberOfItems Number of items to be placed in the filter - * @param numberOfBits The number of bits in the filter. - * @param numberOfHashFunctions The number of hash functions in the filter - * @return a valid Shape. - * @throws IllegalArgumentException if {@code numberOfItems < 1}, {@code numberOfBits < 1}, - * {@code numberOfHashFunctions < 1}, or if the actual probability is {@code >= 1.0}. - */ - public static Shape fromNMK(final int numberOfItems, final int numberOfBits, final int numberOfHashFunctions) { - checkNumberOfItems(numberOfItems); - checkNumberOfBits(numberOfBits); - checkNumberOfHashFunctions(numberOfHashFunctions); - // check that probability is within range - final Shape shape = new Shape(numberOfHashFunctions, numberOfBits); - // check that probability is within range - checkCalculatedProbability(shape.getProbability(numberOfItems)); - return shape; - } - - /** - * Check number of items is strictly positive. - * - * @param numberOfItems the number of items - * @return the number of items - * @throws IllegalArgumentException if the number of items is {@code < 1}. - */ - private static int checkNumberOfItems(final int numberOfItems) { - if (numberOfItems < 1) { - throw new IllegalArgumentException("Number of items must be greater than 0: " + numberOfItems); - } - return numberOfItems; - } - - /** - * Check number of bits is strictly positive. - * - * @param numberOfBits the number of bits - * @return the number of bits - * @throws IllegalArgumentException if the number of bits is {@code < 1}. - */ - private static int checkNumberOfBits(final int numberOfBits) { - if (numberOfBits < 1) { - throw new IllegalArgumentException("Number of bits must be greater than 0: " + numberOfBits); - } - return numberOfBits; - } - - /** - * Check number of hash functions is strictly positive. - * - * @param numberOfHashFunctions the number of hash functions - * @return the number of hash functions - * @throws IllegalArgumentException if the number of hash functions is {@code < 1}. - */ - private static int checkNumberOfHashFunctions(final int numberOfHashFunctions) { - if (numberOfHashFunctions < 1) { - throw new IllegalArgumentException( - "Number of hash functions must be greater than 0: " + numberOfHashFunctions); - } - return numberOfHashFunctions; - } - - /** - * Check the probability is in the range 0.0, exclusive, to 1.0, exclusive. - * - * @param probability the probability - * @throws IllegalArgumentException if the probability is not in the range {@code (0, 1)} - */ - private static void checkProbability(final double probability) { - // Using the negation of within the desired range will catch NaN - if (!(probability > 0.0 && probability < 1.0)) { - throw new IllegalArgumentException("Probability must be greater than 0 and less than 1: " + probability); - } - } - - /** - * Check the calculated probability is {@code < 1.0}. - * - *

This function is used to verify that the dynamically calculated probability for the - * Shape is in the valid range 0 to 1 exclusive. This need only be performed once upon - * construction. - * - * @param probability the probability - * @throws IllegalArgumentException if the probability is {@code >= 1.0}. - */ - private static void checkCalculatedProbability(final double probability) { - // We do not need to check for p <= 0.0 since we only allow positive values for - // parameters and the closest we can come to exp(-kn/m) == 1 is - // exp(-1/Integer.MAX_INT) approx 0.9999999995343387 so Math.pow( x, y ) will - // always be 00 - if (probability >= 1.0) { - throw new IllegalArgumentException( - String.format("Calculated probability is greater than or equal to 1: " + probability)); - } - } - - /** - * Calculates the number of hash functions given numberOfItems and numberOfBits. - * This is a method so that the calculation is consistent across all constructors. - * - * @param numberOfItems the number of items in the filter. - * @param numberOfBits the number of bits in the filter. - * @return the optimal number of hash functions. - * @throws IllegalArgumentException if the calculated number of hash function is {@code < 1} - */ - private static int calculateNumberOfHashFunctions(final int numberOfItems, final int numberOfBits) { - // k = round((m / n) * ln(2)) We change order so that we use real math rather - // than integer math. - final long k = Math.round(LN_2 * numberOfBits / numberOfItems); - if (k < 1) { - throw new IllegalArgumentException( - String.format("Filter too small: Calculated number of hash functions (%s) was less than 1", k)); - } - // Normally we would check that numberOfHashFunctions <= Integer.MAX_VALUE but - // since numberOfBits is at most Integer.MAX_VALUE the numerator of - // numberOfHashFunctions is ln(2) * Integer.MAX_VALUE = 646456992.9449 the - // value of k can not be above Integer.MAX_VALUE. - return (int) k; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/SimpleBloomFilter.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/SimpleBloomFilter.java deleted file mode 100644 index 2145f2fefb..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/SimpleBloomFilter.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.Arrays; -import java.util.Objects; -import java.util.function.IntPredicate; -import java.util.function.LongPredicate; - -/** - * A bloom filter using an array of bit maps to track enabled bits. This is a standard - * implementation and should work well for most Bloom filters. - * @since 4.5 - */ -public final class SimpleBloomFilter implements BloomFilter { - - /** - * The array of bit map longs that defines this Bloom filter. Will be null if the filter is empty. - */ - private final long[] bitMap; - - /** - * The Shape of this Bloom filter. - */ - private final Shape shape; - - /** - * The cardinality of this Bloom filter. - */ - private int cardinality; - - /** - * Creates an empty instance. - * - * @param shape The shape for the filter. - */ - public SimpleBloomFilter(final Shape shape) { - Objects.requireNonNull(shape, "shape"); - this.shape = shape; - this.bitMap = new long[BitMap.numberOfBitMaps(shape.getNumberOfBits())]; - this.cardinality = 0; - } - - /** - * Copy constructor for {@code copy()} use. - * @param source - */ - private SimpleBloomFilter(final SimpleBloomFilter source) { - this.shape = source.shape; - this.bitMap = source.bitMap.clone(); - this.cardinality = source.cardinality; - } - - @Override - public void clear() { - Arrays.fill(bitMap, 0L); - cardinality = 0; - } - - @Override - public long[] asBitMapArray() { - return Arrays.copyOf(bitMap, bitMap.length); - } - - @Override - public boolean forEachBitMapPair(final BitMapProducer other, final LongBiPredicate func) { - final CountingLongPredicate p = new CountingLongPredicate(bitMap, func); - return other.forEachBitMap(p) && p.forEachRemaining(); - } - - @Override - public SimpleBloomFilter copy() { - return new SimpleBloomFilter(this); - } - - @Override - public boolean merge(final IndexProducer indexProducer) { - Objects.requireNonNull(indexProducer, "indexProducer"); - indexProducer.forEachIndex(idx -> { - if (idx < 0 || idx >= shape.getNumberOfBits()) { - throw new IllegalArgumentException(String.format( - "IndexProducer should only send values in the range[0,%s)", shape.getNumberOfBits())); - } - BitMap.set(bitMap, idx); - return true; - }); - cardinality = -1; - return true; - } - - @Override - public boolean merge(final BitMapProducer bitMapProducer) { - Objects.requireNonNull(bitMapProducer, "bitMapProducer"); - try { - final int[] idx = new int[1]; - bitMapProducer.forEachBitMap(value -> { - bitMap[idx[0]++] |= value; - return true; - }); - // idx[0] will be limit+1 so decrement it - idx[0]--; - final int idxLimit = BitMap.getLongIndex(shape.getNumberOfBits()); - if (idxLimit < idx[0]) { - throw new IllegalArgumentException(String.format( - "BitMapProducer set a bit higher than the limit for the shape: %s", shape.getNumberOfBits() - 1)); - } - if (idxLimit == idx[0]) { - final long excess = bitMap[idxLimit] >> shape.getNumberOfBits(); - if (excess != 0) { - throw new IllegalArgumentException( - String.format("BitMapProducer set a bit higher than the limit for the shape: %s", - shape.getNumberOfBits())); - } - } - cardinality = -1; - } catch (final IndexOutOfBoundsException e) { - throw new IllegalArgumentException( - String.format("BitMapProducer should send at most %s maps", bitMap.length), e); - } - return true; - } - - @Override - public boolean merge(final Hasher hasher) { - Objects.requireNonNull(hasher, "hasher"); - return merge(hasher.indices(shape)); - } - - @Override - public boolean merge(final BloomFilter other) { - Objects.requireNonNull(other, "other"); - if ((other.characteristics() & SPARSE) != 0) { - merge((IndexProducer) other); - } else { - merge((BitMapProducer) other); - } - return true; - } - - @Override - public Shape getShape() { - return shape; - } - - @Override - public int characteristics() { - return 0; - } - - @Override - public int cardinality() { - // Lazy evaluation with caching - int c = cardinality; - if (c < 0) { - cardinality = c = SetOperations.cardinality(this); - } - return c; - } - - @Override - public boolean forEachIndex(final IntPredicate consumer) { - Objects.requireNonNull(consumer, "consumer"); - return IndexProducer.fromBitMapProducer(this).forEachIndex(consumer); - } - - @Override - public boolean forEachBitMap(final LongPredicate consumer) { - Objects.requireNonNull(consumer, "consumer"); - for (final long l : bitMap) { - if (!consumer.test(l)) { - return false; - } - } - return true; - } - - @Override - public boolean contains(final IndexProducer indexProducer) { - return indexProducer.forEachIndex(idx -> BitMap.contains(bitMap, idx)); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/SparseBloomFilter.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/SparseBloomFilter.java deleted file mode 100644 index bb4b078f66..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/SparseBloomFilter.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.bloomfilter; - -import java.util.Objects; -import java.util.TreeSet; -import java.util.function.IntPredicate; -import java.util.function.LongPredicate; - -/** - * A bloom filter using a TreeSet of integers to track enabled bits. This is a standard - * implementation and should work well for most low cardinality Bloom filters. - * @since 4.5 - */ -public final class SparseBloomFilter implements BloomFilter { - - /** - * The bitSet that defines this BloomFilter. - */ - private final TreeSet indices; - - /** - * The shape of this BloomFilter. - */ - private final Shape shape; - - /** - * Constructs an empty BitSetBloomFilter. - * - * @param shape The shape of the filter. - */ - public SparseBloomFilter(final Shape shape) { - Objects.requireNonNull(shape, "shape"); - this.shape = shape; - this.indices = new TreeSet<>(); - } - - private SparseBloomFilter(final SparseBloomFilter source) { - shape = source.shape; - indices = new TreeSet<>(source.indices); - } - - @Override - public long[] asBitMapArray() { - final long[] result = new long[BitMap.numberOfBitMaps(shape.getNumberOfBits())]; - for (final int i : indices) { - BitMap.set(result, i); - } - return result; - } - - @Override - public SparseBloomFilter copy() { - return new SparseBloomFilter(this); - } - - /** - * Adds the index to the indices. - * @param idx the index to add. - * @return {@code true} always - */ - private boolean add(final int idx) { - indices.add(idx); - return true; - } - - @Override - public boolean merge(final IndexProducer indexProducer) { - Objects.requireNonNull(indexProducer, "indexProducer"); - indexProducer.forEachIndex(this::add); - if (!this.indices.isEmpty()) { - if (this.indices.last() >= shape.getNumberOfBits()) { - throw new IllegalArgumentException(String.format("Value in list %s is greater than maximum value (%s)", - this.indices.last(), shape.getNumberOfBits() - 1)); - } - if (this.indices.first() < 0) { - throw new IllegalArgumentException( - String.format("Value in list %s is less than 0", this.indices.first())); - } - } - return true; - } - - @Override - public boolean merge(final BitMapProducer bitMapProducer) { - Objects.requireNonNull(bitMapProducer, "bitMapProducer"); - return this.merge(IndexProducer.fromBitMapProducer(bitMapProducer)); - } - - @Override - public boolean merge(final Hasher hasher) { - Objects.requireNonNull(hasher, "hasher"); - merge(hasher.indices(shape)); - return true; - } - - @Override - public boolean merge(final BloomFilter other) { - Objects.requireNonNull(other, "other"); - final IndexProducer producer = (other.characteristics() & SPARSE) != 0 ? (IndexProducer) other : IndexProducer.fromBitMapProducer(other); - merge(producer); - return true; - } - - @Override - public void clear() { - indices.clear(); - } - - @Override - public Shape getShape() { - return shape; - } - - @Override - public int characteristics() { - return SPARSE; - } - - @Override - public int cardinality() { - return indices.size(); - } - - @Override - public boolean forEachIndex(final IntPredicate consumer) { - Objects.requireNonNull(consumer, "consumer"); - for (final int value : indices) { - if (!consumer.test(value)) { - return false; - } - } - return true; - } - - @Override - public boolean forEachBitMap(final LongPredicate consumer) { - Objects.requireNonNull(consumer, "consumer"); - final int limit = BitMap.numberOfBitMaps(shape.getNumberOfBits()); - /* - * because our indices are always in order we can shorten the time necessary to - * create the longs for the consumer - */ - // the currently constructed bitMap - long bitMap = 0; - // the bitmap we are working on - int idx = 0; - for (final int i : indices) { - while (BitMap.getLongIndex(i) != idx) { - if (!consumer.test(bitMap)) { - return false; - } - bitMap = 0; - idx++; - } - bitMap |= BitMap.getLongBit(i); - } - // we fall through with data in the bitMap - if (!consumer.test(bitMap)) { - return false; - } - // account for hte bitMap in the previous block + the next one - idx++; - // while there are more blocks to generate send zero to the consumer. - while (idx < limit) { - if (!consumer.test(0L)) { - return false; - } - idx++; - } - return true; - } - - @Override - public boolean contains(final IndexProducer indexProducer) { - return indexProducer.forEachIndex(indices::contains); - } - - @Override - public boolean contains(final BitMapProducer bitMapProducer) { - return contains(IndexProducer.fromBitMapProducer(bitMapProducer)); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/bloomfilter/package-info.java b/src/main/java/repack/apache/commons/collections4/bloomfilter/package-info.java deleted file mode 100644 index 581b6026a3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/bloomfilter/package-info.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * A collection of extensible Bloom filter classes and interfaces. - * - *

Background:

- * - *

The Bloom filter is a probabilistic data structure that indicates where things are not. Conceptually it is a bit - * vector. You create a Bloom filter by creating hashes and converting those to enabled bits in the vector. Multiple - * Bloom filters may be merged together into one Bloom filter. It is possible to test if a filter {@code B} has merged - * into another filter {@code A} by verifying that {@code (A & B) == B}.

- * - *

Bloom filters are generally used where hash tables would be too large, or as a filter front end for longer processes. - * For example most browsers have a Bloom filter that is built from all known bad URLs (ones that serve up malware). - * When you enter a URL the browser builds a Bloom filter and checks to see if it is "in" the bad URL filter. If not the - * URL is good, if it matches, then the expensive lookup on a remote system is made to see if it actually is in the - * list. There are lots of other uses, and in most cases the reason is to perform a fast check as a gateway for a longer - * operation.

- * - *

BloomFilter

- * - *

The Bloom filter architecture here is designed for speed of execution, so some methods like {@code merge}, {@code remove}, - * {@code add}, and {@code subtract} may throw exceptions. Once an exception is thrown the state of the Bloom filter is unknown. - * The choice to use not use atomic transactions was made to achieve maximum performance under correct usage.

- * - *

In addition the architecture is designed so that the implementation of the storage of bits is abstracted. - * Programs that utilize the Bloom filters may use the {@code BitMapProducer} or {@code IndexProducer} to retrieve a - * representation of the internal structure. Additional methods are available in the {@code BitMap} to assist in - * manipulation of the representations.

- * - *

The bloom filter code is an interface that requires implementation of 9 methods:

- *
    - *
  • {@link BloomFilter#cardinality()} returns the number of bits enabled in the Bloom filter.
  • - * - *
  • {@link BloomFilter#characteristics()} which returns an integer of characteristics flags.
  • - * - *
  • {@link BloomFilter#clear()} which resets the Bloomfilter to its initial empty state.
  • - * - *
  • {@link BloomFilter#contains(IndexProducer)} which returns true if the bits specified by the indices generated by - * IndexProducer are enabled in the Bloom filter.
  • - * - *
  • {@link BloomFilter#copy()} which returns a fresh copy of the bitmap.
  • - * - *
  • {@link BloomFilter#getShape()} which returns the shape the Bloom filter was created with.
  • - * - *
  • {@link BloomFilter#merge(BitMapProducer)} which merges the BitMaps from the BitMapProducer into the internal - * representation of the Bloom filter.
  • - * - *
  • {@link BloomFilter#merge(IndexProducer)} which merges the indices from the IndexProducer into the internal - * representation of the Bloom filter.
  • - *
- * - *

Other methods should be implemented where they can be done so more efficiently than the default implementations.

- * - *

CountingBloomFilter

- * - *

The counting bloom filter extends the Bloom filter by counting the number of times a specific bit has been - * enabled or disabled. This allows the removal (opposite of merge) of Bloom filters at the expense of additional - * overhead.

- * - *

Shape

- * - *

The Shape describes the Bloom filter using the number of bits and the number of hash functions

- * - *

Hasher

- * - *

A Hasher converts bytes into a series of integers based on a Shape. Each hasher represents one item being added - * to the Bloom filter.

- * - *

The EnhancedDoubleHasher uses a combinatorial generation technique to create the integers. It is easily - * initialized by using a byte array returned by the standard {@code MessageDigest} or other hash function to - * initialize the Hasher. Alternatively a pair of a long values may also be used.

- * - *

Other implementations of the Hasher are easy to implement, and should make use of the {@code Hasher.Filter} - * and/or {@code Hasher.FileredIntConsumer} classes to filter out duplicate indices when implementing - * {@code Hasher.uniqueIndices(Shape)}.

- * - *

References

- * - *
    - *
  1. https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf
  2. - *
  3. https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/utils/BloomFilter.java#L60
  4. - *
- * - * @since 4.5 - */ -package repack.apache.commons.collections4.bloomfilter; diff --git a/src/main/java/repack/apache/commons/collections4/collection/AbstractCollectionDecorator.java b/src/main/java/repack/apache/commons/collections4/collection/AbstractCollectionDecorator.java deleted file mode 100644 index f87e0f1383..0000000000 --- a/src/main/java/repack/apache/commons/collections4/collection/AbstractCollectionDecorator.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.collection; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Iterator; -import java.util.Objects; -import java.util.function.Predicate; - -/** - * Decorates another {@code Collection} to provide additional behavior. - *

- * Each method call made on this {@code Collection} is forwarded to the - * decorated {@code Collection}. This class is used as a framework on which - * to build to extensions such as synchronized and unmodifiable behavior. The - * main advantage of decoration is that one decorator can wrap any implementation - * of {@code 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. - *

- *

- * This implementation does not forward the hashCode and equals methods through - * to the backing object, but relies on Object's implementation. This is necessary - * to preserve the symmetry of equals. Custom definitions of equality are usually - * based on an interface, such as Set or List, so that the implementation of equals - * can cast the object being tested for equality to the custom interface. - * AbstractCollectionDecorator does not implement such custom interfaces directly; - * they are implemented only in subclasses. Therefore, forwarding equals would break - * symmetry, as the forwarding object might consider itself equal to the object being - * tested, but the reverse could not be true. This behavior is consistent with the - * JDK's collection wrappers, such as {@link java.util.Collections#unmodifiableCollection(Collection)}. - * Use an interface-specific subclass of AbstractCollectionDecorator, such as - * AbstractListDecorator, to preserve equality behavior, or override equals directly. - *

- * - * @param the type of the elements in the collection - * @since 3.0 - */ -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() { - } - - /** - * Constructor that wraps (not copies). - * - * @param collection the collection to decorate, must not be null - * @throws NullPointerException if the collection is null - */ - protected AbstractCollectionDecorator(final Collection collection) { - this.collection = Objects.requireNonNull(collection, "collection"); - } - - /** - * 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; - } - - - @Override - public boolean add(final E object) { - return decorated().add(object); - } - - @Override - public boolean addAll(final Collection coll) { - return decorated().addAll(coll); - } - - @Override - public void clear() { - decorated().clear(); - } - - @Override - public boolean contains(final Object object) { - return decorated().contains(object); - } - - @Override - public boolean isEmpty() { - return decorated().isEmpty(); - } - - @Override - public Iterator iterator() { - return decorated().iterator(); - } - - @Override - public boolean remove(final Object object) { - return decorated().remove(object); - } - - @Override - public int size() { - return decorated().size(); - } - - @Override - public Object[] toArray() { - return decorated().toArray(); - } - - @Override - public T[] toArray(final T[] object) { - return decorated().toArray(object); - } - - @Override - public boolean containsAll(final Collection coll) { - return decorated().containsAll(coll); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - return decorated().removeIf(filter); - } - - @Override - public boolean removeAll(final Collection coll) { - return decorated().removeAll(coll); - } - - @Override - public boolean retainAll(final Collection coll) { - return decorated().retainAll(coll); - } - - @Override - public String toString() { - return decorated().toString(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/collection/CompositeCollection.java b/src/main/java/repack/apache/commons/collections4/collection/CompositeCollection.java deleted file mode 100644 index aaf3420d88..0000000000 --- a/src/main/java/repack/apache/commons/collections4/collection/CompositeCollection.java +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.collection; - -import java.io.Serializable; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.iterators.EmptyIterator; -import repack.apache.commons.collections4.iterators.IteratorChain; -import repack.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 - */ -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() { - } - - /** - * Create a Composite Collection with one collection. - * - * @param compositeCollection the Collection to be appended to the composite - */ - public CompositeCollection(final Collection compositeCollection) { - 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) { - addComposited(compositeCollection1, compositeCollection2); - } - - /** - * Create a Composite Collection with an array of collections. - * - * @param compositeCollections the collections to composite - */ - public CompositeCollection(final Collection... compositeCollections) { - addComposited(compositeCollections); - } - - /** - * Gets the size of this composite collection. - *

- * This implementation calls {@code size()} on each collection. - *

- * @return total number of elements in all contained containers - */ - @Override - 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 {@code isEmpty()} on each collection. - *

- * @return true if all of the contained collections are empty - */ - @Override - public boolean isEmpty() { - for (final Collection item : all) { - if (!item.isEmpty()) { - return false; - } - } - return true; - } - - /** - * Checks whether this composite collection contains the object. - *

- * This implementation calls {@code contains()} on each collection. - *

- * @param obj the object to search for - * @return true if obj is contained in any of the contained collections - */ - @Override - 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 {@code IteratorChain}. - *

- * @return an {@code IteratorChain} instance which supports - * {@code remove()}. Iteration occurs over contained collections in - * the order they were added, but this behavior should not be relied upon. - * @see IteratorChain - */ - @Override - public Iterator iterator() { - if (all.isEmpty()) { - return EmptyIterator.emptyIterator(); - } - final IteratorChain chain = new IteratorChain<>(); - all.forEach(item -> 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 - */ - @Override - 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 {@code 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 - */ - @Override - @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 - */ - @Override - 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 - */ - @Override - 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 {@code contains()} for each element in the - * specified collection. - *

- * @param coll the collection to check for - * @return true if all elements contained - */ - @Override - public boolean containsAll(final Collection coll) { - if (coll == null) { - return false; - } - for (final Object item : coll) { - if (!contains(item)) { - 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 - */ - @Override - 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 {@code removeAll} on each collection. - *

- * @param coll the collection to remove - * @return true if the collection was modified - * @throws UnsupportedOperationException if removeAll is unsupported - */ - @Override - public boolean removeAll(final Collection coll) { - if (CollectionUtils.isEmpty(coll)) { - return false; - } - boolean changed = false; - for (final Collection item : all) { - changed |= item.removeAll(coll); - } - return changed; - } - - /** - * Removes all of the elements of this collection that satisfy the given predicate from this composite collection. - *

- * This implementation calls {@code removeIf} on each collection. - *

- * @param filter a predicate which returns true for elements to be removed - * @return true if the collection was modified - * @throws UnsupportedOperationException if removeIf is unsupported - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - if (Objects.isNull(filter)) { - return false; - } - boolean changed = false; - for (final Collection item : all) { - changed |= item.removeIf(filter); - } - return changed; - } - - /** - * Retains all the elements in the specified collection in this composite collection, - * removing all others. - *

- * This implementation calls {@code retainAll()} on each collection. - *

- * @param coll the collection to remove - * @return true if the collection was modified - * @throws UnsupportedOperationException if retainAll is unsupported - */ - @Override - public boolean retainAll(final Collection coll) { - boolean changed = false; - if (coll != null) { - for (final Collection item : all) { - changed |= item.retainAll(coll); - } - } - return changed; - } - - /** - * Removes all of the elements from this collection . - *

- * This implementation calls {@code clear()} on each collection. - *

- * @throws UnsupportedOperationException if clear is unsupported - */ - @Override - 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) { - if (compositeCollection != null) { - 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) { - if (compositeCollection1 != null) { - all.add(compositeCollection1); - } - if (compositeCollection2 != null) { - 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) { - for (final Collection compositeCollection : compositeCollections) { - if (compositeCollection != null) { - all.add(compositeCollection); - } - } - } - - /** - * 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<E> - */ - 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); - - } - -} - diff --git a/src/main/java/repack/apache/commons/collections4/collection/IndexedCollection.java b/src/main/java/repack/apache/commons/collections4/collection/IndexedCollection.java deleted file mode 100644 index 50c600264d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/collection/IndexedCollection.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.collection; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Objects; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.MultiMap; -import repack.apache.commons.collections4.Transformer; -import repack.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 - */ -public class IndexedCollection extends AbstractCollectionDecorator { - - // TODO: replace with MultiValuedMap - - /** 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; - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - if (Objects.isNull(filter)) { - return false; - } - boolean changed = false; - final Iterator it = iterator(); - while (it.hasNext()) { - if (filter.test(it.next())) { - it.remove(); - changed = true; - } - } - if (changed) { - reindex(); - } - return changed; - } - - @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)); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/collection/PredicatedCollection.java b/src/main/java/repack/apache/commons/collections4/collection/PredicatedCollection.java deleted file mode 100644 index 611bdc6219..0000000000 --- a/src/main/java/repack/apache/commons/collections4/collection/PredicatedCollection.java +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.collection; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Objects; -import java.util.Queue; -import java.util.Set; - -import repack.apache.commons.collections4.Bag; -import repack.apache.commons.collections4.MultiSet; -import repack.apache.commons.collections4.Predicate; -import repack.apache.commons.collections4.bag.HashBag; -import repack.apache.commons.collections4.bag.PredicatedBag; -import repack.apache.commons.collections4.functors.NotNullPredicate; -import repack.apache.commons.collections4.list.PredicatedList; -import repack.apache.commons.collections4.multiset.HashMultiSet; -import repack.apache.commons.collections4.multiset.PredicatedMultiSet; -import repack.apache.commons.collections4.queue.PredicatedQueue; -import repack.apache.commons.collections4.set.PredicatedSet; - -/** - * 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.predicatedCollection(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 - */ -public class PredicatedCollection extends AbstractCollectionDecorator { - - /** Serialization version */ - private static final long serialVersionUID = -5259182142076705162L; - - /** The predicate to use */ - protected final Predicate predicate; - - /** - * Returns a Builder with the given predicate. - * - * @param the element type - * @param predicate the predicate to use - * @return a new Builder for predicated collections - * @since 4.1 - */ - public static Builder builder(final Predicate predicate) { - return new Builder<>(predicate); - } - - /** - * Returns a Builder with a NotNullPredicate. - * - * @param the element type - * @return a new Builder for predicated collections that ignores null values. - * @since 4.1 - */ - public static Builder notNullBuilder() { - return new Builder<>(NotNullPredicate.notNullPredicate()); - } - - /** - * 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 NullPointerException 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 collection the collection to decorate, must not be null - * @param predicate the predicate to use for validation, must not be null - * @throws NullPointerException if collection or predicate is null - * @throws IllegalArgumentException if the collection contains invalid elements - */ - protected PredicatedCollection(final Collection collection, final Predicate predicate) { - super(collection); - this.predicate = Objects.requireNonNull(predicate, "predicate"); - for (final E item : collection) { - 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)) { - 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 anyone 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); - } - - /** - * Builder for creating predicated collections. - *

- * Create a Builder with a predicate to validate elements against, then add any elements - * to the builder. Elements that fail the predicate will be added to a rejected list. - * Finally create or decorate a collection using the createPredicated[List,Set,Bag,Queue] methods. - *

- * An example: - *

-     *   Predicate<String> predicate = NotNullPredicate.notNullPredicate();
-     *   PredicatedCollectionBuilder<String> builder = PredicatedCollection.builder(predicate);
-     *   builder.add("item1");
-     *   builder.add(null);
-     *   builder.add("item2");
-     *   List<String> predicatedList = builder.createPredicatedList();
-     * 
- *

- * At the end of the code fragment above predicatedList is protected by the predicate supplied - * to the builder and it contains item1 and item2. - *

- * More elements can be added to the builder once a predicated collection has been created, - * but these elements will not be reflected in already created collections. - * - * @param the element type - * @since 4.1 - */ - public static class Builder { - - /** The predicate to use. */ - private final Predicate predicate; - - /** The buffer containing valid elements. */ - private final List accepted = new ArrayList<>(); - - /** The buffer containing rejected elements. */ - private final List rejected = new ArrayList<>(); - - /** - * Constructs a PredicatedCollectionBuilder with the specified Predicate. - * - * @param predicate the predicate to use - * @throws NullPointerException if predicate is null - */ - public Builder(final Predicate predicate) { - this.predicate = Objects.requireNonNull(predicate, "predicate"); - } - - /** - * Adds the item to the builder. - *

- * If the predicate is true, it is added to the list of accepted elements, - * otherwise it is added to the rejected list. - * - * @param item the element to add - * @return the PredicatedCollectionBuilder. - */ - public Builder add(final E item) { - if (predicate.evaluate(item)) { - accepted.add(item); - } else { - rejected.add(item); - } - return this; - } - - /** - * Adds all elements from the given collection to the builder. - *

- * All elements for which the predicate evaluates to true will be added to the - * list of accepted elements, otherwise they are added to the rejected list. - * - * @param items the elements to add to the builder - * @return the PredicatedCollectionBuilder. - */ - public Builder addAll(final Collection items) { - if (items != null) { - for (final E item : items) { - add(item); - } - } - return this; - } - - /** - * Create a new predicated list filled with the accepted elements. - *

- * The builder is not modified by this method, so it is possible to create more collections - * or add more elements afterwards. Further changes will not propagate to the returned list. - * - * @return a new predicated list. - */ - public List createPredicatedList() { - return createPredicatedList(new ArrayList<>()); - } - - /** - * Decorates the given list with validating behavior using the predicate. All accepted elements - * are appended to the list. If the list already contains elements, they are validated. - *

- * The builder is not modified by this method, so it is possible to create more collections - * or add more elements afterwards. Further changes will not propagate to the returned list. - * - * @param list the List to decorate, must not be null - * @return the decorated list. - * @throws NullPointerException if list is null - * @throws IllegalArgumentException if list contains invalid elements - */ - public List createPredicatedList(final List list) { - Objects.requireNonNull(list, "list"); - final List predicatedList = PredicatedList.predicatedList(list, predicate); - predicatedList.addAll(accepted); - return predicatedList; - } - - /** - * Create a new predicated set filled with the accepted elements. - *

- * The builder is not modified by this method, so it is possible to create more collections - * or add more elements afterwards. Further changes will not propagate to the returned set. - * - * @return a new predicated set. - */ - public Set createPredicatedSet() { - return createPredicatedSet(new HashSet<>()); - } - - /** - * Decorates the given list with validating behavior using the predicate. All accepted elements - * are appended to the set. If the set already contains elements, they are validated. - *

- * The builder is not modified by this method, so it is possible to create more collections - * or add more elements afterwards. Further changes will not propagate to the returned set. - * - * @param set the set to decorate, must not be null - * @return the decorated set. - * @throws NullPointerException if set is null - * @throws IllegalArgumentException if set contains invalid elements - */ - public Set createPredicatedSet(final Set set) { - Objects.requireNonNull(set, "set"); - final PredicatedSet predicatedSet = PredicatedSet.predicatedSet(set, predicate); - predicatedSet.addAll(accepted); - return predicatedSet; - } - - /** - * Create a new predicated multiset filled with the accepted elements. - *

- * The builder is not modified by this method, so it is possible to create more collections - * or add more elements afterwards. Further changes will not propagate to the returned multiset. - * - * @return a new predicated multiset. - */ - public MultiSet createPredicatedMultiSet() { - return createPredicatedMultiSet(new HashMultiSet<>()); - } - - /** - * Decorates the given multiset with validating behavior using the predicate. All accepted elements - * are appended to the multiset. If the multiset already contains elements, they are validated. - *

- * The builder is not modified by this method, so it is possible to create more collections - * or add more elements afterwards. Further changes will not propagate to the returned multiset. - * - * @param multiset the multiset to decorate, must not be null - * @return the decorated multiset. - * @throws NullPointerException if multiset is null - * @throws IllegalArgumentException if multiset contains invalid elements - */ - public MultiSet createPredicatedMultiSet(final MultiSet multiset) { - Objects.requireNonNull(multiset, "multiset"); - final PredicatedMultiSet predicatedMultiSet = - PredicatedMultiSet.predicatedMultiSet(multiset, predicate); - predicatedMultiSet.addAll(accepted); - return predicatedMultiSet; - } - - /** - * Create a new predicated bag filled with the accepted elements. - *

- * The builder is not modified by this method, so it is possible to create more collections - * or add more elements afterwards. Further changes will not propagate to the returned bag. - * - * @return a new predicated bag. - */ - public Bag createPredicatedBag() { - return createPredicatedBag(new HashBag<>()); - } - - /** - * Decorates the given bag with validating behavior using the predicate. All accepted elements - * are appended to the bag. If the bag already contains elements, they are validated. - *

- * The builder is not modified by this method, so it is possible to create more collections - * or add more elements afterwards. Further changes will not propagate to the returned bag. - * - * @param bag the bag to decorate, must not be null - * @return the decorated bag. - * @throws NullPointerException if bag is null - * @throws IllegalArgumentException if bag contains invalid elements - */ - public Bag createPredicatedBag(final Bag bag) { - Objects.requireNonNull(bag, "bag"); - final PredicatedBag predicatedBag = PredicatedBag.predicatedBag(bag, predicate); - predicatedBag.addAll(accepted); - return predicatedBag; - } - - /** - * Create a new predicated queue filled with the accepted elements. - *

- * The builder is not modified by this method, so it is possible to create more collections - * or add more elements afterwards. Further changes will not propagate to the returned queue. - * - * @return a new predicated queue. - */ - public Queue createPredicatedQueue() { - return createPredicatedQueue(new LinkedList<>()); - } - - /** - * Decorates the given queue with validating behavior using the predicate. All accepted elements - * are appended to the queue. If the queue already contains elements, they are validated. - *

- * The builder is not modified by this method, so it is possible to create more collections - * or add more elements afterwards. Further changes will not propagate to the returned queue. - * - * @param queue the queue to decorate, must not be null - * @return the decorated queue. - * @throws NullPointerException if queue is null - * @throws IllegalArgumentException if queue contains invalid elements - */ - public Queue createPredicatedQueue(final Queue queue) { - Objects.requireNonNull(queue, "queue"); - final PredicatedQueue predicatedQueue = PredicatedQueue.predicatedQueue(queue, predicate); - predicatedQueue.addAll(accepted); - return predicatedQueue; - } - - /** - * Returns an unmodifiable collection containing all rejected elements. - * - * @return an unmodifiable collection - */ - public Collection rejectedElements() { - return Collections.unmodifiableCollection(rejected); - } - - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/collection/SynchronizedCollection.java b/src/main/java/repack/apache/commons/collections4/collection/SynchronizedCollection.java deleted file mode 100644 index e25bf62987..0000000000 --- a/src/main/java/repack/apache/commons/collections4/collection/SynchronizedCollection.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.collection; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Iterator; -import java.util.Objects; -import java.util.function.Predicate; - -/** - * Decorates another {@link Collection} to synchronize its behavior - * for a multithreaded 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 - */ -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 NullPointerException 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 NullPointerException if the collection is null - */ - protected SynchronizedCollection(final Collection collection) { - this.collection = Objects.requireNonNull(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 NullPointerException if the collection or lock is null - */ - protected SynchronizedCollection(final Collection collection, final Object lock) { - this.collection = Objects.requireNonNull(collection, "collection"); - this.lock = Objects.requireNonNull(lock, "lock"); - } - - /** - * Gets the collection being decorated. - * - * @return the decorated collection - */ - protected Collection decorated() { - return collection; - } - - - @Override - public boolean add(final E object) { - synchronized (lock) { - return decorated().add(object); - } - } - - @Override - public boolean addAll(final Collection coll) { - synchronized (lock) { - return decorated().addAll(coll); - } - } - - @Override - public void clear() { - synchronized (lock) { - decorated().clear(); - } - } - - @Override - public boolean contains(final Object object) { - synchronized (lock) { - return decorated().contains(object); - } - } - - @Override - public boolean containsAll(final Collection coll) { - synchronized (lock) { - return decorated().containsAll(coll); - } - } - - @Override - 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 - */ - @Override - public Iterator iterator() { - return decorated().iterator(); - } - - @Override - public Object[] toArray() { - synchronized (lock) { - return decorated().toArray(); - } - } - - @Override - public T[] toArray(final T[] object) { - synchronized (lock) { - return decorated().toArray(object); - } - } - - @Override - public boolean remove(final Object object) { - synchronized (lock) { - return decorated().remove(object); - } - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - synchronized (lock) { - return decorated().removeIf(filter); - } - } - - @Override - public boolean removeAll(final Collection coll) { - synchronized (lock) { - return decorated().removeAll(coll); - } - } - - @Override - public boolean retainAll(final Collection coll) { - synchronized (lock) { - return decorated().retainAll(coll); - } - } - - @Override - 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(); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/collection/TransformedCollection.java b/src/main/java/repack/apache/commons/collections4/collection/TransformedCollection.java deleted file mode 100644 index 5faf56342f..0000000000 --- a/src/main/java/repack/apache/commons/collections4/collection/TransformedCollection.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.collection; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Objects; - -import repack.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 - */ -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 NullPointerException 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 NullPointerException 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.isEmpty()) { - @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 collection the collection to decorate, must not be null - * @param transformer the transformer to use for conversion, must not be null - * @throws NullPointerException if collection or transformer is null - */ - protected TransformedCollection(final Collection collection, final Transformer transformer) { - super(collection); - this.transformer = Objects.requireNonNull(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)); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/collection/UnmodifiableBoundedCollection.java b/src/main/java/repack/apache/commons/collections4/collection/UnmodifiableBoundedCollection.java deleted file mode 100644 index bb1a8d27ce..0000000000 --- a/src/main/java/repack/apache/commons/collections4/collection/UnmodifiableBoundedCollection.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.collection; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Objects; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.BoundedCollection; -import repack.apache.commons.collections4.Unmodifiable; -import repack.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. - *

- * - * @param the type of elements in this collection - * @since 3.0 - */ -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 {@code BoundedCollection} to decorate, must not be null - * @return a new unmodifiable bounded collection - * @throws NullPointerException 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 collection the {@code BoundedCollection} to decorate, must not be null - * @return a new unmodifiable bounded collection - * @throws NullPointerException if coll is null - * @throws IllegalArgumentException if coll is not a {@code BoundedCollection} - * @since 4.0 - */ - @SuppressWarnings("unchecked") - public static BoundedCollection unmodifiableBoundedCollection(Collection collection) { - Objects.requireNonNull(collection, "collection"); - - // handle decorators - for (int i = 0; i < 1000; i++) { // counter to prevent infinite looping - if (collection instanceof BoundedCollection) { - break; // normal loop exit - } - if (collection instanceof AbstractCollectionDecorator) { - collection = ((AbstractCollectionDecorator) collection).decorated(); - } else if (collection instanceof SynchronizedCollection) { - collection = ((SynchronizedCollection) collection).decorated(); - } - } - - if (!(collection instanceof BoundedCollection)) { - throw new IllegalArgumentException("Collection is not a bounded collection."); - } - return new UnmodifiableBoundedCollection<>((BoundedCollection) collection); - } - - /** - * Constructor that wraps (not copies). - * - * @param coll the collection to decorate, must not be null - * @throws NullPointerException 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - 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 isFull() { - return decorated().isFull(); - } - - @Override - public int maxSize() { - return decorated().maxSize(); - } - - @Override - protected BoundedCollection decorated() { - return (BoundedCollection) super.decorated(); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/collection/UnmodifiableCollection.java b/src/main/java/repack/apache/commons/collections4/collection/UnmodifiableCollection.java deleted file mode 100644 index 966aaef645..0000000000 --- a/src/main/java/repack/apache/commons/collections4/collection/UnmodifiableCollection.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.collection; - -import java.util.Collection; -import java.util.Iterator; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.Unmodifiable; -import repack.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 - */ -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 NullPointerException 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 NullPointerException 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeAll(final Collection coll) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean retainAll(final Collection coll) { - throw new UnsupportedOperationException(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/collection/package-info.java b/src/main/java/repack/apache/commons/collections4/collection/package-info.java deleted file mode 100644 index f5e6d8cdea..0000000000 --- a/src/main/java/repack/apache/commons/collections4/collection/package-info.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 multithreaded 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 - *
- * - */ -package repack.apache.commons.collections4.collection; diff --git a/src/main/java/repack/apache/commons/collections4/comparators/BooleanComparator.java b/src/main/java/repack/apache/commons/collections4/comparators/BooleanComparator.java deleted file mode 100644 index 32be79d1a4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/comparators/BooleanComparator.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -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); - - /** {@code true} iff {@code true} values sort before {@code false} values. */ - private final boolean trueFirst; - - /** - * Returns a BooleanComparator instance that sorts - * {@code true} values before {@code 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 - * {@code false} values before {@code 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 - * {@code trueFirst} values before - * {@code !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 {@code true}, sort - * {@code true} {@code Boolean}s before {@code false} - * @return a singleton BooleanComparator instance - * @since 4.0 - */ - public static BooleanComparator booleanComparator(final boolean trueFirst) { - return trueFirst ? TRUE_FIRST : FALSE_FIRST; - } - - /** - * Creates a {@code BooleanComparator} that sorts - * {@code false} values before {@code true} values. - *

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

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

- * Please use the static factories instead whenever possible. - * - * @param trueFirst when {@code true}, sort - * {@code true} boolean values before {@code false} - */ - public BooleanComparator(final boolean trueFirst) { - this.trueFirst = trueFirst; - } - - /** - * Compares two non-{@code null} {@code 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 {@code null} - */ - @Override - 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 {@code true} iff that Object is - * a {@link Comparator} whose ordering is known to be - * equivalent to mine. - *

- * This implementation returns {@code true} - * iff {@code 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 {@code true} iff - * I sort {@code true} values before - * {@code false} values. In other words, - * returns {@code true} iff - * {@link #compare(Boolean,Boolean) compare(Boolean.FALSE,Boolean.TRUE)} - * returns a positive value. - * - * @return the trueFirst flag - */ - public boolean sortsTrueFirst() { - return trueFirst; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/comparators/ComparableComparator.java b/src/main/java/repack/apache/commons/collections4/comparators/ComparableComparator.java deleted file mode 100644 index c3f1af6307..0000000000 --- a/src/main/java/repack/apache/commons/collections4/comparators/ComparableComparator.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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(Comparable, Comparable)} compare} were {@code 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(Comparable, Comparable)} compare} for - * details. - *

- * - * @param the type of objects compared by this comparator - * - * @since 2.0 - * @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 - */ - public static > ComparableComparator comparableComparator() { - return INSTANCE; - } - - /** - * Constructor whose use should be avoided. - *

- * Please use the {@link #comparableComparator()} method whenever possible. - */ - public ComparableComparator() { - } - - /** - * 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 {@code null}, - * or when {@code ((Comparable)obj1).compareTo(obj2)} does - * @throws ClassCastException if obj1 is not a {@code Comparable}, - * or when {@code ((Comparable)obj1).compareTo(obj2)} does - */ - @Override - 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 a {@link Comparator Comparator} - * whose ordering is known to be equivalent to mine. - *

- * This implementation returns {@code true} iff - * {@code object.{@link Object#getClass() getClass()}} equals - * {@code 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()); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/comparators/ComparatorChain.java b/src/main/java/repack/apache/commons/collections4/comparators/ComparatorChain.java deleted file mode 100644 index bef1f93948..0000000000 --- a/src/main/java/repack/apache/commons/collections4/comparators/ComparatorChain.java +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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; -import java.util.Objects; - -/** - * 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 behavior 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. - *

- * - * @param the type of objects compared by this comparator - * @since 2.0 - */ -public class ComparatorChain implements Comparator, Serializable { - - /** Serialization version from Collections 2.0. */ - private static final long serialVersionUID = -721644942746081630L; - - /** The list of comparators in the chain. */ - private final List> comparatorChain; - /** Order - false (clear) = ascend; true (set) = descend. */ - private final BitSet orderingBits; - /** Whether the chain has been "locked". */ - private boolean isLocked; - - /** - * 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) { - 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) { - orderingBits.set(comparatorChain.size() - 1); - } - } - - /** - * Replace the Comparator at the given index, maintaining - * the existing sort order. - * - * @param index index of the Comparator to replace - * @param comparator Comparator to place at the given index - * @throws IndexOutOfBoundsException - * if index < 0 or index >= size() - */ - public void setComparator(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) { - 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) { - 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.isEmpty()) { - 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 - */ - @Override - public int compare(final E o1, final E o2) throws UnsupportedOperationException { - if (!isLocked) { - 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)) { - 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 {@code true} iff that Object is - * a {@link Comparator} whose ordering is known to be - * equivalent to mine. - *

- * This implementation returns {@code true} - * iff {@code object.{@link Object#getClass() getClass()}} - * equals {@code 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 Objects.equals(orderingBits, chain.orderingBits) && - Objects.equals(comparatorChain, chain.comparatorChain); - } - return false; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/comparators/FixedOrderComparator.java b/src/main/java/repack/apache/commons/collections4/comparators/FixedOrderComparator.java deleted file mode 100644 index 454bb986aa..0000000000 --- a/src/main/java/repack/apache/commons/collections4/comparators/FixedOrderComparator.java +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.comparators; - -import java.io.Serializable; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * 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 {@code 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. - *

- * - * @param the type of objects compared by this comparator - * @since 3.0 - */ -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 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; - - /** Is the comparator locked against further change */ - private boolean isLocked; - - /** The behavior in the case of an unknown object */ - private UnknownObjectBehavior unknownObjectBehavior = UnknownObjectBehavior.EXCEPTION; - - // Constructors - /** - * Constructs an empty FixedOrderComparator. - */ - public FixedOrderComparator() { - } - - /** - * 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 NullPointerException if the array is null - */ - public FixedOrderComparator(final T... items) { - for (final T item : Objects.requireNonNull(items, "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 NullPointerException if the list is null - */ - public FixedOrderComparator(final List items) { - for (final T t : Objects.requireNonNull(items, "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 behavior - - * UNKNOWN_AFTER, UNKNOWN_BEFORE or UNKNOWN_THROW_EXCEPTION - * @throws UnsupportedOperationException if a comparison has been performed - * @throws NullPointerException if unknownObjectBehavior is null - */ - public void setUnknownObjectBehavior(final UnknownObjectBehavior unknownObjectBehavior) { - checkLocked(); - this.unknownObjectBehavior = Objects.requireNonNull(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 unrecognized 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)}. - */ - @Override - 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.hashCode(); - total = total*37 + (unknownObjectBehavior == null ? 0 : unknownObjectBehavior.hashCode()); - total = total*37 + counter; - total = total*37 + (isLocked ? 0 : 1); - return total; - } - - /** - * Returns {@code true} iff that Object is - * a {@link Comparator} whose ordering is known to be - * equivalent to mine. - *

- * This implementation returns {@code true} - * iff {@code 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/comparators/NullComparator.java b/src/main/java/repack/apache/commons/collections4/comparators/NullComparator.java deleted file mode 100644 index f8e17520a8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/comparators/NullComparator.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.comparators; - -import java.io.Serializable; -import java.util.Comparator; -import java.util.Objects; - -import repack.apache.commons.collections4.ComparatorUtils; - -/** - * A Comparator that will compare nulls to be either lower or higher than - * other objects. - * - * @param the type of objects compared by this comparator - * @since 2.0 - */ -public class NullComparator implements Comparator, Serializable { - - /** Serialization version. */ - private static final long serialVersionUID = -5820772575483504339L; - - /** - * The comparator to use when comparing two non-{@code null} objects. - **/ - private final Comparator nonNullComparator; - - /** - * Specifies whether a {@code null} are compared as higher than - * non-{@code null} objects. - **/ - private final boolean nullsAreHigh; - - /** - * Construct an instance that sorts {@code null} higher than any - * non-{@code null} object it is compared with. When comparing two - * non-{@code null} objects, the {@link ComparableComparator} is - * used. - **/ - public NullComparator() { - this(ComparatorUtils.NATURAL_COMPARATOR, true); - } - - /** - * Construct an instance that sorts {@code null} higher than any - * non-{@code null} object it is compared with. When comparing two - * non-{@code null} objects, the specified {@link Comparator} is - * used. - * - * @param nonNullComparator the comparator to use when comparing two - * non-{@code null} objects. This argument cannot be - * {@code null} - * - * @throws NullPointerException if {@code nonNullComparator} is - * {@code null} - **/ - public NullComparator(final Comparator nonNullComparator) { - this(nonNullComparator, true); - } - - /** - * Construct an instance that sorts {@code null} higher or lower than - * any non-{@code null} object it is compared with. When comparing - * two non-{@code null} objects, the {@link ComparableComparator} is - * used. - * - * @param nullsAreHigh a {@code true} value indicates that - * {@code null} should be compared as higher than a - * non-{@code null} object. A {@code false} value indicates - * that {@code null} should be compared as lower than a - * non-{@code null} object. - **/ - public NullComparator(final boolean nullsAreHigh) { - this(ComparatorUtils.NATURAL_COMPARATOR, nullsAreHigh); - } - - /** - * Construct an instance that sorts {@code null} higher or lower than - * any non-{@code null} object it is compared with. When comparing - * two non-{@code null} objects, the specified {@link Comparator} is - * used. - * - * @param nonNullComparator the comparator to use when comparing two - * non-{@code null} objects. This argument cannot be - * {@code null} - * - * @param nullsAreHigh a {@code true} value indicates that - * {@code null} should be compared as higher than a - * non-{@code null} object. A {@code false} value indicates - * that {@code null} should be compared as lower than a - * non-{@code null} object. - * - * @throws NullPointerException if {@code nonNullComparator} is - * {@code null} - **/ - public NullComparator(final Comparator nonNullComparator, final boolean nullsAreHigh) { - this.nonNullComparator = Objects.requireNonNull(nonNullComparator, "nonNullComparator"); - this.nullsAreHigh = nullsAreHigh; - } - - /** - * Perform a comparison between two objects. If both objects are - * {@code null}, a {@code 0} value is returned. If one object - * is {@code 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 {@code null}, an - * underlying comparator specified in the constructor (or the default) is - * used to compare the non-{@code null} objects. - * - * @param o1 the first object to compare - * @param o2 the object to compare it to. - * @return {@code -1} if {@code o1} is "lower" than (less than, - * before, etc.) {@code o2}; {@code 1} if {@code o1} is - * "higher" than (greater than, after, etc.) {@code o2}; or - * {@code 0} if {@code o1} and {@code o2} are equal. - **/ - @Override - 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 {@code true} if the specified object is a NullComparator - * with equivalent {@code null} comparison behavior - * (i.e. {@code null} high or low) and with equivalent underlying - * non-{@code 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); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/comparators/ReverseComparator.java b/src/main/java/repack/apache/commons/collections4/comparators/ReverseComparator.java deleted file mode 100644 index d3fcf1323a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/comparators/ReverseComparator.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.comparators; - -import java.io.Serializable; -import java.util.Comparator; - -import repack.apache.commons.collections4.ComparatorUtils; - -/** - * Reverses the order of another comparator by reversing the arguments - * to its {@link #compare(Object, Object) compare} method. - * - * @param the type of objects compared by this comparator - * - * @since 2.0 - * @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 {@code null}, - * the ReverseComparator defaults to reversing the - * natural order, as per {@link java.util.Collections#reverseOrder()}. - * - * @param comparator Comparator to reverse - */ - 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 - */ - @Override - 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 {@code true} iff that Object is - * a {@link Comparator} whose ordering is known to be - * equivalent to mine. - *

- * This implementation returns {@code true} - * iff {@code object.{@link Object#getClass() getClass()}} - * equals {@code 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/comparators/TransformingComparator.java b/src/main/java/repack/apache/commons/collections4/comparators/TransformingComparator.java deleted file mode 100644 index 0e848b5e77..0000000000 --- a/src/main/java/repack/apache/commons/collections4/comparators/TransformingComparator.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.comparators; - -import java.io.Serializable; -import java.util.Comparator; -import java.util.Objects; - -import repack.apache.commons.collections4.ComparatorUtils; -import repack.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. - *

- * - * @param the input type to the transformer - * @param the output type from the transformer - * - * @since 2.1 - * - * @see repack.apache.commons.collections4.Transformer - * @see repack.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 {@code compare} - */ - 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 {@code 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 - */ - @Override - 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 {@code true} iff that Object is - * a {@link Comparator} whose ordering is known to be - * equivalent to mine. - *

- * This implementation returns {@code true} - * iff {@code 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 Objects.equals(decorated, comp.decorated) && - Objects.equals(transformer, comp.transformer); - } - return false; - } - -} - diff --git a/src/main/java/repack/apache/commons/collections4/comparators/package-info.java b/src/main/java/repack/apache/commons/collections4/comparators/package-info.java deleted file mode 100644 index 1c7e5e80ca..0000000000 --- a/src/main/java/repack/apache/commons/collections4/comparators/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 repack.apache.commons.collections4.ComparatorUtils ComparatorUtils}, - * which is a single class that uses static methods to construct instances - * of the classes in this package. - * - */ -package repack.apache.commons.collections4.comparators; diff --git a/src/main/java/repack/apache/commons/collections4/functors/AbstractQuantifierPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/AbstractQuantifierPredicate.java deleted file mode 100644 index 5d98a7c277..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/AbstractQuantifierPredicate.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Predicate; - -/** - * Abstract base class for quantification predicates, e.g. All, Any, None. - * - * @since 4.0 - */ -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 - */ - @Override - public Predicate[] getPredicates() { - return FunctorUtils.copy(iPredicates); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/AllPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/AllPredicate.java deleted file mode 100644 index d9f808e7ad..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/AllPredicate.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import static repack.apache.commons.collections4.functors.FunctorUtils.coerce; -import static repack.apache.commons.collections4.functors.FunctorUtils.validate; -import static repack.apache.commons.collections4.functors.TruePredicate.truePredicate; - -import java.util.Collection; - -import repack.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 - */ -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 {@code all} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException if any predicate in the array is null - */ - public static Predicate allPredicate(final Predicate... predicates) { - 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 {@code all} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException 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 coerce(preds[0]); - } - return new AllPredicate<>(preds); - } - - /** - * Constructor that performs no validation. - * Use {@code 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 - */ - @Override - public boolean evaluate(final T object) { - for (final Predicate iPredicate : iPredicates) { - if (!iPredicate.evaluate(object)) { - return false; - } - } - return true; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/AndPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/AndPredicate.java deleted file mode 100644 index db751ea50e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/AndPredicate.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that returns true if both the predicates return true. - * - * @since 3.0 - */ -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 {@code and} predicate - * @throws NullPointerException if either predicate is null - */ - public static Predicate andPredicate(final Predicate predicate1, - final Predicate predicate2) { - return new AndPredicate<>(Objects.requireNonNull(predicate1, "predicate1"), - Objects.requireNonNull(predicate2, "predicate2")); - } - - /** - * Constructor that performs no validation. - * Use {@code 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) { - 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 - */ - @Override - 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 - */ - @Override - @SuppressWarnings("unchecked") - public Predicate[] getPredicates() { - return new Predicate[] {iPredicate1, iPredicate2}; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/AnyPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/AnyPredicate.java deleted file mode 100644 index 7f4a0bd38d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/AnyPredicate.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.util.Collection; - -import repack.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 - */ -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 {@code any} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException 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 {@code all} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException 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 {@code 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 - */ - @Override - public boolean evaluate(final T object) { - for (final Predicate iPredicate : iPredicates) { - if (iPredicate.evaluate(object)) { - return true; - } - } - return false; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/CatchAndRethrowClosure.java b/src/main/java/repack/apache/commons/collections4/functors/CatchAndRethrowClosure.java deleted file mode 100644 index b02d881b05..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/CatchAndRethrowClosure.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import repack.apache.commons.collections4.Closure; -import repack.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<String> strList = // some list
- * try {
- *     CollectionUtils.forAllDo(strList, writer);
- * } catch (FunctorException ex) {
- *     Throwable originalError = ex.getCause();
- *     // handle error
- * }
- * 
- * - * @since 4.0 - */ -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. - */ - @Override - 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; -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ChainedClosure.java b/src/main/java/repack/apache/commons/collections4/functors/ChainedClosure.java deleted file mode 100644 index b19fa47ea3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ChainedClosure.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Objects; - -import repack.apache.commons.collections4.Closure; - -/** - * Closure implementation that chains the specified closures together. - * - * @since 3.0 - */ -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 {@code chained} closure - * @throws NullPointerException if the closures array is null - * @throws NullPointerException 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 {@code chained} closure - * @throws NullPointerException if the closures collection is null - * @throws NullPointerException if any closure in the collection is null - */ - @SuppressWarnings("unchecked") - public static Closure chainedClosure(final Collection> closures) { - Objects.requireNonNull(closures, "closures"); - if (closures.isEmpty()) { - 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) { - iClosures = clone ? FunctorUtils.copy(closures) : closures; - } - - /** - * Constructor that performs no validation. - * Use {@code 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 - */ - @Override - 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ChainedTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/ChainedTransformer.java deleted file mode 100644 index 3ccc596d80..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ChainedTransformer.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Objects; - -import repack.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 - */ -public class ChainedTransformer implements Transformer, Serializable { - - private static final Transformer[] EMPTY_TRANSFORMER_ARRAY = {}; - - /** 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 {@code chained} transformer - * @throws NullPointerException if the transformers array is null - * @throws NullPointerException 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 {@code chained} transformer - * @throws NullPointerException if the transformers collection is null - * @throws NullPointerException if any transformer in the collection is null - */ - public static Transformer chainedTransformer( - final Collection> transformers) { - Objects.requireNonNull(transformers, "transformers"); - if (transformers.isEmpty()) { - return NOPTransformer.nopTransformer(); - } - // convert to array like this to guarantee iterator() ordering - final Transformer[] cmds = transformers.toArray(EMPTY_TRANSFORMER_ARRAY); - 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) { - iTransformers = clone ? FunctorUtils.copy(transformers) : transformers; - } - - /** - * Constructor that performs no validation. - * Use {@code 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 - */ - @Override - 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/CloneTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/CloneTransformer.java deleted file mode 100644 index 3b78464efb..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/CloneTransformer.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation that returns a clone of the input object. - *

- * Clone is performed using {@code PrototypeFactory.prototypeFactory(input).create()}. - *

- *

- * WARNING: from v4.1 onwards this class will not be serializable anymore - * in order to prevent potential remote code execution exploits. Please refer to - * COLLECTIONS-580 - * for more details. - *

- * - * @since 3.0 - */ -public class CloneTransformer implements Transformer { - - /** 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 - */ - public static Transformer cloneTransformer() { - return INSTANCE; - } - - /** - * Constructor. - */ - private CloneTransformer() { - } - - /** - * Transforms the input to result by cloning it. - * - * @param input the input object to transform - * @return the transformed result - */ - @Override - public T transform(final T input) { - if (input == null) { - return null; - } - return PrototypeFactory.prototypeFactory(input).create(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ClosureTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/ClosureTransformer.java deleted file mode 100644 index 21e85d8b79..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ClosureTransformer.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Closure; -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation that calls a Closure using the input object - * and then returns the input. - * - * @since 3.0 - */ -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 {@code closure} transformer - * @throws NullPointerException if the closure is null - */ - public static Transformer closureTransformer(final Closure closure) { - return new ClosureTransformer<>(Objects.requireNonNull(closure, "closure")); - } - - /** - * Constructor that performs no validation. - * Use {@code closureTransformer} if you want that. - * - * @param closure the closure to call, not null - */ - public ClosureTransformer(final Closure closure) { - iClosure = closure; - } - - /** - * Transforms the input to result by executing a closure. - * - * @param input the input object to transform - * @return the transformed result - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ComparatorPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/ComparatorPredicate.java deleted file mode 100644 index 54818ede60..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ComparatorPredicate.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Comparator; -import java.util.Objects; - -import repack.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 {@code ComparatorPredicate} can be used used in the - * following way:

- * - *
- * ComparatorPredicate.comparatorPredicate(ONE, comparator).evaluate(TWO);
- * 
- * - *

The input variable {@code TWO} in compared to the stored variable {@code ONE} using - * the supplied {@code comparator}. This is the default usage of the predicate and will return - * {@code true} if the underlying comparator returns {@code 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 {@code comparator} - * using the {@code GREATER} evaluation criterion constant. This instructs the predicate to - * return {@code true} if the comparator returns a value greater than {@code 0}.

- * - * @since 4.0 - */ -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 NullPointerException 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 NullPointerException if comparator or criterion is null - */ - public static Predicate comparatorPredicate(final T object, final Comparator comparator, - final Criterion criterion) { - return new ComparatorPredicate<>(object, Objects.requireNonNull(comparator, "comparator"), - Objects.requireNonNull(criterion, "criterion")); - } - - /** - * Constructor that performs no validation. - * Use {@code 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) { - this.object = object; - this.comparator = comparator; - this.criterion = criterion; - } - - /** - * Evaluates the predicate. The predicate evaluates to {@code true} in the following cases: - * - *
    - *
  • {@code comparator.compare(object, input) == 0 && criterion == EQUAL}
  • - *
  • {@code comparator.compare(object, input) < 0 && criterion == LESS}
  • - *
  • {@code comparator.compare(object, input) > 0 && criterion == GREATER}
  • - *
  • {@code comparator.compare(object, input) >= 0 && criterion == GREATER_OR_EQUAL}
  • - *
  • {@code comparator.compare(object, input) <= 0 && criterion == LESS_OR_EQUAL}
  • - *
- * - * @see repack.apache.commons.collections4.Predicate#evaluate(Object) - * @see java.util.Comparator#compare(Object first, 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) - */ - @Override - 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; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ConstantFactory.java b/src/main/java/repack/apache/commons/collections4/functors/ConstantFactory.java deleted file mode 100644 index 6ad427c56e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ConstantFactory.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.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 - */ -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 {@code constant} factory. - */ - public static Factory constantFactory(final T constantToReturn) { - if (constantToReturn == null) { - return NULL_INSTANCE; - } - return new ConstantFactory<>(constantToReturn); - } - - /** - * Constructor that performs no validation. - * Use {@code constantFactory} if you want that. - * - * @param constantToReturn the constant to return each time - */ - public ConstantFactory(final T constantToReturn) { - iConstant = constantToReturn; - } - - /** - * Always return constant. - * - * @return the stored constant value - */ - @Override - public T create() { - return iConstant; - } - - /** - * Gets the constant. - * - * @return the constant - * @since 3.1 - */ - public T getConstant() { - return iConstant; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ConstantTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/ConstantTransformer.java deleted file mode 100644 index be6b9a7260..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ConstantTransformer.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.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 - */ -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<I, O> that always returns null. - */ - public static Transformer nullTransformer() { - return 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 {@code constant} factory. - */ - public static Transformer constantTransformer(final O constantToReturn) { - if (constantToReturn == null) { - return nullTransformer(); - } - return new ConstantTransformer<>(constantToReturn); - } - - /** - * Constructor that performs no validation. - * Use {@code constantTransformer} if you want that. - * - * @param constantToReturn the constant to return each time - */ - public ConstantTransformer(final O constantToReturn) { - 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 - */ - @Override - 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)) { - 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; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/DefaultEquator.java b/src/main/java/repack/apache/commons/collections4/functors/DefaultEquator.java deleted file mode 100644 index 8029017f68..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/DefaultEquator.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Equator; - -/** - * Default {@link Equator} implementation. - * - * @param the types of object this {@link Equator} can evaluate. - * @since 4.0 - */ -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 {@code null} objects. - */ - public static final int HASHCODE_NULL = -1; - - /** - * Factory returning the typed singleton instance. - * - * @param the object type - * @return the singleton instance - */ - public static DefaultEquator defaultEquator() { - return DefaultEquator.INSTANCE; - } - - /** - * Restricted constructor. - */ - private DefaultEquator() { - } - - /** - * {@inheritDoc} Delegates to {@link Objects#equals(Object, Object)}. - */ - @Override - public boolean equate(final T o1, final T o2) { - return Objects.equals(o1, o2); - } - - /** - * {@inheritDoc} - * - * @return {@code o.hashCode()} if {@code o} is non- - * {@code null}, else {@link #HASHCODE_NULL}. - */ - @Override - public int hash(final T o) { - return o == null ? HASHCODE_NULL : o.hashCode(); - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/EqualPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/EqualPredicate.java deleted file mode 100644 index f410207506..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/EqualPredicate.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Equator; -import repack.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 - */ -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 - */ - public static Predicate equalPredicate(final T object) { - if (object == null) { - return NullPredicate.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 - * @since 4.0 - */ - public static Predicate equalPredicate(final T object, final Equator equator) { - if (object == null) { - return NullPredicate.nullPredicate(); - } - return new EqualPredicate<>(object, equator); - } - - /** - * Constructor that performs no validation. - * Use {@code 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 {@code 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) { - 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 - */ - @Override - public boolean evaluate(final T object) { - if (equator != null) { - return equator.equate(iValue, object); - } - return iValue.equals(object); - } - - /** - * Gets the value. - * - * @return the value - * @since 3.1 - */ - public Object getValue() { - return iValue; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ExceptionClosure.java b/src/main/java/repack/apache/commons/collections4/functors/ExceptionClosure.java deleted file mode 100644 index a7bc3ede09..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ExceptionClosure.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Closure; -import repack.apache.commons.collections4.FunctorException; - -/** - * Closure implementation that always throws an exception. - * - * @since 3.0 - */ -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 - */ - public static Closure exceptionClosure() { - return INSTANCE; - } - - /** - * Restricted constructor. - */ - private ExceptionClosure() { - } - - /** - * Always throw an exception. - * - * @param input the input object - * @throws FunctorException always - */ - @Override - public void execute(final E input) { - throw new FunctorException("ExceptionClosure invoked"); - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ExceptionFactory.java b/src/main/java/repack/apache/commons/collections4/functors/ExceptionFactory.java deleted file mode 100644 index 533f9110b5..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ExceptionFactory.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Factory; -import repack.apache.commons.collections4.FunctorException; - -/** - * Factory implementation that always throws an exception. - * - * @since 3.0 - */ -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 - */ - public static Factory exceptionFactory() { - return INSTANCE; - } - - /** - * Restricted constructor. - */ - private ExceptionFactory() { - } - - /** - * Always throws an exception. - * - * @return never - * @throws FunctorException always - */ - @Override - public T create() { - throw new FunctorException("ExceptionFactory invoked"); - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ExceptionPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/ExceptionPredicate.java deleted file mode 100644 index 5201ba5f7a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ExceptionPredicate.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.FunctorException; -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that always throws an exception. - * - * @since 3.0 - */ -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 - */ - public static Predicate exceptionPredicate() { - return INSTANCE; - } - - /** - * Restricted constructor. - */ - private ExceptionPredicate() { - } - - /** - * Evaluates the predicate always throwing an exception. - * - * @param object the input object - * @return never - * @throws FunctorException always - */ - @Override - public boolean evaluate(final T object) { - throw new FunctorException("ExceptionPredicate invoked"); - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ExceptionTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/ExceptionTransformer.java deleted file mode 100644 index 9bfc646e53..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ExceptionTransformer.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.FunctorException; -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation that always throws an exception. - * - * @since 3.0 - */ -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 - */ - public static Transformer exceptionTransformer() { - return INSTANCE; - } - - /** - * Restricted constructor. - */ - private ExceptionTransformer() { - } - - /** - * Transforms the input to result by cloning it. - * - * @param input the input object to transform - * @return never - * @throws FunctorException always - */ - @Override - public O transform(final I input) { - throw new FunctorException("ExceptionTransformer invoked"); - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/FactoryTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/FactoryTransformer.java deleted file mode 100644 index bfc3cd0c0b..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/FactoryTransformer.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Factory; -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation that calls a Factory and returns the result. - * - * @since 3.0 - */ -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 {@code factory} transformer - * @throws NullPointerException if the factory is null - */ - public static Transformer factoryTransformer(final Factory factory) { - return new FactoryTransformer<>(Objects.requireNonNull(factory, "factory")); - } - - /** - * Constructor that performs no validation. - * Use {@code factoryTransformer} if you want that. - * - * @param factory the factory to call, not null - */ - public FactoryTransformer(final Factory factory) { - 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 - */ - @Override - public O transform(final I input) { - return iFactory.create(); - } - - /** - * Gets the factory. - * - * @return the factory - * @since 3.1 - */ - public Factory getFactory() { - return iFactory; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/FalsePredicate.java b/src/main/java/repack/apache/commons/collections4/functors/FalsePredicate.java deleted file mode 100644 index 42b54a1d2a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/FalsePredicate.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that always returns false. - * - * @since 3.0 - */ -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 - */ - public static Predicate falsePredicate() { - return INSTANCE; - } - - /** - * Restricted constructor. - */ - private FalsePredicate() { - } - - /** - * Evaluates the predicate returning false always. - * - * @param object the input object - * @return false always - */ - @Override - public boolean evaluate(final T object) { - return false; - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/ForClosure.java b/src/main/java/repack/apache/commons/collections4/functors/ForClosure.java deleted file mode 100644 index 10193b7493..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/ForClosure.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import repack.apache.commons.collections4.Closure; - -/** - * Closure implementation that calls another closure n times, like a for loop. - *

- * WARNING: from v4.1 onwards this class will not be serializable anymore - * in order to prevent potential remote code execution exploits. Please refer to - * COLLECTIONS-580 - * for more details. - *

- * - * @since 3.0 - */ -public class ForClosure implements Closure { - - /** 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 {@code 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 {@code 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 {@code 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) { - iCount = count; - iClosure = closure; - } - - /** - * Executes the closure {@code count} times. - * - * @param input the input object - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/FunctorUtils.java b/src/main/java/repack/apache/commons/collections4/functors/FunctorUtils.java deleted file mode 100644 index f8ec605cae..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/FunctorUtils.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.util.Collection; -import java.util.Objects; - -import repack.apache.commons.collections4.Closure; -import repack.apache.commons.collections4.Predicate; -import repack.apache.commons.collections4.Transformer; - -/** - * Internal utilities for functors. - * - * @since 3.0 - */ -class FunctorUtils { - - /** - * Restricted constructor. - */ - private FunctorUtils() { - } - - /** - * 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) { - Objects.requireNonNull(predicates, "predicates"); - for (int i = 0; i < predicates.length; i++) { - if (predicates[i] == null) { - throw new NullPointerException("predicates[" + i + "]"); - } - } - } - - /** - * Validate the predicates to ensure that all is well. - * - * @param predicates the predicates to validate - * @return predicate array - */ - static Predicate[] validate(final Collection> predicates) { - Objects.requireNonNull(predicates, "predicates"); - // 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 NullPointerException("predicates[" + i + "]"); - } - 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) { - Objects.requireNonNull(closures, "closures"); - for (int i = 0; i < closures.length; i++) { - if (closures[i] == null) { - throw new NullPointerException("closures[" + i + "]"); - } - } - } - - /** - * A very simple method that coerces Closure to Closure. - *

This method exists - * simply as centralized 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) { - Objects.requireNonNull(transformers, "transformers"); - for (int i = 0; i < transformers.length; i++) { - if (transformers[i] == null) { - throw new NullPointerException("transformers[" + i + "]"); - } - } - } - - /** - * 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 the type of object the returned transformer should "produce" - * @param transformer the transformer to coerce. - * @return the coerced transformer. - */ - @SuppressWarnings("unchecked") - static Transformer coerce(final Transformer transformer) { - return (Transformer) transformer; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/IdentityPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/IdentityPredicate.java deleted file mode 100644 index 468d98a9f9..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/IdentityPredicate.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.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 - */ -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 - */ - public static Predicate identityPredicate(final T object) { - if (object == null) { - return NullPredicate.nullPredicate(); - } - return new IdentityPredicate<>(object); - } - - /** - * Constructor that performs no validation. - * Use {@code identityPredicate} if you want that. - * - * @param object the object to compare to - */ - public IdentityPredicate(final T object) { - 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 - */ - @Override - public boolean evaluate(final T object) { - return iValue == object; - } - - /** - * Gets the value. - * - * @return the value - * @since 3.1 - */ - public T getValue() { - return iValue; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/IfClosure.java b/src/main/java/repack/apache/commons/collections4/functors/IfClosure.java deleted file mode 100644 index e588ec0417..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/IfClosure.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Closure; -import repack.apache.commons.collections4.Predicate; - -/** - * Closure implementation acts as an if statement calling one or other closure - * based on a predicate. - * - * @since 3.0 - */ -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 {@code if} closure - * @throws NullPointerException 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 {@code if} closure - * @throws NullPointerException if any argument is null - */ - public static Closure ifClosure(final Predicate predicate, - final Closure trueClosure, - final Closure falseClosure) { - return new IfClosure<>(Objects.requireNonNull(predicate, "predicate"), - Objects.requireNonNull(trueClosure, "trueClosure"), - Objects.requireNonNull(falseClosure, "falseClosure")); - } - - /** - * Constructor that performs no validation. - * Use {@code 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 {@code 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) { - iPredicate = predicate; - iTrueClosure = trueClosure; - iFalseClosure = falseClosure; - } - - /** - * Executes the true or false closure according to the result of the predicate. - * - * @param input the input object - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/IfTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/IfTransformer.java deleted file mode 100644 index 16035b33c8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/IfTransformer.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Predicate; -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation that will call one of two closures based on whether a predicate evaluates - * as true or false. - * - * @param The input type for the transformer - * @param The output type for the transformer - * - * @since 4.1 - */ -public class IfTransformer implements Transformer, Serializable { - - /** Serial version UID */ - private static final long serialVersionUID = 8069309411242014252L; - - /** The test */ - private final Predicate iPredicate; - /** The transformer to use if true */ - private final Transformer iTrueTransformer; - /** The transformer to use if false */ - private final Transformer iFalseTransformer; - - /** - * Factory method that performs validation. - * - * @param input type for the transformer - * @param output type for the transformer - * @param predicate predicate to switch on - * @param trueTransformer transformer used if true - * @param falseTransformer transformer used if false - * @return the {@code if} transformer - * @throws NullPointerException if either argument is null - */ - public static Transformer ifTransformer(final Predicate predicate, - final Transformer trueTransformer, - final Transformer falseTransformer) { - return new IfTransformer<>(Objects.requireNonNull(predicate, "predicate"), - Objects.requireNonNull(trueTransformer, "trueTransformer"), - Objects.requireNonNull(falseTransformer, "falseTransformer")); - } - - /** - * Factory method that performs validation. - *

- * This factory creates a transformer that just returns the input object when - * the predicate is false. - * - * @param input and output type for the transformer - * @param predicate predicate to switch on - * @param trueTransformer transformer used if true - * @return the {@code if} transformer - * @throws NullPointerException if either argument is null - */ - public static Transformer ifTransformer( - final Predicate predicate, - final Transformer trueTransformer) { - return new IfTransformer<>(Objects.requireNonNull(predicate, "predicate"), - Objects.requireNonNull(trueTransformer, "trueTransformer"), NOPTransformer.nopTransformer()); - } - - /** - * Constructor that performs no validation. - * Use the static factory method {@code ifTransformer} if you want that. - * - * @param predicate predicate to switch on, not null - * @param trueTransformer transformer used if true, not null - * @param falseTransformer transformer used if false, not null - */ - public IfTransformer(final Predicate predicate, - final Transformer trueTransformer, - final Transformer falseTransformer) { - - iPredicate = predicate; - iTrueTransformer = trueTransformer; - iFalseTransformer = falseTransformer; - } - - /** - * Transforms the input using the true or false transformer based to the result of the predicate. - * - * @param input the input object to transform - * @return the transformed result - */ - @Override - public O transform(final I input) { - if (iPredicate.evaluate(input)){ - return iTrueTransformer.transform(input); - } - return iFalseTransformer.transform(input); - } - - /** - * Gets the predicate. - * - * @return the predicate - */ - public Predicate getPredicate(){ - return iPredicate; - } - - /** - * Gets the transformer used when true. - * - * @return the transformer - */ - public Transformer getTrueTransformer() { - return iTrueTransformer; - } - - /** - * Gets the transformer used when false. - * - * @return the transformer - */ - public Transformer getFalseTransformer() { - return iFalseTransformer; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/InstanceofPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/InstanceofPredicate.java deleted file mode 100644 index 0f6b379e70..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/InstanceofPredicate.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that returns true if the input is an instanceof - * the type stored in this predicate. - * - * @since 3.0 - */ -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 NullPointerException if the class is null - */ - public static Predicate instanceOfPredicate(final Class type) { - return new InstanceofPredicate(Objects.requireNonNull(type, "type")); - } - - /** - * Constructor that performs no validation. - * Use {@code instanceOfPredicate} if you want that. - * - * @param type the type to check for - */ - public InstanceofPredicate(final Class type) { - 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 - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/InstantiateFactory.java b/src/main/java/repack/apache/commons/collections4/functors/InstantiateFactory.java deleted file mode 100644 index c49e10ab31..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/InstantiateFactory.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.Objects; - -import repack.apache.commons.collections4.Factory; -import repack.apache.commons.collections4.FunctorException; - -/** - * Factory implementation that creates a new object instance by reflection. - *

- * WARNING: from v4.1 onwards this class will not be serializable anymore - * in order to prevent potential remote code execution exploits. Please refer to - * COLLECTIONS-580 - * for more details. - *

- * - * @since 3.0 - */ -public class InstantiateFactory implements Factory { - - /** 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; - - /** - * 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 - * @throws NullPointerException if classToInstantiate is null - * @throws IllegalArgumentException if paramTypes does not match args - */ - public static Factory instantiateFactory(final Class classToInstantiate, - final Class[] paramTypes, - final Object[] args) { - Objects.requireNonNull(classToInstantiate, "classToInstantiate"); - 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 {@code instantiateFactory} if you want that. - * - * @param classToInstantiate the class to instantiate - */ - public InstantiateFactory(final Class classToInstantiate) { - iClassToInstantiate = classToInstantiate; - iParamTypes = null; - iArgs = null; - findConstructor(); - } - - /** - * Constructor that performs no validation. - * Use {@code 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) { - 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 - */ - @Override - 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); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/InstantiateTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/InstantiateTransformer.java deleted file mode 100644 index 07d32a14f2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/InstantiateTransformer.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import repack.apache.commons.collections4.FunctorException; -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation that creates a new object instance by reflection. - *

- * WARNING: from v4.1 onwards this class will not be serializable anymore - * in order to prevent potential remote code execution exploits. Please refer to - * COLLECTIONS-580 - * for more details. - *

- * - * @since 3.0 - */ -public class InstantiateTransformer implements Transformer, T> { - - /** 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<Class<? extends T>, T> - */ - public static Transformer, T> instantiateTransformer() { - return 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 - * @throws IllegalArgumentException if paramTypes does not match args - */ - 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() { - iParamTypes = null; - iArgs = null; - } - - /** - * Constructor that performs no validation. - * Use {@code 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) { - 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 - */ - @Override - 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); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/InvokerTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/InvokerTransformer.java deleted file mode 100644 index 94e1ef18b2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/InvokerTransformer.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Objects; - -import repack.apache.commons.collections4.FunctorException; -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation that creates a new object instance by reflection. - *

- * WARNING: from v4.1 onwards this class will not be serializable anymore - * in order to prevent potential remote code execution exploits. Please refer to - * COLLECTIONS-580 - * for more details. - *

- * - * @since 3.0 - */ -public class InvokerTransformer implements Transformer { - - /** 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 - * @throws NullPointerException if methodName is null - * @since 3.1 - */ - public static Transformer invokerTransformer(final String methodName) { - return new InvokerTransformer<>(Objects.requireNonNull(methodName, "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 - * @throws NullPointerException if methodName is null - * @throws IllegalArgumentException if paramTypes does not match args - */ - public static Transformer invokerTransformer(final String methodName, final Class[] paramTypes, - final Object[] args) { - Objects.requireNonNull(methodName, "methodName"); - 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) { - iMethodName = methodName; - iParamTypes = null; - iArgs = null; - } - - /** - * Constructor that performs no validation. - * Use {@code 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) { - 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 - */ - @Override - @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); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/MapTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/MapTransformer.java deleted file mode 100644 index 1923998308..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/MapTransformer.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Map; - -import repack.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 - */ -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 {@code mapTransformer} if you want that. - * - * @param map the map to use for lookup, not cloned - */ - private MapTransformer(final Map map) { - iMap = map; - } - - /** - * Transforms the input to result by looking it up in a {@code Map}. - * - * @param input the input object to transform - * @return the transformed result - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/NOPClosure.java b/src/main/java/repack/apache/commons/collections4/functors/NOPClosure.java deleted file mode 100644 index 333772b08f..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/NOPClosure.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Closure; - -/** - * Closure implementation that does nothing. - * - * @since 3.0 - */ -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 - */ - public static Closure nopClosure() { - return INSTANCE; - } - - /** - * Constructor. - */ - private NOPClosure() { - } - - /** - * Do nothing. - * - * @param input the input object - */ - @Override - public void execute(final E input) { - // do nothing - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/NOPTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/NOPTransformer.java deleted file mode 100644 index 678e388289..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/NOPTransformer.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation that does nothing. - * - * @since 3.0 - */ -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 - */ - public static Transformer nopTransformer() { - return INSTANCE; - } - - /** - * Constructor. - */ - private NOPTransformer() { - } - - /** - * Transforms the input to result by doing nothing. - * - * @param input the input object to transform - * @return the transformed result which is the input - */ - @Override - public T transform(final T input) { - return input; - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/NonePredicate.java b/src/main/java/repack/apache/commons/collections4/functors/NonePredicate.java deleted file mode 100644 index 91a66c6f28..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/NonePredicate.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.util.Collection; - -import repack.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 - */ -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 {@code any} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException 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 {@code one} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException 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 {@code 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 - */ - @Override - public boolean evaluate(final T object) { - for (final Predicate iPredicate : iPredicates) { - if (iPredicate.evaluate(object)) { - return false; - } - } - return true; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/NotNullPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/NotNullPredicate.java deleted file mode 100644 index 12b37e0570..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/NotNullPredicate.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that returns true if the input is not null. - * - * @since 3.0 - */ -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 - */ - public static Predicate notNullPredicate() { - return INSTANCE; - } - - /** - * Restricted constructor. - */ - private NotNullPredicate() { - } - - /** - * Evaluates the predicate returning true if the object does not equal null. - * - * @param object the object to evaluate - * @return true if not null - */ - @Override - public boolean evaluate(final T object) { - return object != null; - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/NotPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/NotPredicate.java deleted file mode 100644 index 6a4cd2ebba..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/NotPredicate.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that returns the opposite of the decorated predicate. - * - * @since 3.0 - */ -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 NullPointerException if the predicate is null - */ - public static Predicate notPredicate(final Predicate predicate) { - return new NotPredicate<>(Objects.requireNonNull(predicate, "predicate")); - } - - /** - * Constructor that performs no validation. - * Use {@code notPredicate} if you want that. - * - * @param predicate the predicate to call after the null check - */ - public NotPredicate(final Predicate predicate) { - iPredicate = predicate; - } - - /** - * Evaluates the predicate returning the opposite to the stored predicate. - * - * @param object the input object - * @return true if predicate returns false - */ - @Override - 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 - */ - @Override - @SuppressWarnings("unchecked") - public Predicate[] getPredicates() { - return new Predicate[] {iPredicate}; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/NullIsExceptionPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/NullIsExceptionPredicate.java deleted file mode 100644 index d7e58fc961..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/NullIsExceptionPredicate.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.FunctorException; -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that throws an exception if the input is null. - * - * @since 3.0 - */ -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 NullPointerException if the predicate is null - */ - public static Predicate nullIsExceptionPredicate(final Predicate predicate) { - return new NullIsExceptionPredicate<>(Objects.requireNonNull(predicate, "predicate")); - } - - /** - * Constructor that performs no validation. - * Use {@code nullIsExceptionPredicate} if you want that. - * - * @param predicate the predicate to call after the null check - */ - public NullIsExceptionPredicate(final Predicate predicate) { - 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 - */ - @Override - 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 - */ - @Override - @SuppressWarnings("unchecked") - public Predicate[] getPredicates() { - return new Predicate[] { iPredicate }; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/NullIsFalsePredicate.java b/src/main/java/repack/apache/commons/collections4/functors/NullIsFalsePredicate.java deleted file mode 100644 index 6bdbdc9b21..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/NullIsFalsePredicate.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that returns false if the input is null. - * - * @since 3.0 - */ -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 NullPointerException if the predicate is null - */ - public static Predicate nullIsFalsePredicate(final Predicate predicate) { - return new NullIsFalsePredicate<>(Objects.requireNonNull(predicate, "predicate")); - } - - /** - * Constructor that performs no validation. - * Use {@code nullIsFalsePredicate} if you want that. - * - * @param predicate the predicate to call after the null check - */ - public NullIsFalsePredicate(final Predicate predicate) { - 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 - */ - @Override - 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 - */ - @Override - @SuppressWarnings("unchecked") - public Predicate[] getPredicates() { - return new Predicate[] { iPredicate }; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/NullIsTruePredicate.java b/src/main/java/repack/apache/commons/collections4/functors/NullIsTruePredicate.java deleted file mode 100644 index 58ab18ade2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/NullIsTruePredicate.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that returns true if the input is null. - * - * @since 3.0 - */ -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 NullPointerException if the predicate is null - */ - public static Predicate nullIsTruePredicate(final Predicate predicate) { - return new NullIsTruePredicate<>(Objects.requireNonNull(predicate, "predicate")); - } - - /** - * Constructor that performs no validation. - * Use {@code nullIsTruePredicate} if you want that. - * - * @param predicate the predicate to call after the null check - */ - public NullIsTruePredicate(final Predicate predicate) { - 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 - */ - @Override - 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 - */ - @Override - @SuppressWarnings("unchecked") - public Predicate[] getPredicates() { - return new Predicate[] { iPredicate }; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/NullPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/NullPredicate.java deleted file mode 100644 index e6e0e51837..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/NullPredicate.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that returns true if the input is null. - * - * @since 3.0 - */ -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 - */ - public static Predicate nullPredicate() { - return INSTANCE; - } - - /** - * Restricted constructor. - */ - private NullPredicate() { - } - - /** - * Evaluates the predicate returning true if the input is null. - * - * @param object the input object - * @return true if input is null - */ - @Override - public boolean evaluate(final T object) { - return object == null; - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/OnePredicate.java b/src/main/java/repack/apache/commons/collections4/functors/OnePredicate.java deleted file mode 100644 index d754f904b0..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/OnePredicate.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.util.Collection; - -import repack.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 - */ -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 {@code any} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException 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 {@code one} predicate - * @throws NullPointerException if the predicates array is null - * @throws NullPointerException 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 {@code 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 - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/OrPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/OrPredicate.java deleted file mode 100644 index 69f14ab315..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/OrPredicate.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that returns true if either of the predicates return true. - * - * @since 3.0 - */ -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 {@code and} predicate - * @throws NullPointerException if either predicate is null - */ - public static Predicate orPredicate(final Predicate predicate1, - final Predicate predicate2) { - return new OrPredicate<>(Objects.requireNonNull(predicate1, "predicate1"), - Objects.requireNonNull(predicate2, "predicate2")); - } - - /** - * Constructor that performs no validation. - * Use {@code 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) { - 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 - */ - @Override - 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 - */ - @Override - @SuppressWarnings("unchecked") - public Predicate[] getPredicates() { - return new Predicate[] {iPredicate1, iPredicate2}; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/PredicateDecorator.java b/src/main/java/repack/apache/commons/collections4/functors/PredicateDecorator.java deleted file mode 100644 index 40b9834b09..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/PredicateDecorator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import repack.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 - */ -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(); - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/PredicateTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/PredicateTransformer.java deleted file mode 100644 index 2fd7d15704..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/PredicateTransformer.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Predicate; -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation that calls a Predicate using the input object - * and then returns the result. - * - * @since 3.0 - */ -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 {@code 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 {@code predicateTransformer} if you want that. - * - * @param predicate the predicate to call, not null - */ - public PredicateTransformer(final Predicate predicate) { - iPredicate = predicate; - } - - /** - * Transforms the input to result by calling a predicate. - * - * @param input the input object to transform - * @return the transformed result - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/PrototypeFactory.java b/src/main/java/repack/apache/commons/collections4/functors/PrototypeFactory.java deleted file mode 100644 index f907b3c082..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/PrototypeFactory.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.Factory; -import repack.apache.commons.collections4.FunctorException; - -/** - * Factory implementation that creates a new instance each time based on a prototype. - *

- * WARNING: from v4.1 onwards {@link Factory} instances returned by - * {@link #prototypeFactory(Object)} will not be serializable anymore in order - * to prevent potential remote code execution exploits. Please refer to - * COLLECTIONS-580 - * for more details. - *

- * - * @since 3.0 - */ -public class PrototypeFactory { - - /** - * Factory method that performs validation. - *

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

- * - *
    - *
  • public clone method
  • - *
  • public copy constructor
  • - *
  • serialization clone
  • - *
- * - * @param the type the factory creates - * @param prototype the object to clone each time in the factory - * @return the {@code 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(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() { - } - - // PrototypeCloneFactory - /** - * PrototypeCloneFactory creates objects by copying a prototype using the clone method. - */ - static class PrototypeCloneFactory implements Factory { - - /** 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) { - 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 - */ - @Override - @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 { - - /** The object to clone via serialization each time */ - private final T iPrototype; - - /** - * Constructor to store prototype - */ - private PrototypeSerializationFactory(final T prototype) { - iPrototype = prototype; - } - - /** - * Creates an object using serialization. - * - * @return the new object - */ - @Override - @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 | IOException ex) { - throw new FunctorException(ex); - } finally { - try { - if (bais != null) { - bais.close(); - } - } catch (final IOException ex) { //NOPMD - // ignore - } - try { - baos.close(); - } catch (final IOException ex) { //NOPMD - // ignore - } - } - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/StringValueTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/StringValueTransformer.java deleted file mode 100644 index fab4d1bfd1..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/StringValueTransformer.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation that returns the result of calling - * {@code String.valueOf} on the input object. - * - * @since 3.0 - */ -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() { - } - - /** - * Transforms the input to result by calling {@code String.valueOf}. - * - * @param input the input object to transform - * @return the transformed result - */ - @Override - public String transform(final T input) { - return String.valueOf(input); - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/SwitchClosure.java b/src/main/java/repack/apache/commons/collections4/functors/SwitchClosure.java deleted file mode 100644 index 2f27500c1e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/SwitchClosure.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Map; -import java.util.Objects; - -import repack.apache.commons.collections4.Closure; -import repack.apache.commons.collections4.Predicate; - -/** - * Closure implementation calls the closure whose predicate returns true, - * like a switch statement. - * - * @since 3.0 - */ -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 {@code chained} closure - * @throws NullPointerException if array is null - * @throws NullPointerException if any element in the array is null - * @throws IllegalArgumentException if the array lengths of predicates and closures do not match - */ - @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 {@code switch} closure - * @throws NullPointerException if the map is null - * @throws NullPointerException 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) { - Objects.requireNonNull(predicatesAndClosures, "predicatesAndClosures"); - // 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) { - iPredicates = clone ? FunctorUtils.copy(predicates) : predicates; - iClosures = clone ? FunctorUtils.copy(closures) : closures; - iDefault = defaultClosure == null ? NOPClosure.nopClosure() : defaultClosure; - } - - /** - * Constructor that performs no validation. - * Use {@code 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 - */ - @Override - public void execute(final E input) { - for (int i = 0; i < iPredicates.length; i++) { - if (iPredicates[i].evaluate(input)) { - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/SwitchTransformer.java b/src/main/java/repack/apache/commons/collections4/functors/SwitchTransformer.java deleted file mode 100644 index 3d8675c457..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/SwitchTransformer.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Map; -import java.util.Objects; - -import repack.apache.commons.collections4.Predicate; -import repack.apache.commons.collections4.Transformer; - -/** - * Transformer implementation calls the transformer whose predicate returns true, - * like a switch statement. - * - * @since 3.0 - */ -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 {@code chained} transformer - * @throws NullPointerException if either array is null - * @throws NullPointerException if any element in the arrays is null - * @throws IllegalArgumentException if the arrays have different sizes - */ - @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 {@code switch} transformer - * @throws NullPointerException if the map is null - * @throws NullPointerException 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) { - - Objects.requireNonNull(map, "map"); - if (map.isEmpty()) { - 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) { - iPredicates = clone ? FunctorUtils.copy(predicates) : predicates; - iTransformers = clone ? FunctorUtils.copy(transformers) : transformers; - iDefault = defaultTransformer == null ? - ConstantTransformer.nullTransformer() : defaultTransformer; - } - - /** - * Constructor that performs no validation. - * Use {@code 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 - */ - @Override - public O transform(final I input) { - for (int i = 0; i < iPredicates.length; i++) { - if (iPredicates[i].evaluate(input)) { - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/TransformedPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/TransformedPredicate.java deleted file mode 100644 index ca00ebc12a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/TransformedPredicate.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.Predicate; -import repack.apache.commons.collections4.Transformer; - -/** - * Predicate implementation that transforms the given object before invoking - * another {@code Predicate}. - * - * @since 3.1 - */ -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 NullPointerException if the transformer or the predicate is null - */ - public static Predicate transformedPredicate(final Transformer transformer, - final Predicate predicate) { - return new TransformedPredicate<>(Objects.requireNonNull(transformer, "transformer"), - Objects.requireNonNull(predicate, "predicate")); - } - - /** - * Constructor that performs no validation. - * Use {@code 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 - */ - @Override - 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 - */ - @Override - @SuppressWarnings("unchecked") - public Predicate[] getPredicates() { - return new Predicate[] {iPredicate}; - } - - /** - * Gets the transformer in use. - * - * @return the transformer - */ - public Transformer getTransformer() { - return iTransformer; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/TransformerClosure.java b/src/main/java/repack/apache/commons/collections4/functors/TransformerClosure.java deleted file mode 100644 index 2160e0d369..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/TransformerClosure.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Closure; -import repack.apache.commons.collections4.Transformer; - -/** - * Closure implementation that calls a Transformer using the input object - * and ignore the result. - * - * @since 3.0 - */ -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 {@code NOPClosure}. - * - * @param the type that the closure acts on - * @param transformer the transformer to call, null means nop - * @return the {@code 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 {@code transformerClosure} if you want that. - * - * @param transformer the transformer to call, not null - */ - public TransformerClosure(final Transformer transformer) { - iTransformer = transformer; - } - - /** - * Executes the closure by calling the decorated transformer. - * - * @param input the input object - */ - @Override - public void execute(final E input) { - iTransformer.transform(input); - } - - /** - * Gets the transformer. - * - * @return the transformer - * @since 3.1 - */ - public Transformer getTransformer() { - return iTransformer; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/TransformerPredicate.java b/src/main/java/repack/apache/commons/collections4/functors/TransformerPredicate.java deleted file mode 100644 index 90be26d5b8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/TransformerPredicate.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.Objects; - -import repack.apache.commons.collections4.FunctorException; -import repack.apache.commons.collections4.Predicate; -import repack.apache.commons.collections4.Transformer; - -/** - * Predicate implementation that returns the result of a transformer. - * - * @since 3.0 - */ -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 NullPointerException if the transformer is null - */ - public static Predicate transformerPredicate(final Transformer transformer) { - return new TransformerPredicate<>(Objects.requireNonNull(transformer, "transformer")); - } - - /** - * Constructor that performs no validation. - * Use {@code transformerPredicate} if you want that. - * - * @param transformer the transformer to decorate - */ - public TransformerPredicate(final Transformer transformer) { - 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 - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/TruePredicate.java b/src/main/java/repack/apache/commons/collections4/functors/TruePredicate.java deleted file mode 100644 index 48975196b0..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/TruePredicate.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that always returns true. - * - * @since 3.0 - */ -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 - */ - public static Predicate truePredicate() { - return INSTANCE; - } - - /** - * Restricted constructor. - */ - private TruePredicate() { - } - - /** - * Evaluates the predicate returning true always. - * - * @param object the input object - * @return true always - */ - @Override - public boolean evaluate(final T object) { - return true; - } - - private Object readResolve() { - return INSTANCE; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/UniquePredicate.java b/src/main/java/repack/apache/commons/collections4/functors/UniquePredicate.java deleted file mode 100644 index 822b54a90a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/UniquePredicate.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -import repack.apache.commons.collections4.Predicate; - -/** - * Predicate implementation that returns true the first time an object is - * passed into the predicate. - * - * @since 3.0 - */ -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 {@code uniquePredicate} if you want that. - */ - public UniquePredicate() { - } - - /** - * 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 - */ - @Override - public boolean evaluate(final T object) { - return iSet.add(object); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/WhileClosure.java b/src/main/java/repack/apache/commons/collections4/functors/WhileClosure.java deleted file mode 100644 index 4223cdc729..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/WhileClosure.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.functors; - -import java.util.Objects; - -import repack.apache.commons.collections4.Closure; -import repack.apache.commons.collections4.Predicate; - -/** - * Closure implementation that executes a closure repeatedly until a condition is met, - * like a do-while or while loop. - *

- * WARNING: from v4.1 onwards this class will not be serializable anymore - * in order to prevent potential remote code execution exploits. Please refer to - * COLLECTIONS-580 - * for more details. - *

- * - * @since 3.0 - */ -public class WhileClosure implements Closure { - - /** 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 {@code while} closure - * @throws NullPointerException if the predicate or closure is null - */ - public static Closure whileClosure(final Predicate predicate, - final Closure closure, final boolean doLoop) { - return new WhileClosure<>(Objects.requireNonNull(predicate, "predicate"), - Objects.requireNonNull(closure, "closure"), doLoop); - } - - /** - * Constructor that performs no validation. - * Use {@code 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) { - iPredicate = predicate; - iClosure = closure; - iDoLoop = doLoop; - } - - /** - * Executes the closure until the predicate is false. - * - * @param input the input object - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/functors/package-info.java b/src/main/java/repack/apache/commons/collections4/functors/package-info.java deleted file mode 100644 index b72c30345e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/functors/package-info.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 repack.apache.commons.collections4.Closure Closure}, - * {@link repack.apache.commons.collections4.Predicate Predicate}, - * {@link repack.apache.commons.collections4.Transformer Transformer} and - * {@link repack.apache.commons.collections4.Factory Factory} interfaces. - * These provide simple callbacks for processing with collections. - *

- * WARNING: from v4.1 onwards several unsafe classes in this package - * will not be serializable anymore in order to prevent potential remote - * code execution exploits. - *

- * Classes considered to be unsafe are: - *

    - *
  • CloneTransformer
  • - *
  • ForClosure
  • - *
  • InstantiateFactory
  • - *
  • InstantiateTransformer
  • - *
  • InvokerTransformer
  • - *
  • PrototypeFactory$PrototypeCloneFactory
  • - *
  • PrototypeFactory$PrototypeSerializationFactory
  • - *
  • WhileClosure
  • - *
- * - */ -package repack.apache.commons.collections4.functors; diff --git a/src/main/java/repack/apache/commons/collections4/iterators/AbstractEmptyIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/AbstractEmptyIterator.java deleted file mode 100644 index e17188f2e7..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/AbstractEmptyIterator.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.NoSuchElementException; - -/** - * Provides an implementation of an empty iterator. - * - * @since 3.1 - */ -abstract class AbstractEmptyIterator { - - /** - * Constructor. - */ - protected AbstractEmptyIterator() { - } - - 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 - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/AbstractEmptyMapIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/AbstractEmptyMapIterator.java deleted file mode 100644 index 1c4b0d16b8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/AbstractEmptyMapIterator.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -/** - * Provides an implementation of an empty map iterator. - * - * @param the type of keys - * @param the type of mapped values - * @since 4.0 - */ -public abstract class AbstractEmptyMapIterator extends AbstractEmptyIterator { - - /** - * Create a new AbstractEmptyMapIterator. - */ - public AbstractEmptyMapIterator() { - } - - 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"); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/AbstractIteratorDecorator.java b/src/main/java/repack/apache/commons/collections4/iterators/AbstractIteratorDecorator.java deleted file mode 100644 index 176cc46321..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/AbstractIteratorDecorator.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; - -/** - * Provides basic behavior for decorating an iterator with extra functionality. - *

- * All methods are forwarded to the decorated iterator. - * - * @since 3.0 - */ -public abstract class AbstractIteratorDecorator extends AbstractUntypedIteratorDecorator { - - /** - * Constructor that decorates the specified iterator. - * - * @param iterator the iterator to decorate, must not be null - * @throws NullPointerException if the iterator is null - */ - protected AbstractIteratorDecorator(final Iterator iterator) { - super(iterator); - } - - /** {@inheritDoc} */ - @Override - public E next() { - return getIterator().next(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/AbstractListIteratorDecorator.java b/src/main/java/repack/apache/commons/collections4/iterators/AbstractListIteratorDecorator.java deleted file mode 100644 index 1fc3eaff50..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/AbstractListIteratorDecorator.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.ListIterator; -import java.util.Objects; - -/** - * Provides basic behavior for decorating a list iterator with extra functionality. - *

- * All methods are forwarded to the decorated list iterator. - * - * @since 3.0 - */ -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 NullPointerException if the iterator is null - */ - public AbstractListIteratorDecorator(final ListIterator iterator) { - this.iterator = Objects.requireNonNull(iterator, "iterator"); - } - - /** - * Gets the iterator being decorated. - * - * @return the decorated iterator - */ - protected ListIterator getListIterator() { - return iterator; - } - - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - /** {@inheritDoc} */ - @Override - public E next() { - return iterator.next(); - } - - /** {@inheritDoc} */ - @Override - public int nextIndex() { - return iterator.nextIndex(); - } - - /** {@inheritDoc} */ - @Override - public boolean hasPrevious() { - return iterator.hasPrevious(); - } - - /** {@inheritDoc} */ - @Override - public E previous() { - return iterator.previous(); - } - - /** {@inheritDoc} */ - @Override - public int previousIndex() { - return iterator.previousIndex(); - } - - /** {@inheritDoc} */ - @Override - public void remove() { - iterator.remove(); - } - - /** {@inheritDoc} */ - @Override - public void set(final E obj) { - iterator.set(obj); - } - - /** {@inheritDoc} */ - @Override - public void add(final E obj) { - iterator.add(obj); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/AbstractMapIteratorDecorator.java b/src/main/java/repack/apache/commons/collections4/iterators/AbstractMapIteratorDecorator.java deleted file mode 100644 index 330071b73c..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/AbstractMapIteratorDecorator.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Objects; - -import repack.apache.commons.collections4.MapIterator; - -/** - * Provides basic behavior for decorating a map iterator with extra functionality. - *

- * All methods are forwarded to the decorated map iterator. - * - * @param the type of keys - * @param the type of mapped values - * @since 3.0 - */ -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 NullPointerException if the iterator is null - */ - public AbstractMapIteratorDecorator(final MapIterator iterator) { - this.iterator = Objects.requireNonNull(iterator, "iterator"); - } - - /** - * Gets the iterator being decorated. - * - * @return the decorated iterator - */ - protected MapIterator getMapIterator() { - return iterator; - } - - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - /** {@inheritDoc} */ - @Override - public K next() { - return iterator.next(); - } - - /** {@inheritDoc} */ - @Override - public void remove() { - iterator.remove(); - } - - /** {@inheritDoc} */ - @Override - public K getKey() { - return iterator.getKey(); - } - - /** {@inheritDoc} */ - @Override - public V getValue() { - return iterator.getValue(); - } - - /** {@inheritDoc} */ - @Override - public V setValue(final V obj) { - return iterator.setValue(obj); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/AbstractOrderedMapIteratorDecorator.java b/src/main/java/repack/apache/commons/collections4/iterators/AbstractOrderedMapIteratorDecorator.java deleted file mode 100644 index cea8b54338..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/AbstractOrderedMapIteratorDecorator.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Objects; - -import repack.apache.commons.collections4.OrderedMapIterator; - -/** - * Provides basic behavior for decorating an ordered map iterator with extra functionality. - *

- * All methods are forwarded to the decorated map iterator. - * - * @param the type of keys - * @param the type of mapped values - * @since 3.0 - */ -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 NullPointerException if the iterator is null - */ - public AbstractOrderedMapIteratorDecorator(final OrderedMapIterator iterator) { - this.iterator = Objects.requireNonNull(iterator, "iterator"); - } - - /** - * Gets the iterator being decorated. - * - * @return the decorated iterator - */ - protected OrderedMapIterator getOrderedMapIterator() { - return iterator; - } - - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - /** {@inheritDoc} */ - @Override - public K next() { - return iterator.next(); - } - - /** {@inheritDoc} */ - @Override - public boolean hasPrevious() { - return iterator.hasPrevious(); - } - - /** {@inheritDoc} */ - @Override - public K previous() { - return iterator.previous(); - } - - /** {@inheritDoc} */ - @Override - public void remove() { - iterator.remove(); - } - - /** {@inheritDoc} */ - @Override - public K getKey() { - return iterator.getKey(); - } - - /** {@inheritDoc} */ - @Override - public V getValue() { - return iterator.getValue(); - } - - /** {@inheritDoc} */ - @Override - public V setValue(final V obj) { - return iterator.setValue(obj); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/AbstractUntypedIteratorDecorator.java b/src/main/java/repack/apache/commons/collections4/iterators/AbstractUntypedIteratorDecorator.java deleted file mode 100644 index 38996ceff8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/AbstractUntypedIteratorDecorator.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; -import java.util.Objects; - -/** - * Provides basic behavior 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 - */ -public abstract class AbstractUntypedIteratorDecorator implements Iterator { - - /** The iterator being decorated */ - private final Iterator iterator; - - /** - * Create a new AbstractUntypedIteratorDecorator. - * - * @param iterator the iterator to decorate - * @throws NullPointerException if the iterator is null - */ - protected AbstractUntypedIteratorDecorator(final Iterator iterator) { - this.iterator = Objects.requireNonNull(iterator, "iterator"); - } - - /** - * Gets the iterator being decorated. - * - * @return the decorated iterator - */ - protected Iterator getIterator() { - return iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public void remove() { - iterator.remove(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/ArrayIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/ArrayIterator.java deleted file mode 100644 index 7aa1a03be0..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/ArrayIterator.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.lang.reflect.Array; -import java.util.NoSuchElementException; - -import repack.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 repack.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. - * - * @param the type of elements returned by this iterator. - * @since 1.0 - */ -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; - - /** - * Constructs an ArrayIterator that will iterate over the values in the - * specified array. - * - * @param array the array to iterate over. - * @throws IllegalArgumentException if {@code array} is not an array. - * @throws NullPointerException if {@code array} is {@code 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 {@code array} is not an array. - * @throws NullPointerException if {@code array} is {@code 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 {@code array} is not an array. - * @throws NullPointerException if {@code array} is {@code null} - * @throws IndexOutOfBoundsException if either index is invalid - */ - public ArrayIterator(final Object array, final int startIndex, final int endIndex) { - 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 - */ - @Override - 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 - */ - @Override - @SuppressWarnings("unchecked") - public E next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - return (E) Array.get(array, index++); - } - - /** - * Throws {@link UnsupportedOperationException}. - * - * @throws UnsupportedOperationException always - */ - @Override - 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. - */ - @Override - public void reset() { - this.index = this.startIndex; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/ArrayListIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/ArrayListIterator.java deleted file mode 100644 index 579744e637..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/ArrayListIterator.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.lang.reflect.Array; -import java.util.NoSuchElementException; - -import repack.apache.commons.collections4.ResettableListIterator; - -/** - * Implements a {@link java.util.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. - * - * @param the type of elements returned by this iterator. - * @see repack.apache.commons.collections4.iterators.ArrayIterator - * @see java.util.Iterator - * @see java.util.ListIterator - * - * @since 3.0 - */ -public class ArrayListIterator extends ArrayIterator - implements ResettableListIterator { - - /** - * Holds the index of the last item returned by a call to {@code next()} - * or {@code previous()}. This is set to {@code -1} if neither method - * has yet been invoked. {@code lastItemIndex} is used to implement - * the {@link #set} method. - */ - private int lastItemIndex = -1; - - /** - * Constructs an ArrayListIterator that will iterate over the values in the - * specified array. - * - * @param array the array to iterate over - * @throws IllegalArgumentException if {@code array} is not an array. - * @throws NullPointerException if {@code array} is {@code 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 {@code array} is not an array. - * @throws NullPointerException if {@code array} is {@code 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 {@code 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 {@code array} is {@code 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 - */ - @Override - 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 - */ - @Override - @SuppressWarnings("unchecked") - public E previous() { - if (!hasPrevious()) { - 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()) { - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 java.util.ListIterator} implementations that support - * {@code add()} and {@code remove()} only allow {@code set()} to be called - * once per call to {@code next()} or {@code previous} (see the {@link java.util.ListIterator} - * javadoc for more details). Since this implementation does - * not support {@code add()} or {@code remove()}, {@code 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 - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/BoundedIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/BoundedIterator.java deleted file mode 100644 index 5d76eed6da..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/BoundedIterator.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Objects; - -/** - * Decorates another iterator to return elements in a specific range. - *

- * The decorated iterator is bounded in the range [offset, offset+max). - * The {@code offset} corresponds to the position of the first element to - * be returned from the decorated iterator, and {@code max} is the maximum - * number of elements to be returned at most. - *

- * In case an offset parameter other than 0 is provided, the decorated - * iterator is immediately advanced to this position, skipping all elements - * before that position. - * - * @param the type of elements returned by this iterator. - * @since 4.1 - */ -public class BoundedIterator implements Iterator { - - /** The iterator being decorated. */ - private final Iterator iterator; - - /** The offset to bound the first element return */ - private final long offset; - - /** The max number of elements to return */ - private final long max; - - /** The position of the current element */ - private long pos; - - - /** - * Decorates the specified iterator to return at most the given number of elements, - * skipping all elements until the iterator reaches the position at {@code offset}. - *

- * The iterator is immediately advanced until it reaches the position at {@code offset}, - * incurring O(n) time. - * - * @param iterator the iterator to be decorated - * @param offset the index of the first element of the decorated iterator to return - * @param max the maximum number of elements of the decorated iterator to return - * @throws NullPointerException if iterator is null - * @throws IllegalArgumentException if either offset or max is negative - */ - public BoundedIterator(final Iterator iterator, final long offset, final long max) { - if (offset < 0) { - throw new IllegalArgumentException("Offset parameter must not be negative."); - } - if (max < 0) { - throw new IllegalArgumentException("Max parameter must not be negative."); - } - - this.iterator = Objects.requireNonNull(iterator, "iterator"); - this.offset = offset; - this.max = max; - pos = 0; - init(); - } - - /** - * Advances the underlying iterator to the beginning of the bounded range. - */ - private void init() { - while (pos < offset && iterator.hasNext()) { - iterator.next(); - pos++; - } - } - - - @Override - public boolean hasNext() { - if (!checkBounds()) { - return false; - } - return iterator.hasNext(); - } - - /** - * Checks whether the iterator is still within its bounded range. - * @return {@code true} if the iterator is within its bounds, {@code false} otherwise - */ - private boolean checkBounds() { - if (pos - offset + 1 > max) { - return false; - } - return true; - } - - @Override - public E next() { - if (!checkBounds()) { - throw new NoSuchElementException(); - } - final E next = iterator.next(); - pos++; - return next; - } - - /** - * {@inheritDoc} - *

- * In case an offset other than 0 was specified, the underlying iterator will be advanced - * to this position upon creation. A call to {@link #remove()} will still result in an - * {@link IllegalStateException} if no explicit call to {@link #next()} has been made prior - * to calling {@link #remove()}. - */ - @Override - public void remove() { - if (pos <= offset) { - throw new IllegalStateException("remove() can not be called before calling next()"); - } - iterator.remove(); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/CollatingIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/CollatingIterator.java deleted file mode 100644 index 00216e9858..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/CollatingIterator.java +++ /dev/null @@ -1,387 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.Objects; - -import repack.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 {@code A} and - * {@code B}, the {@link #next} method on this iterator will return the - * lesser of {@code A.next()} and {@code B.next()}. - * - * @param the type of elements returned by this iterator. - * @since 2.1 - */ -public class CollatingIterator implements Iterator { - - /** The {@link Comparator} used to evaluate order. */ - private Comparator comparator; - - /** The list of {@link Iterator}s to evaluate. */ - private final List> iterators; - - /** {@link Iterator#next Next} objects peeked from each iterator. */ - private List values; - - /** Whether or not each {@link #values} element has been set. */ - private BitSet valueSet; - - /** - * Index of the {@link #iterators iterator} from whom the last returned - * value was obtained. - */ - private int lastReturned = -1; - - /** - * Constructs a new {@code 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 {@code CollatingIterator} that will use 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 {@code CollatingIterator} that will use 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 {@code 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 {@code 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 {@code 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); - } - } - - /** - * 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(); - Objects.requireNonNull(iterator, "iterator"); - 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(); - Objects.requireNonNull(iterator, "iterator"); - 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 collation 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 Comparable} interface), then use the - * {@link repack.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; - } - - /** - * Returns {@code true} if any child iterator has remaining elements. - * - * @return true if this iterator has remaining elements - */ - @Override - 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 - */ - @Override - public E next() throws NoSuchElementException { - if (!hasNext()) { - 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 - */ - @Override - 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; - } - - /** - * 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 {@code 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)) { - set(i); - } - if (valueSet.get(i)) { - if (leastIndex == -1) { - leastIndex = i; - leastObject = values.get(i); - } else { - final E curObject = values.get(i); - Objects.requireNonNull(comparator, "You must invoke setComparator() to set a comparator first."); - if (comparator.compare(curObject, leastObject) < 0) { - leastObject = curObject; - leastIndex = i; - } - } - } - } - return leastIndex; - } - - /** - * Returns {@code true} iff any bit in the given set is - * {@code true}. - */ - private boolean anyValueSet(final BitSet set) { - for (int i = 0; i < set.size(); i++) { - if (set.get(i)) { - return true; - } - } - return false; - } - - /** - * Returns {@code true} iff any {@link Iterator} in the given list has - * a next value. - */ - private boolean anyHasNext(final List> iterators) { - for (final Iterator iterator : iterators) { - if (iterator.hasNext()) { - return true; - } - } - return false; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/EmptyIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/EmptyIterator.java deleted file mode 100644 index 6e97fcebc6..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/EmptyIterator.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; - -import repack.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 {@code IteratorUtils}. - * - * @param the type of elements returned by this iterator. - * @since 2.1.1 and 3.1 - */ -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<E> - */ - public static ResettableIterator resettableEmptyIterator() { - return RESETTABLE_INSTANCE; - } - - /** - * Get a typed empty iterator instance. - * @param the element type - * @return Iterator<E> - */ - public static Iterator emptyIterator() { - return INSTANCE; - } - - /** - * Constructor. - */ - protected EmptyIterator() { - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/EmptyListIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/EmptyListIterator.java deleted file mode 100644 index d05a336fc9..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/EmptyListIterator.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.ListIterator; - -import repack.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 {@code IteratorUtils}. - * - * @param the type of elements returned by this iterator. - * @since 2.1.1 and 3.1 - */ -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}<E> - */ - public static ResettableListIterator resettableEmptyListIterator() { - return RESETTABLE_INSTANCE; - } - - /** - * Get a typed instance of the iterator. - * @param the element type - * @return {@link ListIterator}<E> - */ - public static ListIterator emptyListIterator() { - return INSTANCE; - } - - /** - * Constructor. - */ - protected EmptyListIterator() { - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/EmptyMapIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/EmptyMapIterator.java deleted file mode 100644 index 0cfd241599..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/EmptyMapIterator.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.ResettableIterator; - -/** - * Provides an implementation of an empty map iterator. - * - * @param the type of keys - * @param the type of mapped values - * @since 3.1 - */ -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}<K, V> - */ - public static MapIterator emptyMapIterator() { - return INSTANCE; - } - - /** - * Constructor. - */ - protected EmptyMapIterator() { - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/EmptyOrderedIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/EmptyOrderedIterator.java deleted file mode 100644 index 2d69c5e119..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/EmptyOrderedIterator.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import repack.apache.commons.collections4.OrderedIterator; -import repack.apache.commons.collections4.ResettableIterator; - -/** - * Provides an implementation of an empty ordered iterator. - * - * @param the type of elements returned by this iterator. - * @since 3.1 - */ -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<E> - */ - public static OrderedIterator emptyOrderedIterator() { - return INSTANCE; - } - - /** - * Constructor. - */ - protected EmptyOrderedIterator() { - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/EmptyOrderedMapIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/EmptyOrderedMapIterator.java deleted file mode 100644 index 26fe36aac2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/EmptyOrderedMapIterator.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.ResettableIterator; - -/** - * Provides an implementation of an empty ordered map iterator. - * - * @param the type of keys - * @param the type of mapped values - * @since 3.1 - */ -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}<K, V> - */ - public static OrderedMapIterator emptyOrderedMapIterator() { - return INSTANCE; - } - - /** - * Constructor. - */ - protected EmptyOrderedMapIterator() { - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/EntrySetMapIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/EntrySetMapIterator.java deleted file mode 100644 index 0005afa7e7..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/EntrySetMapIterator.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; -import java.util.Map; - -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.ResettableIterator; - -/** - * Implements a {@code 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);
- * }
- * 
- * - * @param the type of keys - * @param the type of mapped values - * @since 3.0 - */ -public class EntrySetMapIterator implements MapIterator, ResettableIterator { - - private final Map map; - private Iterator> iterator; - private Map.Entry last; - private boolean canRemove; - - /** - * Constructor. - * - * @param map the map to iterate over - */ - public EntrySetMapIterator(final Map map) { - this.map = map; - this.iterator = map.entrySet().iterator(); - } - - /** - * Checks to see if there are more entries still to be iterated. - * - * @return {@code true} if the iterator has more elements - */ - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - /** - * Gets the next key from the {@code Map}. - * - * @return the next key in the iteration - * @throws java.util.NoSuchElementException if the iteration is finished - */ - @Override - public K next() { - last = iterator.next(); - canRemove = true; - return last.getKey(); - } - - /** - * Removes the last returned key from the underlying {@code Map}. - *

- * This method can be called once per call to {@code next()}. - * - * @throws UnsupportedOperationException if remove is not supported by the map - * @throws IllegalStateException if {@code next()} has not yet been called - * @throws IllegalStateException if {@code remove()} has already been called - * since the last call to {@code next()} - */ - @Override - public void remove() { - if (!canRemove) { - 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 {@code next()}. - * - * @return the current key - * @throws IllegalStateException if {@code next()} has not yet been called - */ - @Override - 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 {@code next()}. - * - * @return the current value - * @throws IllegalStateException if {@code next()} has not yet been called - */ - @Override - 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 {@code next()} has not yet been called - * @throws IllegalStateException if {@code remove()} has been called since the - * last call to {@code next()} - */ - @Override - 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. - */ - @Override - 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[]"; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/EnumerationIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/EnumerationIterator.java deleted file mode 100644 index 0d4a71ca5a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/EnumerationIterator.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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. - * - * @param the type of elements returned by this iterator. - * @since 1.0 - */ -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 {@code EnumerationIterator} that will not - * function until {@link #setEnumeration(Enumeration)} is called. - */ - public EnumerationIterator() { - this(null, null); - } - - /** - * Constructs a new {@code 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 {@code 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) { - 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 - */ - @Override - 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 - */ - @Override - public E next() { - last = enumeration.nextElement(); - return last; - } - - /** - * Removes the last retrieved element if a collection is attached. - *

- * Functions if an associated {@code Collection} is known. - * If so, the first occurrence of the last returned object from this - * iterator will be removed from the collection. - * - * @throws IllegalStateException {@code next()} not called. - * @throws UnsupportedOperationException if no associated collection - */ - @Override - public void remove() { - if (collection == null) { - throw new UnsupportedOperationException("No Collection associated with this Iterator"); - } - if (last == null) { - throw new IllegalStateException("next() must have been called for remove() to function"); - } - collection.remove(last); - } - - // 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/FilterIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/FilterIterator.java deleted file mode 100644 index af2478692d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/FilterIterator.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -import repack.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}. - * - * @param the type of elements returned by this iterator. - * @since 1.0 - */ -public class FilterIterator implements Iterator { - - /** The iterator being used */ - private Iterator iterator; - /** The predicate being used */ - private Predicate predicate; - /** The next object in the iteration */ - private E nextObject; - /** Whether the next object has been calculated yet */ - private boolean nextObjectSet; - - /** - * Constructs a new {@code FilterIterator} that will not function - * until {@link #setIterator(Iterator) setIterator} is invoked. - */ - public FilterIterator() { - } - - /** - * Constructs a new {@code FilterIterator} that will not function - * until {@link #setPredicate(Predicate) setPredicate} is invoked. - * - * @param iterator the iterator to use - */ - public FilterIterator(final Iterator iterator) { - this.iterator = iterator; - } - - /** - * Constructs a new {@code 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) { - 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 - */ - @Override - 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 - */ - @Override - public E next() { - if (!nextObjectSet && !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 {@code next()} was called, but not after - * {@code hasNext()}, because the {@code hasNext()} call - * changes the base iterator. - * - * @throws IllegalStateException if {@code hasNext()} has already - * been called. - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/FilterListIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/FilterListIterator.java deleted file mode 100644 index 7dbfa66da3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/FilterListIterator.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.ListIterator; -import java.util.NoSuchElementException; - -import repack.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}. - * - * @param the type of elements returned by this iterator. - * @since 2.0 - */ -public class FilterListIterator implements ListIterator { - - /** The iterator being used */ - private ListIterator iterator; - - /** The predicate being used */ - private Predicate predicate; - - /** - * The value of the next (matching) object, when - * {@link #nextObjectSet} is true. - */ - private E nextObject; - - /** - * Whether or not the {@link #nextObject} has been set - * (possibly to {@code null}). - */ - private boolean nextObjectSet; - - /** - * 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 {@code null}). - */ - private boolean previousObjectSet; - - /** - * The index of the element that would be returned by {@link #next}. - */ - private int nextIndex; - - /** - * Constructs a new {@code FilterListIterator} that will not function - * until {@link #setListIterator(ListIterator) setListIterator} - * and {@link #setPredicate(Predicate) setPredicate} are invoked. - */ - public FilterListIterator() { - } - - /** - * Constructs a new {@code FilterListIterator} that will not - * function until {@link #setPredicate(Predicate) setPredicate} is invoked. - * - * @param iterator the iterator to use - */ - public FilterListIterator(final ListIterator iterator ) { - this.iterator = iterator; - } - - /** - * Constructs a new {@code FilterListIterator}. - * - * @param iterator the iterator to use - * @param predicate the predicate to use - */ - public FilterListIterator(final ListIterator iterator, final Predicate predicate) { - this.iterator = iterator; - this.predicate = predicate; - } - - /** - * Constructs a new {@code FilterListIterator} that will not function - * until {@link #setListIterator(ListIterator) setListIterator} is invoked. - * - * @param predicate the predicate to use. - */ - public FilterListIterator(final Predicate predicate) { - this.predicate = predicate; - } - - /** - * Not supported. - * @param o the element to insert - */ - @Override - public void add(final E o) { - throw new UnsupportedOperationException("FilterListIterator.add(Object) is not supported."); - } - - @Override - public boolean hasNext() { - return nextObjectSet || setNextObject(); - } - - @Override - public boolean hasPrevious() { - return previousObjectSet || setPreviousObject(); - } - - @Override - public E next() { - if (!nextObjectSet && !setNextObject()) { - throw new NoSuchElementException(); - } - nextIndex++; - final E temp = nextObject; - clearNextObject(); - return temp; - } - - @Override - public int nextIndex() { - return nextIndex; - } - - @Override - public E previous() { - if (!previousObjectSet && !setPreviousObject()) { - throw new NoSuchElementException(); - } - nextIndex--; - final E temp = previousObject; - clearPreviousObject(); - return temp; - } - - @Override - public int previousIndex() { - return nextIndex-1; - } - - /** Not supported. */ - @Override - public void remove() { - throw new UnsupportedOperationException("FilterListIterator.remove() is not supported."); - } - - /** - * Not supported. - * @param o the element with which to replace the last element returned by - * {@code next} or {@code previous} - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/IteratorChain.java b/src/main/java/repack/apache/commons/collections4/iterators/IteratorChain.java deleted file mode 100644 index 841f4901e1..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/IteratorChain.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Objects; -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 - */ -public class IteratorChain implements Iterator { - - /** The chain of iterators */ - private final Queue> iteratorChain = new LinkedList<>(); - - /** The current iterator */ - private Iterator currentIterator; - - /** - * 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; - - /** - * ComparatorChain is "locked" after the first time compare(Object,Object) - * is called - */ - private boolean isLocked; - - /** - * Construct an IteratorChain with no Iterators. - *

- * You will normally use {@link #addIterator(Iterator)} to add some - * iterators after using this constructor. - */ - public IteratorChain() { - } - - /** - * 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) { - addIterator(iterator); - } - - /** - * Constructs a new {@code 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) { - addIterator(first); - addIterator(second); - } - - /** - * Constructs a new {@code 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) { - for (final Iterator element : iteratorChain) { - addIterator(element); - } - } - - /** - * Constructs a new {@code 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) { - 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(); - iteratorChain.add(Objects.requireNonNull(iterator, "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) { - 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) { - 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() && !iteratorChain.isEmpty()) { - currentIterator = iteratorChain.remove(); - } - } - - /** - * Return true if any Iterator in the IteratorChain has a remaining element. - * - * @return true if elements remain - */ - @Override - 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 - */ - @Override - 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. - */ - @Override - public void remove() { - lockChain(); - if (currentIterator == null) { - updateCurrentIterator(); - } - lastUsedIterator.remove(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/IteratorEnumeration.java b/src/main/java/repack/apache/commons/collections4/iterators/IteratorEnumeration.java deleted file mode 100644 index ec64fc679a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/IteratorEnumeration.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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. - * - * @param the type of elements returned by this iterator. - * @since 1.0 - */ -public class IteratorEnumeration implements Enumeration { - - /** The iterator being decorated. */ - private Iterator iterator; - - /** - * Constructs a new {@code IteratorEnumeration} that will not function - * until {@link #setIterator(Iterator) setIterator} is invoked. - */ - public IteratorEnumeration() { - } - - /** - * Constructs a new {@code IteratorEnumeration} that will use the given - * iterator. - * - * @param iterator the iterator to use - */ - public IteratorEnumeration(final Iterator iterator) { - this.iterator = iterator; - } - - /** - * Returns true if the underlying iterator has more elements. - * - * @return true if the underlying iterator has more elements - */ - @Override - 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 - */ - @Override - public E nextElement() { - return iterator.next(); - } - - /** - * 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/IteratorIterable.java b/src/main/java/repack/apache/commons/collections4/iterators/IteratorIterable.java deleted file mode 100644 index b4d3ea0d08..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/IteratorIterable.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; - -import repack.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<Integer> iterator = // some non-resettable iterator
- *   Iterable<Integer> iterable = new IteratorIterable<Integer>(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<Integer> iterator = IteratorUtils.arrayIterator(array); // a resettable iterator
- *   Iterable<Integer> iterable = new IteratorIterable<Integer>(iterator);
- * 
- * - *

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

- * - *
- *   Iterator<Integer> iterator = // some non-resettable iterator
- *   Iterable<Integer> iterable = new IteratorIterable<Integer>(iterator, true);
- * 
- * - * @param the type of elements returned by this iterator. - * @since 4.0 - */ -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() { - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public E next() { - return iterator.next(); - } - - @Override - 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 {@code IteratorIterable} that will use the given - * iterator. - * - * @param iterator the iterator to use. - */ - public IteratorIterable(final Iterator iterator) { - this(iterator, false); - } - - /** - * Constructs a new {@code IteratorIterable} that will use the given - * iterator. - * - * @param iterator the iterator to use. - * @param multipleUse {@code true} if the new iterable can be used in multiple iterations - */ - public IteratorIterable(final Iterator iterator, final boolean multipleUse) { - 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 - */ - @Override - public Iterator iterator() { - if (iterator instanceof ResettableIterator) { - ((ResettableIterator) iterator).reset(); - } - return typeSafeIterator; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/LazyIteratorChain.java b/src/main/java/repack/apache/commons/collections4/iterators/LazyIteratorChain.java deleted file mode 100644 index 7e0f5cb241..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/LazyIteratorChain.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - * subclasses 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 - */ -public abstract class LazyIteratorChain implements Iterator { - - /** The number of times {@link #next()} was already called. */ - private int callCounter; - - /** Indicates that the Iterator chain has been exhausted. */ - private boolean chainExhausted; - - /** The current iterator. */ - private Iterator currentIterator; - - /** - * 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; - - - /** - * 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() && !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 - */ - @Override - 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 - */ - @Override - 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. - */ - @Override - public void remove() { - if (currentIterator == null) { - updateCurrentIterator(); - } - lastUsedIterator.remove(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/ListIteratorWrapper.java b/src/main/java/repack/apache/commons/collections4/iterators/ListIteratorWrapper.java deleted file mode 100644 index d1d436cb7d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/ListIteratorWrapper.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.Objects; - -import repack.apache.commons.collections4.ResettableListIterator; - -/** - * Converts an {@link Iterator} into a {@link ResettableListIterator}. - * For plain {@code Iterator}s this is accomplished by caching the returned - * elements. This class can also be used to simply add - * {@link repack.apache.commons.collections4.ResettableIterator ResettableIterator} - * functionality to a given {@link ListIterator}. - *

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

- * The optional operations of {@code ListIterator} are not supported for plain {@code Iterator}s. - *

- * This class implements ResettableListIterator from Commons Collections 3.2. - * - * @since 2.1 - */ -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; - /** The current index of the wrapped iterator. */ - private int wrappedIteratorIndex; - /** recall whether the wrapped iterator's "cursor" is in such a state as to allow remove() to be called */ - private boolean removeState; - - /** - * Constructs a new {@code 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) { - this.iterator = Objects.requireNonNull(iterator, "iterator"); - } - - /** - * Throws {@link UnsupportedOperationException} - * unless the underlying {@code Iterator} is a {@code ListIterator}. - * - * @param obj the object to add - * @throws UnsupportedOperationException if the underlying iterator is not of - * type {@link ListIterator} - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - public int nextIndex() { - if (iterator instanceof ListIterator) { - final ListIterator li = (ListIterator) iterator; - return li.nextIndex(); - } - return currentIndex; - } - - /** - * Returns the previous element. - * - * @return the previous element - * @throws NoSuchElementException if there are no previous elements - */ - @Override - 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 - */ - @Override - public int previousIndex() { - if (iterator instanceof ListIterator) { - final ListIterator li = (ListIterator) iterator; - return li.previousIndex(); - } - return currentIndex - 1; - } - - /** - * Removes the last element that was returned by {@link #next()} or {@link #previous()} from the underlying collection. - * This call can only be made once per call to {@code next} or {@code previous} and only if {@link #add(Object)} was not called in between. - * - * @throws IllegalStateException if {@code next} or {@code previous} have not been called before, or if {@code remove} or {@code add} have been called after the last call to {@code next} or {@code previous} - */ - @Override - public void remove() throws IllegalStateException { - 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 {@code Iterator} is a {@code ListIterator}. - * - * @param obj the object to set - * @throws UnsupportedOperationException if the underlying iterator is not of - * type {@link ListIterator} - */ - @Override - 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); - } - - /** - * Resets this iterator back to the position at which the iterator - * was created. - * - * @since 3.2 - */ - @Override - public void reset() { - if (iterator instanceof ListIterator) { - final ListIterator li = (ListIterator) iterator; - while (li.previousIndex() >= 0) { - li.previous(); - } - return; - } - currentIndex = 0; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/LoopingIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/LoopingIterator.java deleted file mode 100644 index 4adeba6baf..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/LoopingIterator.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Objects; - -import repack.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. - * - * @param the type of elements returned by this iterator. - * @since 3.0 - */ -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 collection the collection to wrap - * @throws NullPointerException if the collection is null - */ - public LoopingIterator(final Collection collection) { - this.collection = Objects.requireNonNull(collection, "collection"); - 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 {@code true} if there are more elements - */ - @Override - public boolean hasNext() { - return !collection.isEmpty(); - } - - /** - * 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. - */ - @Override - public E next() { - if (collection.isEmpty()) { - throw new NoSuchElementException("There are no elements for this iterator to loop on"); - } - if (!iterator.hasNext()) { - 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. - */ - @Override - public void remove() { - iterator.remove(); - } - - /** - * Resets the iterator back to the start of the collection. - */ - @Override - 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/LoopingListIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/LoopingListIterator.java deleted file mode 100644 index b79a38b5a2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/LoopingListIterator.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import java.util.Objects; - -import repack.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. - * - * @param the type of elements returned by this iterator. - * @since 3.2 - */ -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 is null - */ - public LoopingListIterator(final List list) { - this.list = Objects.requireNonNull(list, "collection"); - _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 {@code true} if there are more elements - */ - @Override - 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 - */ - @Override - public E next() { - if (list.isEmpty()) { - throw new NoSuchElementException( - "There are no elements for this iterator to loop on"); - } - if (!iterator.hasNext()) { - 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 - */ - @Override - public int nextIndex() { - if (list.isEmpty()) { - throw new NoSuchElementException( - "There are no elements for this iterator to loop on"); - } - if (!iterator.hasNext()) { - 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 {@code true} if there are more elements - */ - @Override - 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 - */ - @Override - public E previous() { - if (list.isEmpty()) { - throw new NoSuchElementException( - "There are no elements for this iterator to loop on"); - } - if (!iterator.hasPrevious()) { - 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 - */ - @Override - public int previousIndex() { - if (list.isEmpty()) { - throw new NoSuchElementException( - "There are no elements for this iterator to loop on"); - } - if (!iterator.hasPrevious()) { - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - public void set(final E obj) { - iterator.set(obj); - } - - /** - * Resets the iterator back to the start of the list. - */ - @Override - 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/NodeListIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/NodeListIterator.java deleted file mode 100644 index c50636b251..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/NodeListIterator.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Objects; - -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 - * @see NodeList - */ -public class NodeListIterator implements Iterator { - - /** the original NodeList instance */ - private final NodeList nodeList; - /** The current iterator index */ - private int index; - - /** - * 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 NullPointerException if node is null - */ - public NodeListIterator(final Node node) { - Objects.requireNonNull(node, "node"); - this.nodeList = node.getChildNodes(); - } - - /** - * Constructor, that creates a new NodeListIterator from the specified - * {@code org.w3c.NodeList} - * - * @param nodeList node list, which is wrapped by this class. Must not be null - * @throws NullPointerException if nodeList is null - */ - public NodeListIterator(final NodeList nodeList) { - this.nodeList = Objects.requireNonNull(nodeList, "nodeList"); - } - - @Override - public boolean hasNext() { - return nodeList != null && index < nodeList.getLength(); - } - - @Override - 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 - */ - @Override - public void remove() { - throw new UnsupportedOperationException("remove() method not supported for a NodeListIterator."); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/ObjectArrayIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/ObjectArrayIterator.java deleted file mode 100644 index 35e0cd857e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/ObjectArrayIterator.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.NoSuchElementException; - -import repack.apache.commons.collections4.ResettableIterator; - -/** - * An {@link java.util.Iterator 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. - * - * @param the type of elements returned by this iterator. - * @since 3.0 - */ -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; - - /** - * Constructs an ObjectArrayIterator that will iterate over the values in the - * specified array. - * - * @param array the array to iterate over - * @throws NullPointerException if {@code array} is {@code 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 {@code array} is {@code 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 {@code array} is {@code null} - */ - public ObjectArrayIterator(final E array[], final int start, final int end) { - 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; - } - - /** - * Returns true if there are more elements to return from the array. - * - * @return true if there is a next element to return - */ - @Override - 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 - */ - @Override - public E next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - return this.array[this.index++]; - } - - /** - * Throws {@link UnsupportedOperationException}. - * - * @throws UnsupportedOperationException always - */ - @Override - public void remove() { - throw new UnsupportedOperationException("remove() method is not supported for an ObjectArrayIterator"); - } - - /** - * 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. - */ - @Override - public void reset() { - this.index = this.startIndex; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/ObjectArrayListIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/ObjectArrayListIterator.java deleted file mode 100644 index b83d2271a0..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/ObjectArrayListIterator.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.NoSuchElementException; - -import repack.apache.commons.collections4.ResettableListIterator; - -/** - * Implements a {@link java.util.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. - * - * @param the type of elements returned by this iterator. - * @see repack.apache.commons.collections4.iterators.ObjectArrayIterator - * @see java.util.Iterator - * @see java.util.ListIterator - * - * @since 3.0 - */ -public class ObjectArrayListIterator extends ObjectArrayIterator - implements ResettableListIterator { - - /** - * Holds the index of the last item returned by a call to {@code next()} - * or {@code previous()}. This is set to {@code -1} if neither method - * has yet been invoked. {@code lastItemIndex} is used 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 {@code array} is {@code 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 {@code array} is {@code 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 {@code array} is {@code null} - */ - public ObjectArrayListIterator(final E[] array, final int start, final int end) { - super(array, start, end); - } - - /** - * Returns true if there are previous elements to return from the array. - * - * @return true if there is a previous element to return - */ - @Override - 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 - */ - @Override - public E previous() { - if (!hasPrevious()) { - 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()) { - 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 - */ - @Override - 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 - */ - @Override - 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. - */ - @Override - 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 java.util.ListIterator} implementations that support {@code add()} - * and {@code remove()} only allow {@code set()} to be called once per call - * to {@code next()} or {@code previous} (see the {@link java.util.ListIterator} - * javadoc for more details). Since this implementation does not support - * {@code add()} or {@code remove()}, {@code 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 - */ - @Override - 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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/ObjectGraphIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/ObjectGraphIterator.java deleted file mode 100644 index d1b76754c8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/ObjectGraphIterator.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import repack.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 {@code Transformer} to extract the iterators and elements. - * Its main benefit is that no intermediate {@code 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 {@code 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 type of elements returned by this iterator. - * @since 3.1 - */ -public class ObjectGraphIterator implements Iterator { - - /** The stack of iterators */ - private final Deque> stack = new ArrayDeque<>(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; - /** 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) { - 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) { - 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) { - E next = currentIterator.next(); - if (transformer != null) { - next = transformer.transform(next); - } - findNext(next); - } - // if we haven'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 - */ - @Override - 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 - */ - @Override - public E next() { - updateCurrentIterator(); - if (!hasNext) { - 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. - */ - @Override - public void remove() { - if (lastUsedIterator == null) { - throw new IllegalStateException("Iterator remove() cannot be called at this time"); - } - lastUsedIterator.remove(); - lastUsedIterator = null; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/PeekingIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/PeekingIterator.java deleted file mode 100644 index 4f2667c195..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/PeekingIterator.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Objects; - -/** - * 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()}. - * - * @param the type of elements returned by this iterator. - * @since 4.0 - */ -public class PeekingIterator implements Iterator { - - /** The iterator being decorated. */ - private final Iterator iterator; - - /** Indicates that the decorated iterator is exhausted. */ - private boolean exhausted; - - /** Indicates if the lookahead slot is filled. */ - private boolean slotFilled; - - /** 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 NullPointerException if the iterator is null - */ - public static PeekingIterator peekingIterator(final Iterator iterator) { - Objects.requireNonNull(iterator, "iterator"); - 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; - } - } - - @Override - public boolean hasNext() { - if (exhausted) { - return false; - } - return slotFilled || 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; - } - - @Override - 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()} - */ - @Override - public void remove() { - if (slotFilled) { - throw new IllegalStateException("peek() or element() called before remove()"); - } - iterator.remove(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/PermutationIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/PermutationIterator.java deleted file mode 100644 index 0f16b1e9e4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/PermutationIterator.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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; -import java.util.Objects; - -/** - * 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 - * - * @since 4.0 - */ -public class PermutationIterator implements Iterator> { - - /** - * Permutation is done on these keys to handle equal objects. - */ - private final int[] keys; - - /** - * Mapping between keys and objects. - */ - private final Map objectMap; - - /** - * Direction table used in the algorithm: - *

    - *
  • false is left
  • - *
  • true is right
  • - *
- */ - private final 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 collection the collection to generate permutations for - * @throws NullPointerException if coll is null - */ - public PermutationIterator(final Collection collection) { - Objects.requireNonNull(collection, "collection"); - keys = new int[collection.size()]; - direction = new boolean[collection.size()]; - Arrays.fill(direction, false); - int value = 1; - objectMap = new HashMap<>(); - for (final E e : collection) { - objectMap.put(Integer.valueOf(value), e); - keys[value - 1] = value; - value++; - } - nextPermutation = new ArrayList<>(collection); - } - - /** - * Indicates if there are more permutation available. - * @return true if there are more permutations, otherwise false - */ - @Override - 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 - */ - @Override - 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) { // NOPMD - largestKey = keys[i]; - indexOfLargestMobileInteger = i; - } - } - } - if (largestKey == -1) { - final 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; - final 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; - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove() is not supported"); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/PushbackIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/PushbackIterator.java deleted file mode 100644 index 89df08d883..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/PushbackIterator.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.ArrayDeque; -import java.util.Deque; -import java.util.Iterator; -import java.util.Objects; - -/** - * 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}. - * - * @param the type of elements returned by this iterator. - * @since 4.0 - */ -public class PushbackIterator implements Iterator { - - /** The iterator being decorated. */ - private final Iterator iterator; - - /** The LIFO queue containing the pushed back items. */ - private final Deque items = new ArrayDeque<>(); - - /** - * Decorates the specified iterator to support one-element lookahead. - *

- * If the iterator is already a {@link PushbackIterator} it is returned directly. - * - * @param the element type - * @param iterator the iterator to decorate - * @return a new peeking iterator - * @throws NullPointerException if the iterator is null - */ - public static PushbackIterator pushbackIterator(final Iterator iterator) { - Objects.requireNonNull(iterator, "iterator"); - 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) { - 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); - } - - @Override - public boolean hasNext() { - return !items.isEmpty() || iterator.hasNext(); - } - - @Override - public E next() { - return !items.isEmpty() ? items.pop() : iterator.next(); - } - - /** - * This iterator will always throw an {@link UnsupportedOperationException}. - * - * @throws UnsupportedOperationException always - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/ReverseListIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/ReverseListIterator.java deleted file mode 100644 index 564e5ab143..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/ReverseListIterator.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.List; -import java.util.ListIterator; -import java.util.Objects; - -import repack.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 {@code next()} will return the last element - * from the list, and so on. The {@code hasNext()} method works - * in concert with the {@code next()} method as expected. - * However, the {@code nextIndex()} method returns the correct - * index in the list, thus it starts high and reduces as the iteration - * continues. The previous methods work similarly. - * - * @param the type of elements returned by this iterator. - * @since 3.2 - */ -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) { - this.list = Objects.requireNonNull(list, "list"); - iterator = list.listIterator(list.size()); - } - - /** - * Checks whether there is another element. - * - * @return true if there is another element - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - public int nextIndex() { - return iterator.previousIndex(); - } - - /** - * Checks whether there is a previous element. - * - * @return true if there is a previous element - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - public void remove() { - if (!validForUpdate) { - 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 - */ - @Override - public void set(final E obj) { - if (!validForUpdate) { - 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 - */ - @Override - public void add(final E obj) { - // the validForUpdate flag is needed as the necessary previous() - // method call re-enables remove and add - if (!validForUpdate) { - 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) - */ - @Override - public void reset() { - iterator = list.listIterator(list.size()); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/SingletonIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/SingletonIterator.java deleted file mode 100644 index 9da18ccd4b..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/SingletonIterator.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.NoSuchElementException; - -import repack.apache.commons.collections4.ResettableIterator; - -/** - * {@code SingletonIterator} is an {@link java.util.Iterator} over a single - * object instance. - * - * @param the type of elements returned by this iterator. - * @since 2.0 - */ -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; - /** The object */ - private E object; - - /** - * Constructs a new {@code SingletonIterator} where {@code 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 {@code SingletonIterator} optionally choosing if - * {@code 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) { - 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 - */ - @Override - 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 - */ - @Override - public E next() { - if (!beforeFirst || removed) { - throw new NoSuchElementException(); - } - beforeFirst = false; - return object; - } - - /** - * Remove the object from this iterator. - * - * @throws IllegalStateException if the {@code next} method has not - * yet been called, or the {@code remove} method has already - * been called after the last call to the {@code next} - * method. - * @throws UnsupportedOperationException if remove is not supported - */ - @Override - public void remove() { - if (!removeAllowed) { - throw new UnsupportedOperationException(); - } - if (removed || beforeFirst) { - throw new IllegalStateException(); - } - object = null; - removed = true; - } - - /** - * Reset the iterator to the start. - */ - @Override - public void reset() { - beforeFirst = true; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/SingletonListIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/SingletonListIterator.java deleted file mode 100644 index f27511230f..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/SingletonListIterator.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.NoSuchElementException; - -import repack.apache.commons.collections4.ResettableListIterator; - -/** - * {@code SingletonIterator} is an {@link java.util.ListIterator} over a single - * object instance. - * - * @param the type of elements returned by this iterator. - * @since 2.1 - */ -public class SingletonListIterator implements ResettableListIterator { - - private boolean beforeFirst = true; - private boolean nextCalled; - private boolean removed; - private E object; - - /** - * Constructs a new {@code SingletonListIterator}. - * - * @param object the single object to return from the iterator - */ - public SingletonListIterator(final E object) { - 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 - */ - @Override - 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 - */ - @Override - public boolean hasPrevious() { - return !beforeFirst && !removed; - } - - /** - * Returns the index of the element that would be returned by a subsequent - * call to {@code next}. - * - * @return 0 or 1 depending on current state. - */ - @Override - public int nextIndex() { - return beforeFirst ? 0 : 1; - } - - /** - * Returns the index of the element that would be returned by a subsequent - * call to {@code previous}. A return value of -1 indicates that the iterator is currently at - * the start. - * - * @return 0 or -1 depending on current state. - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - public E previous() { - if (beforeFirst || removed) { - throw new NoSuchElementException(); - } - beforeFirst = true; - return object; - } - - /** - * Remove the object from this iterator. - * @throws IllegalStateException if the {@code next} or {@code previous} - * method has not yet been called, or the {@code remove} method - * has already been called after the last call to {@code next} - * or {@code previous}. - */ - @Override - 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 - */ - @Override - 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 {@code next} has not been called - * or the object has been removed - */ - @Override - public void set(final E obj) { - if (!nextCalled || removed) { - throw new IllegalStateException(); - } - this.object = obj; - } - - /** - * Reset the iterator back to the start. - */ - @Override - public void reset() { - beforeFirst = true; - nextCalled = false; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/SkippingIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/SkippingIterator.java deleted file mode 100644 index 3ab0439d7d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/SkippingIterator.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; - -/** - * Decorates another iterator to skip the first N elements. - *

- * In case an offset parameter other than 0 is provided, the decorated - * iterator is immediately advanced to this position, skipping all elements - * before that position. - *

- * - * @param the type of elements returned by this iterator. - * @since 4.1 - */ -public class SkippingIterator extends AbstractIteratorDecorator { - - /** The offset to bound the first element return */ - private final long offset; - - /** The position of the current element */ - private long pos; - - - /** - * Decorates the specified iterator to skip all elements until the iterator - * reaches the position at {@code offset}. - *

- * The iterator is immediately advanced until it reaches the position at {@code offset}, - * incurring O(n) time. - * - * @param iterator the iterator to be decorated - * @param offset the index of the first element of the decorated iterator to return - * @throws NullPointerException if iterator is null - * @throws IllegalArgumentException if offset is negative - */ - public SkippingIterator(final Iterator iterator, final long offset) { - super(iterator); - - if (offset < 0) { - throw new IllegalArgumentException("Offset parameter must not be negative."); - } - - this.offset = offset; - this.pos = 0; - init(); - } - - /** - * Skips the given number of elements. - */ - private void init() { - while (pos < offset && hasNext()) { - next(); - } - } - - - @Override - public E next() { - final E next = super.next(); - pos++; - return next; - } - - /** - * {@inheritDoc} - *

- * In case an offset other than 0 was specified, the underlying iterator will be advanced - * to this position upon creation. A call to {@link #remove()} will still result in an - * {@link IllegalStateException} if no explicit call to {@link #next()} has been made prior - * to calling {@link #remove()}. - */ - @Override - public void remove() { - if (pos <= offset) { - throw new IllegalStateException("remove() can not be called before calling next()"); - } - super.remove(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/TransformIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/TransformIterator.java deleted file mode 100644 index e41c38e615..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/TransformIterator.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; - -import repack.apache.commons.collections4.Transformer; - -/** - * Decorates an iterator such that each element returned is transformed. - * - * @since 1.0 - */ -public class TransformIterator implements Iterator { - - /** The iterator being used */ - private Iterator iterator; - /** The transformer being used */ - private Transformer transformer; - - /** - * Constructs a new {@code TransformIterator} that will not function - * until the {@link #setIterator(Iterator) setIterator} and - * {@link #setTransformer(Transformer)} methods are invoked. - */ - public TransformIterator() { - } - - /** - * Constructs a new {@code TransformIterator} that won't transform - * elements from the given iterator. - * - * @param iterator the iterator to use - */ - public TransformIterator(final Iterator iterator) { - this.iterator = iterator; - } - - /** - * Constructs a new {@code 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) { - this.iterator = iterator; - this.transformer = transformer; - } - - @Override - 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 - */ - @Override - public O next() { - return transform(iterator.next()); - } - - @Override - 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); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/UniqueFilterIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/UniqueFilterIterator.java deleted file mode 100644 index de8e29b8eb..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/UniqueFilterIterator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; - -import repack.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. - * - * @param the type of elements returned by this iterator. - * @since 2.1 - */ -public class UniqueFilterIterator extends FilterIterator { - - /** - * Constructs a new {@code UniqueFilterIterator}. - * - * @param iterator the iterator to use - */ - public UniqueFilterIterator(final Iterator iterator) { - super(iterator, UniquePredicate.uniquePredicate()); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableIterator.java deleted file mode 100644 index f20dfa61d9..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableIterator.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Iterator; -import java.util.Objects; - -import repack.apache.commons.collections4.Unmodifiable; - -/** - * Decorates an iterator such that it cannot be modified. - *

- * Attempts to modify it will result in an UnsupportedOperationException. - *

- * - * @param the type of elements returned by this iterator. - * @since 3.0 - */ -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 NullPointerException if the iterator is null - */ - public static Iterator unmodifiableIterator(final Iterator iterator) { - Objects.requireNonNull(iterator, "iterator"); - 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) { - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public E next() { - return iterator.next(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove() is not supported"); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableListIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableListIterator.java deleted file mode 100644 index 7c4fe3038a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableListIterator.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.ListIterator; -import java.util.Objects; - -import repack.apache.commons.collections4.Unmodifiable; - -/** - * Decorates a list iterator such that it cannot be modified. - *

- * Attempts to modify it will result in an UnsupportedOperationException. - *

- * - * @param the type of elements returned by this iterator. - * @since 3.0 - */ -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 NullPointerException if the iterator is null - */ - public static ListIterator unmodifiableListIterator(final ListIterator iterator) { - Objects.requireNonNull(iterator, "iterator"); - if (iterator instanceof Unmodifiable) { - @SuppressWarnings("unchecked") // safe to upcast - final ListIterator tmpIterator = (ListIterator) iterator; - return tmpIterator; - } - return new UnmodifiableListIterator<>(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 NullPointerException if the iterator is null - * @deprecated method name has typo in it. Use {@link repack.apache.commons.collections4.iterators.UnmodifiableListIterator#unmodifiableListIterator(ListIterator)} instead. - */ - @Deprecated - public static ListIterator umodifiableListIterator(final ListIterator iterator) { - return unmodifiableListIterator(iterator); - } - - /** - * Constructor. - * - * @param iterator the iterator to decorate - */ - private UnmodifiableListIterator(final ListIterator iterator) { - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public E next() { - return iterator.next(); - } - - @Override - public int nextIndex() { - return iterator.nextIndex(); - } - - @Override - public boolean hasPrevious() { - return iterator.hasPrevious(); - } - - @Override - public E previous() { - return iterator.previous(); - } - - @Override - public int previousIndex() { - return iterator.previousIndex(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove() is not supported"); - } - - @Override - public void set(final E obj) { - throw new UnsupportedOperationException("set() is not supported"); - } - - @Override - public void add(final E obj) { - throw new UnsupportedOperationException("add() is not supported"); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableMapIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableMapIterator.java deleted file mode 100644 index 38524c40a3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableMapIterator.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Objects; - -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.Unmodifiable; - -/** - * Decorates a map iterator such that it cannot be modified. - *

- * Attempts to modify it will result in an UnsupportedOperationException. - *

- * - * @param the type of keys - * @param the type of mapped values - * @since 3.0 - */ -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 NullPointerException if the iterator is null - */ - public static MapIterator unmodifiableMapIterator( - final MapIterator iterator) { - Objects.requireNonNull(iterator, "iterator"); - 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) { - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public K next() { - return iterator.next(); - } - - @Override - public K getKey() { - return iterator.getKey(); - } - - @Override - public V getValue() { - return iterator.getValue(); - } - - @Override - public V setValue(final V value) { - throw new UnsupportedOperationException("setValue() is not supported"); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove() is not supported"); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableOrderedMapIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableOrderedMapIterator.java deleted file mode 100644 index 859e7c4078..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/UnmodifiableOrderedMapIterator.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.Objects; - -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.Unmodifiable; - -/** - * Decorates an ordered map iterator such that it cannot be modified. - *

- * Attempts to modify it will result in an UnsupportedOperationException. - *

- * - * @param the type of keys - * @param the type of mapped values - * @since 3.0 - */ -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 NullPointerException if the iterator is null - */ - public static OrderedMapIterator unmodifiableOrderedMapIterator( - final OrderedMapIterator iterator) { - Objects.requireNonNull(iterator, "iterator"); - 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) { - this.iterator = iterator; - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public K next() { - return iterator.next(); - } - - @Override - public boolean hasPrevious() { - return iterator.hasPrevious(); - } - - @Override - public K previous() { - return iterator.previous(); - } - - @Override - public K getKey() { - return iterator.getKey(); - } - - @Override - public V getValue() { - return iterator.getValue(); - } - - @Override - public V setValue(final V value) { - throw new UnsupportedOperationException("setValue() is not supported"); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("remove() is not supported"); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/ZippingIterator.java b/src/main/java/repack/apache/commons/collections4/iterators/ZippingIterator.java deleted file mode 100644 index f0c043ac31..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/ZippingIterator.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.iterators; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Objects; - -import repack.apache.commons.collections4.FluentIterable; - -/** - * Provides an interleaved iteration over the elements contained in a - * collection of Iterators. - *

- * Given two {@link Iterator} instances {@code A} and {@code B}, the - * {@link #next} method on this iterator will switch between {@code A.next()} - * and {@code B.next()} until both iterators are exhausted. - *

- * - * @param the type of elements returned by this iterator. - * @since 4.1 - */ -public class ZippingIterator implements Iterator { - - /** The {@link Iterator}s to evaluate. */ - private final Iterator> iterators; - - /** The next iterator to use for next(). */ - private Iterator nextIterator; - - /** The last iterator which was used for next(). */ - private Iterator lastReturned; - - /** - * Constructs a new {@code ZippingIterator} that will provide - * interleaved iteration over the two given iterators. - * - * @param a the first child iterator - * @param b the second child iterator - * @throws NullPointerException if either iterator is null - */ - @SuppressWarnings("unchecked") - public ZippingIterator(final Iterator a, final Iterator b) { - this(new Iterator[] {a, b}); - } - - /** - * Constructs a new {@code ZippingIterator} that will provide - * interleaved iteration over the three given iterators. - * - * @param a the first child iterator - * @param b the second child iterator - * @param c the third child iterator - * @throws NullPointerException if either iterator is null - */ - @SuppressWarnings("unchecked") - public ZippingIterator(final Iterator a, - final Iterator b, - final Iterator c) { - this(new Iterator[] {a, b, c}); - } - - /** - * Constructs a new {@code ZippingIterator} that will provide - * interleaved iteration of the specified iterators. - * - * @param iterators the array of iterators - * @throws NullPointerException if any iterator is null - */ - public ZippingIterator(final Iterator... iterators) { - // create a mutable list to be able to remove exhausted iterators - final List> list = new ArrayList<>(); - for (final Iterator iterator : iterators) { - Objects.requireNonNull(iterator, "iterator"); - list.add(iterator); - } - this.iterators = FluentIterable.of(list).loop().iterator(); - } - - /** - * Returns {@code true} if any child iterator has remaining elements. - * - * @return true if this iterator has remaining elements - */ - @Override - public boolean hasNext() { - // the next iterator has already been determined - // this might happen if hasNext() is called multiple - if (nextIterator != null) { - return true; - } - - while (iterators.hasNext()) { - final Iterator childIterator = iterators.next(); - if (childIterator.hasNext()) { - nextIterator = childIterator; - return true; - } - // iterator is exhausted, remove it - iterators.remove(); - } - return false; - } - - /** - * Returns the next element from a child iterator. - * - * @return the next interleaved element - * @throws NoSuchElementException if no child iterator has any more elements - */ - @Override - public E next() throws NoSuchElementException { - if (!hasNext()) { - throw new NoSuchElementException(); - } - - final E val = nextIterator.next(); - lastReturned = nextIterator; - nextIterator = null; - 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 - */ - @Override - public void remove() { - if (lastReturned == null) { - throw new IllegalStateException("No value can be removed at present"); - } - lastReturned.remove(); - lastReturned = null; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/iterators/package-info.java b/src/main/java/repack/apache/commons/collections4/iterators/package-info.java deleted file mode 100644 index 864b765884..0000000000 --- a/src/main/java/repack/apache/commons/collections4/iterators/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 repack.apache.commons.collections4.IteratorUtils IteratorUtils}, - * which is a single class that uses static methods to construct instances - * of the classes in this package. - * - */ -package repack.apache.commons.collections4.iterators; diff --git a/src/main/java/repack/apache/commons/collections4/keyvalue/AbstractKeyValue.java b/src/main/java/repack/apache/commons/collections4/keyvalue/AbstractKeyValue.java deleted file mode 100644 index 1230d7519a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/keyvalue/AbstractKeyValue.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.keyvalue; - -import repack.apache.commons.collections4.KeyValue; - -/** - * Abstract pair class to assist with creating {@code KeyValue} - * and {@link java.util.Map.Entry Map.Entry} implementations. - * - * @param the type of keys - * @param the type of values - * @since 3.0 - */ -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) { - this.key = key; - this.value = value; - } - - /** - * Gets the key from the pair. - * - * @return the key - */ - @Override - public K getKey() { - return key; - } - - protected K setKey(final K key) { - final K old = this.key; - this.key = key; - return old; - } - - /** - * Gets the value from the pair. - * - * @return the value - */ - @Override - public V getValue() { - return value; - } - - protected V setValue(final 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/keyvalue/AbstractMapEntry.java b/src/main/java/repack/apache/commons/collections4/keyvalue/AbstractMapEntry.java deleted file mode 100644 index de6bfdda48..0000000000 --- a/src/main/java/repack/apache/commons/collections4/keyvalue/AbstractMapEntry.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.keyvalue; - -import java.util.Map; - -/** - * Abstract Pair class to assist with creating correct - * {@link java.util.Map.Entry Map.Entry} implementations. - * - * @param the type of keys - * @param the type of mapped values - * @since 3.0 - */ -public abstract class AbstractMapEntry extends AbstractKeyValue implements Map.Entry { - - /** - * Constructs a new entry with the given key and given value. - * - * @param key the key for the entry, may be null - * @param value the value for the entry, may be null - */ - protected AbstractMapEntry(final K key, final V value) { - super(key, value); - } - - /** - * Sets the value stored in this {@code Map.Entry}. - *

- * This {@code 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) { // NOPMD - return super.setValue(value); - } - - /** - * Compares this {@code Map.Entry} with another {@code 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)) { - 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()); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/keyvalue/AbstractMapEntryDecorator.java b/src/main/java/repack/apache/commons/collections4/keyvalue/AbstractMapEntryDecorator.java deleted file mode 100644 index 729f34ed42..0000000000 --- a/src/main/java/repack/apache/commons/collections4/keyvalue/AbstractMapEntryDecorator.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.keyvalue; - -import java.util.Map; -import java.util.Objects; - -import repack.apache.commons.collections4.KeyValue; - -/** - * Provides a base decorator that allows additional functionality to be - * added to a {@link java.util.Map.Entry Map.Entry}. - * - * @param the type of keys - * @param the type of mapped values - * @since 3.0 - */ -public abstract class AbstractMapEntryDecorator implements Map.Entry, KeyValue { - - /** The {@code Map.Entry} to decorate */ - private final Map.Entry entry; - - /** - * Constructor that wraps (not copies). - * - * @param entry the {@code Map.Entry} to decorate, must not be null - * @throws NullPointerException if the collection is null - */ - public AbstractMapEntryDecorator(final Map.Entry entry) { - this.entry = Objects.requireNonNull(entry, "entry"); - } - - /** - * Gets the map being decorated. - * - * @return the decorated map - */ - protected Map.Entry getMapEntry() { - return entry; - } - - - @Override - public K getKey() { - return entry.getKey(); - } - - @Override - public V getValue() { - return entry.getValue(); - } - - @Override - 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/keyvalue/DefaultKeyValue.java b/src/main/java/repack/apache/commons/collections4/keyvalue/DefaultKeyValue.java deleted file mode 100644 index bd5799b284..0000000000 --- a/src/main/java/repack/apache/commons/collections4/keyvalue/DefaultKeyValue.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.keyvalue; - -import java.util.Map; - -import repack.apache.commons.collections4.KeyValue; - -/** - * A mutable {@code KeyValue} pair that does not implement - * {@link java.util.Map.Entry Map.Entry}. - *

- * Note that a {@code DefaultKeyValue} instance may not contain - * itself as a key or value. - *

- * - * @param the type of keys - * @param the type of values - * @since 3.0 - */ -public class DefaultKeyValue extends AbstractKeyValue { - - /** - * Constructs a new pair with a null key and null value. - */ - public DefaultKeyValue() { - super(null, null); - } - - /** - * Constructs a new pair with the specified key and given value. - * - * @param key the key for the entry, may be null - * @param value the value for the entry, may be null - */ - public DefaultKeyValue(final K key, final V value) { - super(key, value); - } - - /** - * Constructs a new pair from the specified {@code 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 {@code 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 {@code Map.Entry} object with key and value from this pair. - * - * @return a MapEntry instance - */ - public Map.Entry toMapEntry() { - return new DefaultMapEntry<>(this); - } - - /** - * Compares this {@code Map.Entry} with another {@code Map.Entry}. - *

- * Returns true if the compared object is also a {@code 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)) { - 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()); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/keyvalue/DefaultMapEntry.java b/src/main/java/repack/apache/commons/collections4/keyvalue/DefaultMapEntry.java deleted file mode 100644 index feb72d88a9..0000000000 --- a/src/main/java/repack/apache/commons/collections4/keyvalue/DefaultMapEntry.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.keyvalue; - -import java.util.Map; - -import repack.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. - * - * @param the type of keys - * @param the type of mapped values - * @since 3.0 - */ -public final class DefaultMapEntry extends AbstractMapEntry { - - /** - * Constructs a new entry with the specified key and given value. - * - * @param key the key for the entry, may be null - * @param value the value for the entry, may be null - */ - public DefaultMapEntry(final K key, final V value) { - super(key, value); - } - - /** - * Constructs a new entry from the specified {@code 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 {@code 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()); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/keyvalue/MultiKey.java b/src/main/java/repack/apache/commons/collections4/keyvalue/MultiKey.java deleted file mode 100644 index 7826ea8e39..0000000000 --- a/src/main/java/repack/apache/commons/collections4/keyvalue/MultiKey.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.keyvalue; - -import java.io.Serializable; -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.Objects; - -/** - * A {@code 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);
- * 
- * - * @param the type of keys - * @since 3.0 - */ -public class MultiKey implements Serializable { - // This class could implement List, but that would confuse its purpose - - /** Serialisation version */ - private static final long serialVersionUID = 4465448607415788805L; - - @SuppressWarnings("unchecked") - private static Class getClass(final T value) { - return (Class) (value == null ? Object.class : value.getClass()); - } - - private static Class getComponentType(final T... values) { - @SuppressWarnings("unchecked") - final Class rootClass = (Class) Object.class; - if (values == null) { - return rootClass; - } - Class prevClass = values.length > 0 ? getClass(values[0]) : rootClass; - for (int i = 1; i < values.length; i++) { - final Class classI = getClass(values[i]); - if (prevClass != classI) { - return rootClass; - } - prevClass = classI; - } - return prevClass; - } - - private static T[] newArray(final T key1, final T key2) { - @SuppressWarnings("unchecked") - final T[] array = (T[]) Array.newInstance(getComponentType(key1, key2), 2); - array[0] = key1; - array[1] = key2; - return array; - } - - private static T[] newArray(final T key1, final T key2, final T key3) { - @SuppressWarnings("unchecked") - final T[] array = (T[]) Array.newInstance(getComponentType(key1, key2, key3), 3); - array[0] = key1; - array[1] = key2; - array[2] = key3; - return array; - } - - private static T[] newArray(final T key1, final T key2, final T key3, final T key4) { - @SuppressWarnings("unchecked") - final T[] array = (T[]) Array.newInstance(getComponentType(key1, key2, key3, key4), 4); - array[0] = key1; - array[1] = key2; - array[2] = key3; - array[3] = key4; - return array; - } - - private static T[] newArray(final T key1, final T key2, final T key3, final T key4, final T key5) { - @SuppressWarnings("unchecked") - final T[] array = (T[]) Array.newInstance(getComponentType(key1, key2, key3, key4, key5), 5); - array[0] = key1; - array[1] = key2; - array[2] = key3; - array[3] = key4; - array[4] = key5; - return array; - } - - /** 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 - */ - public MultiKey(final K key1, final K key2) { - this(newArray(key1, key2), false); - } - - - /** - * Constructor taking three keys. - *

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

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

- * The keys should be immutable - * If they are not then they must not be changed after adding to the MultiKey. - * - * @param key1 the first key - * @param key2 the second key - * @param key3 the third key - * @param key4 the fourth key - * @param key5 the fifth key - */ - public MultiKey(final K key1, final K key2, final K key3, final K key4, final K key5) { - this(newArray(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 {@code new MultiKey(keys, true)}. - * - * @param keys the array of keys, not null - * @throws NullPointerException 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 NullPointerException if the key array is null - * @since 3.1 - */ - public MultiKey(final K[] keys, final boolean makeClone) { - Objects.requireNonNull(keys, "keys"); - this.keys = makeClone ? keys.clone() : keys; - calculateHashCode(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; - } - - /** - * Compares this object to another. - *

- * To be equal, the other object must be a {@code 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 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 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 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; - } - - /** - * 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 - */ - protected Object readResolve() { - calculateHashCode(keys); - return this; - } - - /** - * 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; - } - - /** - * Gets a debugging string version of the key. - * - * @return a debugging string - */ - @Override - public String toString() { - return "MultiKey" + Arrays.toString(keys); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/keyvalue/TiedMapEntry.java b/src/main/java/repack/apache/commons/collections4/keyvalue/TiedMapEntry.java deleted file mode 100644 index f4120b6291..0000000000 --- a/src/main/java/repack/apache/commons/collections4/keyvalue/TiedMapEntry.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.keyvalue; - -import java.io.Serializable; -import java.util.Map; - -import repack.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. - *

- * - * @param the type of keys - * @param the type of mapped values - * @since 3.0 - */ -public class TiedMapEntry implements Map.Entry, KeyValue, Serializable { - - /** Serialization version */ - private static final long serialVersionUID = -8453869361373831205L; - - /** The map underlying the entry/iterator */ - private final Map map; - - /** The key */ - private final K key; - - /** - * Constructs a new entry with the given Map and key. - * - * @param map the map - * @param key the key - */ - public TiedMapEntry(final Map map, final K key) { - this.map = map; - this.key = key; - } - - /** - * Gets the key of this entry - * - * @return the key - */ - @Override - public K getKey() { - return key; - } - - /** - * Gets the value of this entry direct from the map. - * - * @return the value - */ - @Override - 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 - */ - @Override - 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 {@code Map.Entry} with another {@code 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)) { - 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/keyvalue/UnmodifiableMapEntry.java b/src/main/java/repack/apache/commons/collections4/keyvalue/UnmodifiableMapEntry.java deleted file mode 100644 index a6c5e385b5..0000000000 --- a/src/main/java/repack/apache/commons/collections4/keyvalue/UnmodifiableMapEntry.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.keyvalue; - -import java.util.Map; - -import repack.apache.commons.collections4.KeyValue; -import repack.apache.commons.collections4.Unmodifiable; - -/** - * A {@link java.util.Map.Entry Map.Entry} that throws - * UnsupportedOperationException when {@code setValue} is called. - * - * @param the type of keys - * @param the type of mapped values - * @since 3.0 - */ -public final class UnmodifiableMapEntry extends AbstractMapEntry implements Unmodifiable { - - /** - * Constructs a new entry with the specified key and given value. - * - * @param key the key for the entry, may be null - * @param value the value for the entry, may be null - */ - public UnmodifiableMapEntry(final K key, final V value) { - super(key, value); - } - - /** - * Constructs a new entry from the specified {@code 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 {@code 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"); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/keyvalue/package-info.java b/src/main/java/repack/apache/commons/collections4/keyvalue/package-info.java deleted file mode 100644 index 67151b511f..0000000000 --- a/src/main/java/repack/apache/commons/collections4/keyvalue/package-info.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 - *
- * - */ -package repack.apache.commons.collections4.keyvalue; diff --git a/src/main/java/repack/apache/commons/collections4/list/AbstractLinkedList.java b/src/main/java/repack/apache/commons/collections4/list/AbstractLinkedList.java deleted file mode 100644 index 05ed65dd1a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/AbstractLinkedList.java +++ /dev/null @@ -1,1080 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.Objects; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.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 - */ -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 {@code next} is the first item in the - * list. The value of {@code 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() { - } - - /** - * Constructs a list copying data from the specified collection. - * - * @param coll the collection to copy - */ - protected AbstractLinkedList(final Collection coll) { - init(); - addAll(coll); - } - - /** - * The equivalent of a default constructor, broken out so it can be called - * by any constructor and by {@code readObject}. - * Subclasses which override this method should make sure they call super, - * so the list is initialized properly. - */ - protected void init() { - header = createHeaderNode(); - } - - - @Override - public int size() { - return size; - } - - @Override - public boolean isEmpty() { - return size() == 0; - } - - @Override - public E get(final int index) { - final Node node = getNode(index, false); - return node.getValue(); - } - - - @Override - public Iterator iterator() { - return listIterator(); - } - - @Override - public ListIterator listIterator() { - return new LinkedListIterator<>(this, 0); - } - - @Override - public ListIterator listIterator(final int fromIndex) { - return new LinkedListIterator<>(this, fromIndex); - } - - - @Override - 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 CollectionUtils.INDEX_NOT_FOUND; - } - - @Override - 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 CollectionUtils.INDEX_NOT_FOUND; - } - - @Override - public boolean contains(final Object value) { - return indexOf(value) != -1; - } - - @Override - public boolean containsAll(final Collection coll) { - for (final Object o : coll) { - if (!contains(o)) { - return false; - } - } - return true; - } - - - @Override - public Object[] toArray() { - return toArray(new Object[size]); - } - - @Override - @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 - */ - @Override - public List subList(final int fromIndexInclusive, final int toIndexExclusive) { - return new LinkedSubList<>(this, fromIndexInclusive, toIndexExclusive); - } - - - @Override - public boolean add(final E value) { - addLast(value); - return true; - } - - @Override - public void add(final int index, final E value) { - final Node node = getNode(index, true); - addNodeBefore(node, value); - } - - @Override - public boolean addAll(final Collection coll) { - return addAll(size, coll); - } - - @Override - 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; - } - - - @Override - public E remove(final int index) { - final Node node = getNode(index, false); - final E oldValue = node.getValue(); - removeNode(node); - return oldValue; - } - - @Override - 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 {@code coll}. If it's contained, it's removed - * from this list. As a consequence, it is advised to use a collection type for - * {@code coll} that provides a fast (e.g. O(1)) implementation of - * {@link Collection#contains(Object)}. - */ - @Override - 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 {@code coll}. If it's not contained, it's removed - * from this list. As a consequence, it is advised to use a collection type for - * {@code coll} that provides a fast (e.g. O(1)) implementation of - * {@link Collection#contains(Object)}. - */ - @Override - public boolean retainAll(final Collection coll) { - boolean modified = false; - final Iterator it = iterator(); - while (it.hasNext()) { - if (!coll.contains(it.next())) { - it.remove(); - modified = true; - } - } - return modified; - } - - @Override - 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; - } - - @Override - 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)) { - 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()) { - if (!Objects.equals(it1.next(), it2.next())) { - 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 (isEmpty()) { - return "[]"; - } - final StringBuilder buf = new StringBuilder(16 * size()); - buf.append(CollectionUtils.DEFAULT_TOSTRING_PREFIX); - - 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(CollectionUtils.DEFAULT_TOSTRING_SUFFIX); - 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 Objects.equals(value1, 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 - * {@code value} and inserts it before {@code 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 {@code 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 - * {@code value} and inserts it after {@code 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 {@code 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) { - Objects.requireNonNull(nodeToInsert, "nodeToInsert"); - Objects.requireNonNull(insertBeforeNode, "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 {@code node} is null - */ - protected void removeNode(final Node node) { - Objects.requireNonNull(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 - * {@code 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 - * {@code 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 {@code 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() { - previous = this; - next = this; - } - - /** - * Constructs a new node. - * - * @param value the value to store - */ - protected Node(final E value) { - 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) { - 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 {@code 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 behavior. - */ - 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 { - 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; - } - - @Override - public boolean hasNext() { - return next != parent.header; - } - - @Override - 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; - } - - @Override - public boolean hasPrevious() { - return next.previous != parent.header; - } - - @Override - 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; - } - - @Override - public int nextIndex() { - return nextIndex; - } - - @Override - public int previousIndex() { - // not normally overridden, as relative to nextIndex() - return nextIndex() - 1; - } - - @Override - 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++; - } - - @Override - public void set(final E obj) { - checkModCount(); - getLastNodeReturned().setValue(obj); - } - - @Override - 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 sub 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++; - modCount++; - } - - @Override - public E remove(final int index) { - rangeCheck(index, size); - checkModCount(); - final E result = parent.remove(index + offset); - expectedModCount = parent.modCount; - size--; - 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; - 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(); - } - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/AbstractListDecorator.java b/src/main/java/repack/apache/commons/collections4/list/AbstractListDecorator.java deleted file mode 100644 index 0c9c01d521..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/AbstractListDecorator.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.list; - -import java.util.Collection; -import java.util.List; -import java.util.ListIterator; - -import repack.apache.commons.collections4.collection.AbstractCollectionDecorator; - -/** - * Decorates another {@link List} to provide additional behavior. - *

- * Methods are forwarded directly to the decorated list. - *

- * - * @param the type of the elements in the list - * @since 3.0 - */ -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() { - } - - /** - * Constructor that wraps (not copies). - * - * @param list the list to decorate, must not be null - * @throws NullPointerException 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(); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - - - @Override - public void add(final int index, final E object) { - decorated().add(index, object); - } - - @Override - public boolean addAll(final int index, final Collection coll) { - return decorated().addAll(index, coll); - } - - @Override - public E get(final int index) { - return decorated().get(index); - } - - @Override - public int indexOf(final Object object) { - return decorated().indexOf(object); - } - - @Override - public int lastIndexOf(final Object object) { - return decorated().lastIndexOf(object); - } - - @Override - public ListIterator listIterator() { - return decorated().listIterator(); - } - - @Override - public ListIterator listIterator(final int index) { - return decorated().listIterator(index); - } - - @Override - public E remove(final int index) { - return decorated().remove(index); - } - - @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) { - return decorated().subList(fromIndex, toIndex); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/AbstractSerializableListDecorator.java b/src/main/java/repack/apache/commons/collections4/list/AbstractSerializableListDecorator.java deleted file mode 100644 index 3cebc0ac5a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/AbstractSerializableListDecorator.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -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 NullPointerException 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 if an error occurs while writing to the stream - */ - 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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - */ - @SuppressWarnings("unchecked") - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - setCollection((Collection) in.readObject()); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/CursorableLinkedList.java b/src/main/java/repack/apache/commons/collections4/list/CursorableLinkedList.java deleted file mode 100644 index d65a93818c..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/CursorableLinkedList.java +++ /dev/null @@ -1,613 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 {@code List} implementation with a {@code ListIterator} that - * allows concurrent modifications to the underlying list. - *

- * This implementation supports all of the optional {@link List} operations. - * It extends {@code 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 {@code Cursor} instance which extends - * {@code 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 behavior. - *

- *

- * The {@code 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 {@code 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 - */ -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() { - 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 {@code 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 behavior 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 {@code Cursor} is a {@code ListIterator} with an additional - * {@code 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 {@code 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 {@code Cursor} if the {@code 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 {@code Cursor} is a {@code ListIterator} with an additional - * {@code 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 {@code 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 {@code Cursor} if the {@code 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 {@code 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 (!isEmpty()) { - // 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. - cursors.removeIf(ref -> ref.get() == null); - 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. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - doWriteObject(out); - } - - /** - * Deserializes the data held in this object to the stream specified. - * - * @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 - */ - 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 {@code 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; - - /** - * 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 of - // 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) { - 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.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--; - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/FixedSizeList.java b/src/main/java/repack/apache/commons/collections4/list/FixedSizeList.java deleted file mode 100644 index e329f98838..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/FixedSizeList.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.list; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.BoundedCollection; -import repack.apache.commons.collections4.iterators.AbstractListIteratorDecorator; -import repack.apache.commons.collections4.iterators.UnmodifiableIterator; - -/** - * Decorates another {@code 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). - *

- *

- * NOTE: - * Modifying the decorated list directly would results in influencing the outcome - * of method calls on this object. For example, the bounds of this list would reflect - * a newly added object to the underlying list. - *

- *

- * This class is Serializable from Commons Collections 3.1. - *

- * - * @param the type of elements in this collection - * @since 3.0 - */ -public class FixedSizeList - extends AbstractSerializableListDecorator - implements BoundedCollection { - - /** Serialization version */ - private static final long serialVersionUID = -2218010673611160319L; - - /** - * Factory method to create a fixed size list. - * - * @param 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 NullPointerException 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 NullPointerException if list is null - */ - protected FixedSizeList(final List list) { - super(list); - } - - @Override - public boolean add(final E object) { - throw unsupportedOperationException(); - } - - @Override - public void add(final int index, final E object) { - throw unsupportedOperationException(); - } - - @Override - public boolean addAll(final Collection coll) { - throw unsupportedOperationException(); - } - - @Override - public boolean addAll(final int index, final Collection coll) { - throw unsupportedOperationException(); - } - - @Override - public void clear() { - throw unsupportedOperationException(); - } - - @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 unsupportedOperationException(); - } - - @Override - public boolean remove(final Object object) { - throw unsupportedOperationException(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - throw unsupportedOperationException(); - } - - @Override - public boolean removeAll(final Collection coll) { - throw unsupportedOperationException(); - } - - @Override - public boolean retainAll(final Collection coll) { - throw unsupportedOperationException(); - } - - @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 unsupportedOperationException(); - } - @Override - public void add(final Object object) { - throw unsupportedOperationException(); - } - } - - @Override - public boolean isFull() { - return true; - } - - @Override - public int maxSize() { - return size(); - } - - private static UnsupportedOperationException unsupportedOperationException() { - return new UnsupportedOperationException("List is fixed size"); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/GrowthList.java b/src/main/java/repack/apache/commons/collections4/list/GrowthList.java deleted file mode 100644 index c8982d6ef2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/GrowthList.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.list; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -/** - * Decorates another {@code 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 {@code 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 {@code null} values, as - * {@code 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 {@code LazyList} grows on get. However, they - * can be used together by decorating twice. - *

- * - * @see LazyList - * @since 3.2 - */ -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 NullPointerException 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 initialCapacity the initial capacity of the ArrayList - * @throws IllegalArgumentException if initial capacity is invalid - */ - public GrowthList(final int initialCapacity) { - super(new ArrayList<>(initialCapacity)); - } - - /** - * Constructor that wraps (not copies). - * - * @param list the list to decorate, must not be null - * @throws NullPointerException if list is null - */ - protected GrowthList(final List list) { - super(list); - } - - /** - * Decorate the add method to perform the growth behavior. - *

- * 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 {@code 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 behavior. - *

- * 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 {@code 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 behavior. - *

- * 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 {@code 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/LazyList.java b/src/main/java/repack/apache/commons/collections4/list/LazyList.java deleted file mode 100644 index f0ef27e6b8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/LazyList.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.list; - -import java.util.List; -import java.util.Objects; - -import repack.apache.commons.collections4.Factory; -import repack.apache.commons.collections4.Transformer; - -/** - * Decorates another {@code 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 or transformer. 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, {@code date} will contain - * a new {@code Date} instance. Furthermore, that {@code Date} - * instance is the fourth element in the list. The first, second, - * and third element are all set to {@code null}. - *

- *

- * This class differs from {@link GrowthList} because here growth occurs on - * get, where {@code 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 - */ -public class LazyList extends AbstractSerializableListDecorator { - - /** Serialization version */ - private static final long serialVersionUID = -3677737457567429713L; - - /** The factory to use to lazily instantiate the objects */ - private final Factory factory; - - /** The transformer to use to lazily instantiate the objects */ - private final Transformer transformer; - - /** - * 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 NullPointerException if list or factory is null - * @since 4.0 - */ - public static LazyList lazyList(final List list, final Factory factory) { - return new LazyList<>(list, factory); - } - - /** - * Transformer 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 transformer the transformer to use for creation, must not be null - * @return a new lazy list - * @throws NullPointerException if list or transformer is null - * @since 4.4 - */ - public static LazyList lazyList(final List list, final Transformer transformer) { - return new LazyList<>(list, transformer); - } - - /** - * 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 NullPointerException if list or factory is null - */ - protected LazyList(final List list, final Factory factory) { - super(list); - this.factory = Objects.requireNonNull(factory); - this.transformer = null; - } - - /** - * Constructor that wraps (not copies). - * - * @param list the list to decorate, must not be null - * @param transformer the transformer to use for creation, must not be null - * @throws NullPointerException if list or transformer is null - */ - protected LazyList(final List list, final Transformer transformer) { - super(list); - this.factory = null; - this.transformer = Objects.requireNonNull(transformer); - } - - /** - * Decorate the get method to perform the lazy behavior. - *

- * 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 - * or transformer. Indexes in-between the old size and the requested size - * are left with a placeholder that is replaced with a factory or - * transformer 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 placeholder, create new one, set and return - object = element(index); - decorated().set(index, 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 = element(index); - decorated().add(object); - return object; - } - - @Override - public List subList(final int fromIndex, final int toIndex) { - final List sub = decorated().subList(fromIndex, toIndex); - if (factory != null) { - return new LazyList<>(sub, factory); - } - if (transformer != null) { - return new LazyList<>(sub, transformer); - } - throw new IllegalStateException("Factory and Transformer are both null!"); - } - - private E element(final int index) { - if (factory != null) { - return factory.create(); - } - if (transformer != null) { - return transformer.transform(index); - } - throw new IllegalStateException("Factory and Transformer are both null!"); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/NodeCachingLinkedList.java b/src/main/java/repack/apache/commons/collections4/list/NodeCachingLinkedList.java deleted file mode 100644 index 8abf3170b5..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/NodeCachingLinkedList.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 {@code 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 - */ -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 {@code null} if no nodes are cached. - * Cached nodes are stored in a singly-linked list with - * {@code 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) { - 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 {@code null} values for next, previous and element. - * - * @return a node, or {@code 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 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. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - doWriteObject(out); - } - - /** - * Deserializes the data held in this object to the stream specified. - * - * @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 - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - doReadObject(in); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/PredicatedList.java b/src/main/java/repack/apache/commons/collections4/list/PredicatedList.java deleted file mode 100644 index 2d7d0f9e97..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/PredicatedList.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.list; - -import java.util.Collection; -import java.util.List; -import java.util.ListIterator; - -import repack.apache.commons.collections4.Predicate; -import repack.apache.commons.collections4.collection.PredicatedCollection; -import repack.apache.commons.collections4.iterators.AbstractListIteratorDecorator; - -/** - * Decorates another {@code 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. - *

- *
- * {@code
- * List list =
- *   PredicatedList.predicatedList(new ArrayList(), PredicateUtils.notNullPredicate());
- * }
- * 
- *

- * This class is Serializable from Commons Collections 3.1. - *

- * - * @since 3.0 - */ -public class PredicatedList extends PredicatedCollection implements List { - - /** Serialization version */ - private static final long serialVersionUID = -5722039223898659102L; - - /** - * Factory method to create a predicated (validating) list. - *

- * If there are any elements already in the list being decorated, they - * are validated. - * - * @param 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 NullPointerException 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 NullPointerException 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(); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - - - @Override - public E get(final int index) { - return decorated().get(index); - } - - @Override - public int indexOf(final Object object) { - return decorated().indexOf(object); - } - - @Override - public int lastIndexOf(final Object object) { - return decorated().lastIndexOf(object); - } - - @Override - public E remove(final int index) { - return decorated().remove(index); - } - - - @Override - public void add(final int index, final E object) { - validate(object); - decorated().add(index, object); - } - - @Override - public boolean addAll(final int index, final Collection coll) { - for (final E aColl : coll) { - validate(aColl); - } - return decorated().addAll(index, coll); - } - - @Override - public ListIterator listIterator() { - return listIterator(0); - } - - @Override - public ListIterator listIterator(final int i) { - return new PredicatedListIterator(decorated().listIterator(i)); - } - - @Override - public E set(final int index, final E object) { - validate(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 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); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/SetUniqueList.java b/src/main/java/repack/apache/commons/collections4/list/SetUniqueList.java deleted file mode 100644 index 9b3cb7b60a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/SetUniqueList.java +++ /dev/null @@ -1,429 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.list; - -import java.lang.reflect.InvocationTargetException; -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.Objects; -import java.util.Set; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.ListUtils; -import repack.apache.commons.collections4.iterators.AbstractIteratorDecorator; -import repack.apache.commons.collections4.iterators.AbstractListIteratorDecorator; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates a {@code List} to ensure that no duplicates are present much - * like a {@code Set}. - *

- * The {@code 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 repack.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 - */ -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 {@code HashSet} is used for the set behavior. - * - * @param the element type - * @param list the list to decorate, must not be null - * @return a new {@link SetUniqueList} - * @throws NullPointerException if list is null - * @since 4.0 - */ - public static SetUniqueList setUniqueList(final List list) { - Objects.requireNonNull(list, "list"); - 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 initialized 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 NullPointerException if set or list is null - */ - protected SetUniqueList(final List list, final Set set) { - super(list); - this.set = Objects.requireNonNull(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 {@code List} interface requires that this - * method returns {@code true} always. However this class may return - * {@code false} because of the {@code Set} behavior. - * - * @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 {@code 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)) { - set.add(object); - super.add(index, 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 {@code 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 {@code 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; - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - final boolean result = super.removeIf(filter); - set.removeIf(filter); - return result; - } - - @Override - public boolean removeAll(final Collection coll) { - boolean result = false; - for (final Object name : coll) { - result |= remove(name); - } - return result; - } - - /** - * {@inheritDoc} - *

- * This implementation iterates over the elements of this list, checking - * each element in turn to see if it's contained in {@code coll}. - * If it's not contained, it's removed from this list. As a consequence, - * it is advised to use a collection type for {@code coll} that provides - * a fast (e.g. O(1)) implementation of {@link Collection#contains(Object)}. - */ - @Override - public boolean retainAll(final Collection coll) { - final boolean result = set.retainAll(coll); - if (!result) { - return false; - } - if (set.isEmpty()) { - super.clear(); - } else { - // use the set as parameter for the call to retainAll to improve performance - super.retainAll(set); - } - return result; - } - - @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} - */ - 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().getDeclaredConstructor(set.getClass()).newInstance(set); - } catch (final InstantiationException - | IllegalAccessException - | InvocationTargetException - | NoSuchMethodException ie) { - subSet = new HashSet<>(); - } - } - subSet.addAll(list); - return subSet; - } - - /** - * Inner class iterator. - */ - static class SetListIterator extends AbstractIteratorDecorator { - - private final Set set; - private E last; - - 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; - - 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)) { - super.add(object); - set.add(object); - } - } - - @Override - public void set(final E object) { - throw new UnsupportedOperationException("ListIterator does not support set"); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/TransformedList.java b/src/main/java/repack/apache/commons/collections4/list/TransformedList.java deleted file mode 100644 index 1342b60cac..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/TransformedList.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.list; - -import java.util.Collection; -import java.util.List; -import java.util.ListIterator; - -import repack.apache.commons.collections4.Transformer; -import repack.apache.commons.collections4.collection.TransformedCollection; -import repack.apache.commons.collections4.iterators.AbstractListIteratorDecorator; - -/** - * Decorates another {@code 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 - */ -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 NullPointerException 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 NullPointerException 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 (!list.isEmpty()) { - @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 NullPointerException 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(); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - - - @Override - public E get(final int index) { - return getList().get(index); - } - - @Override - public int indexOf(final Object object) { - return getList().indexOf(object); - } - - @Override - public int lastIndexOf(final Object object) { - return getList().lastIndexOf(object); - } - - @Override - public E remove(final int index) { - return getList().remove(index); - } - - - @Override - public void add(final int index, E object) { - object = transform(object); - getList().add(index, object); - } - - @Override - public boolean addAll(final int index, Collection coll) { - coll = transform(coll); - return getList().addAll(index, coll); - } - - @Override - public ListIterator listIterator() { - return listIterator(0); - } - - @Override - public ListIterator listIterator(final int i) { - return new TransformedListIterator(getList().listIterator(i)); - } - - @Override - public E set(final int index, E object) { - object = transform(object); - return getList().set(index, object); - } - - @Override - 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); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/TreeList.java b/src/main/java/repack/apache/commons/collections4/list/TreeList.java deleted file mode 100644 index f1c8ea991d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/TreeList.java +++ /dev/null @@ -1,1125 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.list; - -import java.util.AbstractList; -import java.util.ArrayDeque; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Deque; -import java.util.Iterator; -import java.util.ListIterator; -import java.util.NoSuchElementException; -import java.util.Objects; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.OrderedIterator; - -/** - * A {@code 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 {@code ArrayList} and a {@code 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
- * 
- *

- * {@code ArrayList} is a good general purpose list implementation. - * It is faster than {@code TreeList} for most operations except inserting - * and removing in the middle of the list. {@code ArrayList} also uses less - * memory as {@code TreeList} uses one object per entry. - *

- *

- * {@code LinkedList} is rarely a good choice of implementation. - * {@code TreeList} is almost always a good replacement for it, although it - * does use slightly more memory. - *

- * - * @since 3.1 - */ -public class TreeList extends AbstractList { -// add; toArray; iterator; insert; get; indexOf; remove -// TreeList = 1260;7360;3080; 160; 170;3400; 170; -// ArrayList = 220;1480;1760; 6870; 50;1540; 7200; -// LinkedList = 270;7360;3350;55860;290720;2910;55200; - - /** The root node in the AVL tree */ - private AVLNode root; - - /** The current size of the list */ - private int size; - - /** - * Constructs a new empty list. - */ - public TreeList() { - } - - /** - * 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) { - 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 (Objects.equals(value, 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 it's a faedelung. - */ - private AVLNode getLeftSubTree() { - return leftIsPrevious ? null : left; - } - - /** - * Gets the right node, returning null if it's 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; - } - 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 newOffset) { - if (node == null) { - return 0; - } - final int oldOffset = getOffset(node); - node.relativePosition = newOffset; - 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 Deque> sAncestors = new ArrayDeque<>(); - 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; - } - otherTree = otherTree.removeMin(); - - final Deque> sAncestors = new ArrayDeque<>(); - 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(CollectionUtils.COMMA) - .append(left != null) - .append(CollectionUtils.COMMA) - .append(value) - .append(CollectionUtils.COMMA) - .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 { - 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(); - } - } - - @Override - public boolean hasNext() { - return nextIndex < parent.size(); - } - - @Override - 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; - } - - @Override - public boolean hasPrevious() { - return nextIndex > 0; - } - - @Override - 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; - } - - @Override - public int nextIndex() { - return nextIndex; - } - - @Override - public int previousIndex() { - return nextIndex() - 1; - } - - @Override - 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++; - } - - @Override - public void set(final E obj) { - checkModCount(); - if (current == null) { - throw new IllegalStateException(); - } - current.setValue(obj); - } - - @Override - public void add(final E obj) { - checkModCount(); - parent.add(nextIndex, obj); - current = null; - currentIndex = -1; - nextIndex++; - expectedModCount++; - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/UnmodifiableList.java b/src/main/java/repack/apache/commons/collections4/list/UnmodifiableList.java deleted file mode 100644 index 3de9aff1c7..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/UnmodifiableList.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.list; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableIterator; -import repack.apache.commons.collections4.iterators.UnmodifiableListIterator; - -/** - * Decorates another {@code 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 - */ -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 NullPointerException 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 NullPointerException 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - 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.unmodifiableListIterator(decorated().listIterator()); - } - - @Override - public ListIterator listIterator(final int index) { - return UnmodifiableListIterator.unmodifiableListIterator(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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/list/package-info.java b/src/main/java/repack/apache/commons/collections4/list/package-info.java deleted file mode 100644 index f7af2a8b72..0000000000 --- a/src/main/java/repack/apache/commons/collections4/list/package-info.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 erring when set/add used with index beyond the list size
  • - *
  • SetUnique - a list that avoids duplicate entries like a Set
  • - *
- * - */ -package repack.apache.commons.collections4.list; diff --git a/src/main/java/repack/apache/commons/collections4/map/AbstractHashedMap.java b/src/main/java/repack/apache/commons/collections4/map/AbstractHashedMap.java deleted file mode 100644 index 5c59540298..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/AbstractHashedMap.java +++ /dev/null @@ -1,1398 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.Arrays; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.IterableMap; -import repack.apache.commons.collections4.KeyValue; -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.iterators.EmptyIterator; -import repack.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 {@code 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 behavior, 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 v5.0. - * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class AbstractHashedMap extends AbstractMap implements IterableMap { - - protected static final String NO_NEXT_ENTRY = "No next() entry in the iteration"; - protected static final String NO_PREVIOUS_ENTRY = "No previous() entry in the iteration"; - protected static final String REMOVE_INVALID = "remove() can only be called once after next()"; - protected static final String GETKEY_INVALID = "getKey() can only be called after next() and before remove()"; - protected static final String GETVALUE_INVALID = "getValue() can only be called after next() and before remove()"; - protected static final String SETVALUE_INVALID = "setValue() can only be called after next() and before remove()"; - - /** The default capacity to use */ - protected static final int DEFAULT_CAPACITY = 16; - /** The default threshold to use */ - protected static final int DEFAULT_THRESHOLD = 12; - /** The default load factor to use */ - protected static final float DEFAULT_LOAD_FACTOR = 0.75f; - /** The maximum capacity allowed */ - protected static final int MAXIMUM_CAPACITY = 1 << 30; - /** An object for masking null */ - protected static final Object NULL = new Object(); - - /** Load factor, normally 0.75 */ - 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() { - } - - /** - * 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) { - 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) { - 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); - } - - /** - * Initialize subclasses during construction, cloning or deserialization. - */ - protected void init() { - // noop - } - - /** - * 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 overridden. - * - * @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; - Arrays.fill(data, 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 {@code 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 {@code 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 {@code 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 {@code createEntry()}, {@code addEntry()} - * and {@code checkCapacity()}. - * It also handles changes to {@code modCount} and {@code 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 {@code removeEntry()} and {@code destroyEntry()}. - * It also handles changes to {@code modCount} and {@code 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 {@code next} field from a {@code HashEntry}. - * Used in subclasses that have no visibility of the field. - * - * @param entry the entry to query, must not be null - * @return the {@code 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 {@code hashCode} field from a {@code HashEntry}. - * Used in subclasses that have no visibility of the field. - * - * @param entry the entry to query, must not be null - * @return the {@code 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 {@code key} field from a {@code HashEntry}. - * Used in subclasses that have no visibility of the field. - * - * @param entry the entry to query, must not be null - * @return the {@code 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 {@code value} field from a {@code HashEntry}. - * Used in subclasses that have no visibility of the field. - * - * @param entry the entry to query, must not be null - * @return the {@code 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 - */ - @Override - public MapIterator mapIterator() { - if (size == 0) { - return EmptyMapIterator.emptyMapIterator(); - } - return new HashMapIterator<>(this); - } - - /** - * MapIterator implementation. - * - * @param the type of the keys in the map - * @param the type of the values in the map - */ - protected static class HashMapIterator extends HashIterator implements MapIterator { - - protected HashMapIterator(final AbstractHashedMap parent) { - super(parent); - } - - @Override - public K next() { - return super.nextEntry().getKey(); - } - - @Override - public K getKey() { - final HashEntry current = currentEntry(); - if (current == null) { - throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); - } - return current.getKey(); - } - - @Override - public V getValue() { - final HashEntry current = currentEntry(); - if (current == null) { - throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); - } - return current.getValue(); - } - - @Override - 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 (isEmpty()) { - return EmptyIterator.>emptyIterator(); - } - return new EntrySetIterator<>(this); - } - - /** - * EntrySet implementation. - * - * @param the type of the keys in the map - * @param the type of the values in the map - */ - protected static class EntrySet extends AbstractSet> { - /** The parent map */ - private final AbstractHashedMap parent; - - protected EntrySet(final AbstractHashedMap parent) { - 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)) { - return false; - } - if (!contains(obj)) { - return false; - } - final Map.Entry entry = (Map.Entry) obj; - parent.remove(entry.getKey()); - return true; - } - - @Override - public Iterator> iterator() { - return parent.createEntrySetIterator(); - } - } - - /** - * EntrySet iterator. - * - * @param the type of the keys in the map - * @param the type of the values in the map - */ - protected static class EntrySetIterator extends HashIterator implements Iterator> { - - protected EntrySetIterator(final AbstractHashedMap parent) { - super(parent); - } - - @Override - 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 (isEmpty()) { - return EmptyIterator.emptyIterator(); - } - return new KeySetIterator<>(this); - } - - /** - * KeySet implementation. - * - * @param the type of elements maintained by this set - */ - protected static class KeySet extends AbstractSet { - /** The parent map */ - private final AbstractHashedMap parent; - - protected KeySet(final AbstractHashedMap parent) { - 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. - * - * @param the type of elements maintained by this set - */ - protected static class KeySetIterator extends HashIterator implements Iterator { - - @SuppressWarnings("unchecked") - protected KeySetIterator(final AbstractHashedMap parent) { - super((AbstractHashedMap) parent); - } - - @Override - 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 (isEmpty()) { - return EmptyIterator.emptyIterator(); - } - return new ValuesIterator<>(this); - } - - /** - * Values implementation. - * - * @param the type of elements maintained by this collection - */ - protected static class Values extends AbstractCollection { - /** The parent map */ - private final AbstractHashedMap parent; - - protected Values(final AbstractHashedMap parent) { - 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. - * - * @param the type of elements maintained by this collection - */ - protected static class ValuesIterator extends HashIterator implements Iterator { - - @SuppressWarnings("unchecked") - protected ValuesIterator(final AbstractHashedMap parent) { - super((AbstractHashedMap) parent); - } - - @Override - public V next() { - return super.nextEntry().getValue(); - } - } - - /** - * HashEntry used to store the data. - *

- * If you subclass {@code AbstractHashedMap} but not {@code HashEntry} - * then you will not be able to access the protected fields. - * The {@code entryXxx()} methods on {@code AbstractHashedMap} exist - * to provide the necessary access. - * - * @param the type of the keys - * @param the type of the values - */ - 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) { - this.next = next; - this.hashCode = hashCode; - this.key = key; - this.value = value; - } - - @Override - @SuppressWarnings("unchecked") - public K getKey() { - if (key == NULL) { - return null; - } - return (K) key; - } - - @Override - @SuppressWarnings("unchecked") - public V getValue() { - return (V) value; - } - - @Override - @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)) { - 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 - * - * @param the type of the keys in the map - * @param the type of the values in the map - */ - protected abstract static 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) { - 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 {@code put()} is used. - *

- * Serialization is not one of the JDK's nicest topics. Normal serialization will - * initialize the superclass before the subclass. Sometimes however, this isn't - * what you want, as in this case the {@code 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 - * {@code 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 - */ - 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 {@code put()} is used. - *

- * Serialization is not one of the JDK's nicest topics. Normal serialization will - * initialize the superclass before the subclass. Sometimes however, this isn't - * what you want, as in this case the {@code 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 - * {@code readObject()} of the first serializable subclass. - *

- * Subclasses may override if the subclass has a specific field that must be present - * before {@code put()} or {@code 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 {@code clone()}, a subclass must implement the - * {@code 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)) { - 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)) { - return false; - } - } else { - if (!value.equals(map.get(key))) { - return false; - } - } - } - } catch (final ClassCastException | 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 (isEmpty()) { - 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(CollectionUtils.COMMA).append(' '); - } - } - - buf.append('}'); - return buf.toString(); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/map/AbstractInputCheckedMapDecorator.java b/src/main/java/repack/apache/commons/collections4/map/AbstractInputCheckedMapDecorator.java deleted file mode 100644 index 018b76b599..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/AbstractInputCheckedMapDecorator.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import java.lang.reflect.Array; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import repack.apache.commons.collections4.iterators.AbstractIteratorDecorator; -import repack.apache.commons.collections4.keyvalue.AbstractMapEntryDecorator; -import repack.apache.commons.collections4.set.AbstractSetDecorator; - -/** - * An abstract base class that simplifies the task of creating map decorators. - *

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

- *

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

- *

- * This class is package-scoped, and may be withdrawn or replaced in future - * versions of Commons Collections. - *

- * - * @since 3.1 - */ -abstract class AbstractInputCheckedMapDecorator - extends AbstractMapDecorator { - - /** - * Constructor only used in deserialization, do not use otherwise. - */ - protected AbstractInputCheckedMapDecorator() { - } - - /** - * Constructor that wraps (not copies). - * - * @param map the map to decorate, must not be null - * @throws NullPointerException if map is null - */ - protected AbstractInputCheckedMapDecorator(final Map map) { - super(map); - } - - /** - * Hook method called when a value is being set using {@code 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 - * @return the input value - * @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 {@code checkSetValue} has any effect. - *

- * An implementation should return false if the {@code checkSetValue} method - * has no effect as this optimises the implementation. - *

- * This implementation returns {@code 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 multithreaded 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); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/AbstractIterableMap.java b/src/main/java/repack/apache/commons/collections4/map/AbstractIterableMap.java deleted file mode 100644 index 900f435999..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/AbstractIterableMap.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import repack.apache.commons.collections4.IterableMap; -import repack.apache.commons.collections4.MapIterator; - -/** - * Provide a basic {@link IterableMap} implementation. - * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.0 - */ -public abstract class AbstractIterableMap implements IterableMap { - - /** - * {@inheritDoc} - */ - @Override - public MapIterator mapIterator() { - return new EntrySetToMapIteratorAdapter<>(entrySet()); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/map/AbstractLinkedMap.java b/src/main/java/repack/apache/commons/collections4/map/AbstractLinkedMap.java deleted file mode 100644 index e8d0b939fc..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/AbstractLinkedMap.java +++ /dev/null @@ -1,616 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; - -import repack.apache.commons.collections4.OrderedIterator; -import repack.apache.commons.collections4.OrderedMap; -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.ResettableIterator; -import repack.apache.commons.collections4.iterators.EmptyOrderedIterator; -import repack.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 - * {@code 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 behavior, 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 {@code OrderedMap} interface is implemented - * to provide access to bidirectional iteration and extra convenience methods. - *

- *

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

- *

- * All the available iterators can be reset back to the start by casting to - * {@code ResettableIterator} and calling {@code reset()}. - *

- *

- * The implementation is also designed to be subclassed, with lots of useful - * methods exposed. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -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() { - } - - /** - * 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); - } - - /** - * Initialize 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 {@code before} field from a {@code LinkEntry}. - * Used in subclasses that have no visibility of the field. - * - * @param entry the entry to query, must not be null - * @return the {@code 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 {@code after} field from a {@code LinkEntry}. - * Used in subclasses that have no visibility of the field. - * - * @param entry the entry to query, must not be null - * @return the {@code 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); - } - - @Override - public K next() { - return super.nextEntry().getKey(); - } - - @Override - public K previous() { - return super.previousEntry().getKey(); - } - - @Override - public K getKey() { - final LinkEntry current = currentEntry(); - if (current == null) { - throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); - } - return current.getKey(); - } - - @Override - public V getValue() { - final LinkEntry current = currentEntry(); - if (current == null) { - throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); - } - return current.getValue(); - } - - @Override - 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 (isEmpty()) { - 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); - } - - @Override - public Map.Entry next() { - return super.nextEntry(); - } - - @Override - 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 (isEmpty()) { - 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); - } - - @Override - public K next() { - return super.nextEntry().getKey(); - } - - @Override - 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 (isEmpty()) { - 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); - } - - @Override - public V next() { - return super.nextEntry().getValue(); - } - - @Override - public V previous() { - return super.previousEntry().getValue(); - } - } - - /** - * LinkEntry that stores the data. - *

- * If you subclass {@code AbstractLinkedMap} but not {@code LinkEntry} - * then you will not be able to access the protected fields. - * The {@code entryXxx()} methods on {@code 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 abstract static 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) { - 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[]"; - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/AbstractMapDecorator.java b/src/main/java/repack/apache/commons/collections4/map/AbstractMapDecorator.java deleted file mode 100644 index 4bbce6c570..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/AbstractMapDecorator.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import java.util.Collection; -import java.util.Map; -import java.util.Objects; -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 - */ -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() { - } - - /** - * Constructor that wraps (not copies). - * - * @param map the map to decorate, must not be null - * @throws NullPointerException if the map is null - */ - protected AbstractMapDecorator(final Map map) { - this.map = Objects.requireNonNull(map, "map"); - } - - /** - * Gets the map being decorated. - * - * @return the decorated map - */ - protected Map decorated() { - return map; - } - - @Override - public void clear() { - decorated().clear(); - } - - @Override - public boolean containsKey(final Object key) { - return decorated().containsKey(key); - } - - @Override - public boolean containsValue(final Object value) { - return decorated().containsValue(value); - } - - @Override - public Set> entrySet() { - return decorated().entrySet(); - } - - @Override - public V get(final Object key) { - return decorated().get(key); - } - - @Override - public boolean isEmpty() { - return decorated().isEmpty(); - } - - @Override - public Set keySet() { - return decorated().keySet(); - } - - @Override - public V put(final K key, final V value) { - return decorated().put(key, value); - } - - @Override - public void putAll(final Map mapToCopy) { - decorated().putAll(mapToCopy); - } - - @Override - public V remove(final Object key) { - return decorated().remove(key); - } - - @Override - public int size() { - return decorated().size(); - } - - @Override - 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/AbstractOrderedMapDecorator.java b/src/main/java/repack/apache/commons/collections4/map/AbstractOrderedMapDecorator.java deleted file mode 100644 index 576d404763..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/AbstractOrderedMapDecorator.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import repack.apache.commons.collections4.OrderedMap; -import repack.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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public abstract class AbstractOrderedMapDecorator extends AbstractMapDecorator - implements OrderedMap { - - /** - * Constructor only used in deserialization, do not use otherwise. - * @since 3.1 - */ - protected AbstractOrderedMapDecorator() { - } - - /** - * Constructor that wraps (not copies). - * - * @param map the map to decorate, must not be null - * @throws NullPointerException if the map 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(); - } - - @Override - public K firstKey() { - return decorated().firstKey(); - } - - @Override - public K lastKey() { - return decorated().lastKey(); - } - - @Override - public K nextKey(final K key) { - return decorated().nextKey(key); - } - - @Override - public K previousKey(final K key) { - return decorated().previousKey(key); - } - - @Override - public OrderedMapIterator mapIterator() { - return decorated().mapIterator(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/AbstractReferenceMap.java b/src/main/java/repack/apache/commons/collections4/map/AbstractReferenceMap.java deleted file mode 100644 index 929fd1a5e6..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/AbstractReferenceMap.java +++ /dev/null @@ -1,1122 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.MapIterator; -import repack.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 - * {@code 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 behavior, 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 {@code 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 - * - * {@code 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 - * {@code NullPointerException}. - *

- *

- * All the available iterators can be reset back to the start by casting to - * {@code ResettableIterator} and calling {@code reset()}. - *

- *

- * This implementation is not synchronized. - * You can use {@link java.util.Collections#synchronizedMap} to - * provide synchronized access to a {@code ReferenceMap}. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * - * @see java.lang.ref.Reference - * @since 3.1 (extracted from ReferenceMap in 3.0) - */ -public abstract class AbstractReferenceMap extends AbstractHashedMap { - - /** - * Reference type enum. - */ - public 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(); - } - } - - 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() { - } - - /** - * 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; - } - - /** - * Initialize 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) { - Objects.requireNonNull(key, "key"); - Objects.requireNonNull(value, "value"); - 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(); - // Drain the queue - while (queue.poll() != null) { // NOPMD - } - } - - /** - * 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 {@code next()} is called again. - * The {@code setValue()} method on the {@code 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) { - final ReferenceEntry refEntry = (ReferenceEntry) entry; - if (refEntry.purge(ref)) { - if (previous == null) { - data[index] = entry.next; - } else { - previous.next = entry.next; - } - this.size--; - refEntry.onPurge(); - 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 {@code 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 a key set iterator. - * - * @return the keySet iterator - */ - @Override - protected Iterator createKeySetIterator() { - return new ReferenceKeySetIterator<>(this); - } - - /** - * Creates a 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. - *

- * - * @param the type of the keys - * @param the type of the values - * @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 {@code isEqualKey} and - * {@code 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)) { - 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 {@code 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(); - } - - /** - * This is the callback for custom "after purge" logic - */ - protected void onPurge() { - // empty - } - - /** - * Purges the specified reference - * @param ref the reference to purge - * @return true or false - */ - protected 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) { - nullValue(); - } - } - return r; - } - - /** - * Gets the next entry in the bucket. - * - * @return the next entry in the bucket - */ - protected ReferenceEntry next() { - return (ReferenceEntry) next; - } - - /** - * This method can be overridden to provide custom logic to purge value - */ - protected void nullValue() { - value = null; - } - } - - /** - * 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 next; - ReferenceEntry current; - - // 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; - - ReferenceBaseIterator(final AbstractReferenceMap parent) { - this.parent = parent; - index = !parent.isEmpty() ? 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 = next; - int i = index; - while (e == null && i > 0) { - i--; - e = (ReferenceEntry) parent.data[i]; - } - next = e; - index = i; - if (e == null) { - return false; - } - nextKey = e.getKey(); - nextValue = e.getValue(); - if (nextNull()) { - next = next.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(); - } - current = next; - next = next.next(); - currentKey = nextKey; - currentValue = nextValue; - nextKey = null; - nextValue = null; - return current; - } - - protected ReferenceEntry currentEntry() { - checkMod(); - return current; - } - - public void remove() { - checkMod(); - if (current == null) { - throw new IllegalStateException(); - } - parent.remove(currentKey); - current = null; - currentKey = null; - currentValue = null; - expectedModCount = parent.modCount; - } - } - - /** - * The EntrySet iterator. - */ - static class ReferenceEntrySetIterator - extends ReferenceBaseIterator implements Iterator> { - - ReferenceEntrySetIterator(final AbstractReferenceMap parent) { - super(parent); - } - - @Override - 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); - } - - @Override - 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); - } - - @Override - public V next() { - return nextEntry().getValue(); - } - } - - /** - * The MapIterator implementation. - */ - static class ReferenceMapIterator extends ReferenceBaseIterator implements MapIterator { - - protected ReferenceMapIterator(final AbstractReferenceMap parent) { - super(parent); - } - - @Override - public K next() { - return nextEntry().getKey(); - } - - @Override - public K getKey() { - final HashEntry current = currentEntry(); - if (current == null) { - throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); - } - return current.getKey(); - } - - @Override - public V getValue() { - final HashEntry current = currentEntry(); - if (current == null) { - throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); - } - return current.getValue(); - } - - @Override - 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 - // 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; - - SoftRef(final int hash, final T r, final ReferenceQueue q) { - super(r, q); - this.hash = hash; - } - - @Override - public int hashCode() { - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final SoftRef other = (SoftRef) obj; - return hash == other.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; - - WeakRef(final int hash, final T r, final ReferenceQueue q) { - super(r, q); - this.hash = hash; - } - - @Override - public int hashCode() { - return hash; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final WeakRef other = (WeakRef) obj; - return hash == other.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 - * initialize the superclass before the subclass. Sometimes however, this isn't - * what you want, as in this case the {@code 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 - * {@code 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 - * initialize the superclass before the subclass. Sometimes however, this isn't - * what you want, as in this case the {@code 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 - * {@code readObject()} of the first serializable subclass. - *

- * Subclasses may override if the subclass has a specific field that must be present - * before {@code put()} or {@code 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]; - - // COLLECTIONS-599: Calculate threshold before populating, otherwise it will be 0 - // when it hits AbstractHashedMap.checkCapacity() and so will unnecessarily - // double up the size of the "data" array during population. - // - // NB: AbstractHashedMap.doReadObject() DOES calculate the threshold before populating. - // - threshold = calculateThreshold(data.length, loadFactor); - - while (true) { - final K key = (K) in.readObject(); - if (key == null) { - break; - } - final V value = (V) in.readObject(); - put(key, value); - } - // 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(final ReferenceStrength type) { - return this.keyType == type; - } - - /** - * Provided protected read-only access to the value type. - * @param type the type to check against. - * @return true if valueType has the specified type - */ - protected boolean isValueType(final ReferenceStrength type) { - return this.valueType == type; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/map/AbstractSortedMapDecorator.java b/src/main/java/repack/apache/commons/collections4/map/AbstractSortedMapDecorator.java deleted file mode 100644 index 1ee3eddb07..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/AbstractSortedMapDecorator.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.IterableSortedMap; -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.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 - */ -public abstract class AbstractSortedMapDecorator extends AbstractMapDecorator implements - IterableSortedMap { - - /** - * Constructor only used in deserialization, do not use otherwise. - * @since 3.1 - */ - protected AbstractSortedMapDecorator() { - } - - /** - * Constructor that wraps (not copies). - * - * @param map the map to decorate, must not be null - * @throws NullPointerException if the map 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(); - } - - @Override - public Comparator comparator() { - return decorated().comparator(); - } - - @Override - public K firstKey() { - return decorated().firstKey(); - } - - @Override - public K lastKey() { - return decorated().lastKey(); - } - - @Override - public SortedMap subMap(final K fromKey, final K toKey) { - return decorated().subMap(fromKey, toKey); - } - - @Override - public SortedMap headMap(final K toKey) { - return decorated().headMap(toKey); - } - - @Override - public SortedMap tailMap(final K fromKey) { - return decorated().tailMap(fromKey); - } - - @Override - public K previousKey(final K key) { - final SortedMap headMap = headMap(key); - return headMap.isEmpty() ? null : headMap.lastKey(); - } - - @Override - 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} - */ - @Override - public boolean hasPrevious() { - return ((ListIterator>) iterator).hasPrevious(); - } - - /** - * {@inheritDoc} - */ - @Override - public K previous() { - entry = ((ListIterator>) iterator).previous(); - return getKey(); - } - } -} diff --git a/src/main/java/repack/apache/commons/collections4/map/CaseInsensitiveMap.java b/src/main/java/repack/apache/commons/collections4/map/CaseInsensitiveMap.java deleted file mode 100644 index f9a744b55e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/CaseInsensitiveMap.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 {@code 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 {@code 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");
- * 
- *

- * The example above creates a {@code CaseInsensitiveMap} with three entries. - *

- *

- * {@code map.get(null)} returns {@code "Three"} and {@code map.get("ONE")} - * returns {@code "Four".} The {@code Set} returned by {@code keySet()} - * equals {@code {"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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class CaseInsensitiveMap extends AbstractHashedMap implements Serializable, Cloneable { - - /** Serialisation version */ - private static final long serialVersionUID = -7074655917369299456L; - - /** - * Constructs a new empty map with default size and load factor. - */ - public CaseInsensitiveMap() { - super(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_THRESHOLD); - } - - /** - * Constructs a new, empty map with the specified initial capacity. - * - * @param initialCapacity the initial capacity - * @throws IllegalArgumentException if the initial capacity is 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. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - doWriteObject(out); - } - - /** - * Read the map in using a custom routine. - * - * @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 - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - doReadObject(in); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/CompositeMap.java b/src/main/java/repack/apache/commons/collections4/map/CompositeMap.java deleted file mode 100644 index f9ab38a586..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/CompositeMap.java +++ /dev/null @@ -1,567 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.collection.CompositeCollection; -import repack.apache.commons.collections4.set.CompositeSet; - -/** - * Decorates a map of other maps to provide a single unified view. - *

- * Changes made to this map will actually be made on the decorated map. - * Add and remove operations require the use of a pluggable strategy. If no - * strategy is provided then add and remove are unsupported. - *

- *

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

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class CompositeMap extends AbstractIterableMap implements Serializable { - - private static final Map[] EMPTY_MAP_ARRAY = {}; - - /** 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 = EMPTY_MAP_ARRAY; - 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 { - if (map != null) { - for (int i = composite.length - 1; i >= 0; --i) { - final Collection intersect = CollectionUtils.intersection(this.composite[i].keySet(), map.keySet()); - if (!intersect.isEmpty()) { - 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 {@code 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 {@code clear()} on all composited Maps. - * - * @throws UnsupportedOperationException if any of the composited Maps do not support clear() - */ - @Override - public void clear() { - for (int i = this.composite.length - 1; i >= 0; --i) { - this.composite[i].clear(); - } - } - - /** - * Returns {@code true} if this map contains a mapping for the specified - * key. More formally, returns {@code true} if and only if - * this map contains at a mapping for a key {@code k} such that - * {@code (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 {@code 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 {@code null} and this map - * does not permit {@code null} keys (optional). - */ - @Override - 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 {@code true} if this map maps one or more keys to the - * specified value. More formally, returns {@code true} if and only if - * this map contains at least one mapping to a value {@code v} such that - * {@code (value==null ? v==null : value.equals(v))}. This operation - * will probably require time linear in the map size for most - * implementations of the {@code Map} interface. - * - * @param value value whose presence in this map is to be tested. - * @return {@code 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 {@code null} and this map - * does not permit {@code null} values (optional). - */ - @Override - 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 {@code 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 - * {@code Iterator.remove}, {@code Set.remove}, {@code removeAll}, - * {@code retainAll} and {@code clear} operations. It does not support - * the {@code add} or {@code addAll} operations. - *

- * This implementation returns a {@code 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. - */ - @Override - 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 - * {@code null} if the map contains no mapping for this key. A return - * value of {@code 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 {@code null}. The {@code containsKey} - * operation may be used to distinguish these two cases. - * - *

More formally, if this map contains a mapping from a key - * {@code k} to a value {@code v} such that (key==null ? k==null : - * key.equals(k)), then this method returns {@code v}; otherwise - * it returns {@code 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 - * {@code 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 {@code null} and this map does - * not permit {@code null} keys (optional). - * - * @see #containsKey(Object) - */ - @Override - 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 {@code true} if this map contains no key-value mappings. - * - * @return {@code true} if this map contains no key-value mappings. - */ - @Override - 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 {@code Iterator.remove}, {@code Set.remove}, - * {@code removeAll} {@code retainAll}, and {@code clear} operations. - * It does not support the add or {@code addAll} operations. - *

- * This implementation returns a {@code CompositeSet} which - * composites the key sets from all of the composited maps. - * - * @return a set view of the keys contained in this map. - */ - @Override - 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 - * {@code m} is said to contain a mapping for a key {@code k} if and only - * if {@link #containsKey(Object) m.containsKey(k)} would return - * {@code 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 {@code null} - * if there was no mapping for key. A {@code null} return can - * also indicate that the map previously associated {@code null} - * with the specified key, if the implementation supports - * {@code 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 {@code null} - * keys or values, and the specified key or value is - * {@code null}. - */ - @Override - 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 {@code k} to value {@code 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 {@code 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 {@code null}, or if - * this map does not permit {@code null} keys or values, and the - * specified map contains {@code null} keys or values. - */ - @Override - 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 {@code k} to value {@code v} such that - * {@code (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 - * {@code null} if the map contained no mapping for this key. (A - * {@code null} return can also indicate that the map previously - * associated {@code null} with the specified key if the implementation - * supports {@code 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 {@code 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 {@code null} and the composited map - * does not permit {@code null} keys (optional). - * @throws UnsupportedOperationException if the {@code remove} method is - * not supported by the composited map containing the key - */ - @Override - 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 {@code Integer.MAX_VALUE} elements, returns - * {@code Integer.MAX_VALUE}. - * - * @return the number of key-value mappings in this map. - */ - @Override - 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 - * {@code Iterator.remove}, {@code Collection.remove}, - * {@code removeAll}, {@code retainAll} and {@code clear} operations. - * It does not support the add or {@code addAll} operations. - * - * @return a collection view of the values contained in this map. - */ - @Override - 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. - * - * @param the type of the keys in the map - * @param the type of the values in the map - */ - public 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 {@code null} - * if there was no mapping for key. A {@code null} return can - * also indicate that the map previously associated {@code null} - * with the specified key, if the implementation supports - * {@code 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 {@code null} - * keys or values, and the specified key or value is - * {@code 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 {@code null} - * keys or values, and the specified key or value is - * {@code null}. - */ - void putAll(CompositeMap map, Map[] composited, - Map mapToAdd); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/map/DefaultedMap.java b/src/main/java/repack/apache/commons/collections4/map/DefaultedMap.java deleted file mode 100644 index e190d9e1bc..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/DefaultedMap.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.Objects; - -import repack.apache.commons.collections4.Factory; -import repack.apache.commons.collections4.Transformer; -import repack.apache.commons.collections4.functors.ConstantTransformer; -import repack.apache.commons.collections4.functors.FactoryTransformer; - -/** - * Decorates another {@code 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 behavior 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * - * @since 3.2 - * @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 NullPointerException 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 NullPointerException if map or factory is null - * @since 4.0 - */ - public static DefaultedMap defaultedMap(final Map map, final Factory factory) { - return new DefaultedMap<>(map, FactoryTransformer.factoryTransformer( - Objects.requireNonNull(factory, "Factory must not be null"))); - } - - /** - * 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 NullPointerException if map or transformer is null - * @since 4.0 - */ - public static Map defaultedMap(final Map map, - final Transformer transformer) { - return new DefaultedMap<>(map, Objects.requireNonNull(transformer, "Transformer must not be null")); - } - - /** - * Constructs a new empty {@code DefaultedMap} that decorates - * a {@code 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 {@code DefaultedMap} that decorates a {@code 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 NullPointerException if map or transformer is null - */ - protected DefaultedMap(final Map map, final Transformer defaultValueTransformer) { - super(map); - this.value = Objects.requireNonNull(defaultValueTransformer, "defaultValueTransformer"); - } - - /** - * Write the map out using a custom routine. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - 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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - */ - @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) { - final V v; - return (v = map.get(key)) != null || map.containsKey(key) - ? v - : value.transform((K) 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. -} diff --git a/src/main/java/repack/apache/commons/collections4/map/EntrySetToMapIteratorAdapter.java b/src/main/java/repack/apache/commons/collections4/map/EntrySetToMapIteratorAdapter.java deleted file mode 100644 index 74024d3417..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/EntrySetToMapIteratorAdapter.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.ResettableIterator; - -/** - * Adapts a Map entrySet to the MapIterator interface. - * - * @param the type of the keys in the map - * @param the type of the values in the map - * - * @since 4.0 - */ -public class EntrySetToMapIteratorAdapter implements MapIterator, ResettableIterator { - - /** The adapted Map entry Set. */ - final 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} - */ - @Override - public K getKey() { - return current().getKey(); - } - - /** - * {@inheritDoc} - */ - @Override - public V getValue() { - return current().getValue(); - } - - /** - * {@inheritDoc} - */ - @Override - public V setValue(final V value) { - return current().setValue(value); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - /** - * {@inheritDoc} - */ - @Override - public K next() { - entry = iterator.next(); - return getKey(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void reset() { - iterator = entrySet.iterator(); - } - - /** - * {@inheritDoc} - */ - @Override - public void remove() { - iterator.remove(); - entry = null; - } - - /** - * Get the currently active entry. - * @return Map.Entry<K, V> - */ - protected synchronized Map.Entry current() { - if (entry == null) { - throw new IllegalStateException(); - } - return entry; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/map/FixedSizeMap.java b/src/main/java/repack/apache/commons/collections4/map/FixedSizeMap.java deleted file mode 100644 index ffcd62dc41..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/FixedSizeMap.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.BoundedMap; -import repack.apache.commons.collections4.collection.UnmodifiableCollection; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -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 NullPointerException 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 NullPointerException 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 if an error occurs while writing to the stream - * @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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @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)) { - 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); - } - - @Override - public boolean isFull() { - return true; - } - - @Override - public int maxSize() { - return size(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/FixedSizeSortedMap.java b/src/main/java/repack/apache/commons/collections4/map/FixedSizeSortedMap.java deleted file mode 100644 index 58eb3383c2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/FixedSizeSortedMap.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.BoundedMap; -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.collection.UnmodifiableCollection; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -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 NullPointerException 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 NullPointerException 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. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - 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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - */ - @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)) { - 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)); - } - - @Override - public boolean isFull() { - return true; - } - - @Override - public int maxSize() { - return size(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/Flat3Map.java b/src/main/java/repack/apache/commons/collections4/map/Flat3Map.java deleted file mode 100644 index a36f60ef46..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/Flat3Map.java +++ /dev/null @@ -1,1280 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.IterableMap; -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.ResettableIterator; -import repack.apache.commons.collections4.iterators.EmptyIterator; -import repack.apache.commons.collections4.iterators.EmptyMapIterator; - -/** - * A {@code 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 {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class Flat3Map implements IterableMap, Serializable, Cloneable { - - /** Serialization version */ - private static final long serialVersionUID = -6701087419741928296L; - - /** The size of the map, used while in flat mode */ - private transient int size; - /** Hash, used while in flat mode */ - private transient int hash1; - /** Hash, used while in flat mode */ - private transient int hash2; - /** Hash, used while in flat mode */ - private transient int hash3; - /** Key, used while in flat mode */ - private transient K key1; - /** Key, used while in flat mode */ - private transient K key2; - /** Key, used while in flat mode */ - private transient K key3; - /** Value, used while in flat mode */ - private transient V value1; - /** Value, used while in flat mode */ - private transient V value2; - /** Value, used while in flat mode */ - private transient V value3; - /** Map, used while in delegate mode */ - private transient AbstractHashedMap delegateMap; - - /** - * Constructor. - */ - public Flat3Map() { - } - - /** - * Constructor copying elements from another map. - * - * @param map the map to copy - * @throws NullPointerException if the map is null - */ - public Flat3Map(final Map map) { - putAll(map); - } - - /** - * 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) { - 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 - */ - @Override - 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 - */ - @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(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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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. - */ - @Override - 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 - */ - @Override - 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; - private boolean canRemove; - - FlatMapIterator(final Flat3Map parent) { - this.parent = parent; - } - - @Override - public boolean hasNext() { - return nextIndex < parent.size; - } - - @Override - public K next() { - if (!hasNext()) { - throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); - } - canRemove = true; - nextIndex++; - return getKey(); - } - - @Override - public void remove() { - if (!canRemove) { - throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); - } - parent.remove(getKey()); - nextIndex--; - canRemove = false; - } - - @Override - public K getKey() { - if (!canRemove) { - 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); - } - - @Override - public V getValue() { - if (!canRemove) { - 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); - } - - @Override - public V setValue(final V value) { - if (!canRemove) { - 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; - } - - @Override - 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 - */ - @Override - 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) { - 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)) { - 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.isEmpty()) { - 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; - - 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 the new value of the removed flag - */ - void setRemoved(final boolean flag) { - this.removed = flag; - } - - @Override - 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); - } - - @Override - 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); - } - - @Override - 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)) { - 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 ""; - } - - } - - abstract static class EntryIterator { - private final Flat3Map parent; - private int nextIndex; - private FlatMapEntry currentEntry; - - /** - * Create a new Flat3Map.EntryIterator. - */ - 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); - } - parent.remove(currentEntry.getKey()); - currentEntry.setRemoved(true); - nextIndex--; - currentEntry = null; - } - - } - - /** - * EntrySetIterator and MapEntry - */ - static class EntrySetIterator extends EntryIterator implements Iterator> { - EntrySetIterator(final Flat3Map parent) { - super(parent); - } - - @Override - 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 - */ - @Override - 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) { - 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.isEmpty()) { - return EmptyIterator.emptyIterator(); - } - return new KeySetIterator<>(parent); - } - } - - /** - * KeySetIterator - */ - static class KeySetIterator extends EntryIterator implements Iterator { - - @SuppressWarnings("unchecked") - KeySetIterator(final Flat3Map parent) { - super((Flat3Map) parent); - } - - @Override - 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 - */ - @Override - 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) { - 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.isEmpty()) { - return EmptyIterator.emptyIterator(); - } - return new ValuesIterator<>(parent); - } - } - - /** - * ValuesIterator - */ - static class ValuesIterator extends EntryIterator implements Iterator { - - @SuppressWarnings("unchecked") - ValuesIterator(final Flat3Map parent) { - super((Flat3Map) parent); - } - - @Override - public V next() { - return nextEntry().getValue(); - } - } - - /** - * Write the map out using a custom routine. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - 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. - * - * @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") - 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)) { - 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)) { - return false; - } - otherValue = other.get(key3); - if (!Objects.equals(value3, otherValue)) { - return false; - } - case 2: - if (!other.containsKey(key2)) { - return false; - } - otherValue = other.get(key2); - if (!Objects.equals(value2, otherValue)) { - return false; - } - case 1: - if (!other.containsKey(key1)) { - return false; - } - otherValue = other.get(key1); - if (!Objects.equals(value1, 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(CollectionUtils.COMMA); - case 2: - buf.append(key2 == this ? "(this Map)" : key2); - buf.append('='); - buf.append(value2 == this ? "(this Map)" : value2); - buf.append(CollectionUtils.COMMA); - 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/HashedMap.java b/src/main/java/repack/apache/commons/collections4/map/HashedMap.java deleted file mode 100644 index 89df2e7e9d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/HashedMap.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 {@code Map} implementation that is a general purpose alternative - * to {@code HashMap}. - *

- * This implementation improves on the JDK1.4 HashMap by adding the - * {@link repack.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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class HashedMap - extends AbstractHashedMap implements Serializable, Cloneable { - - /** Serialisation version */ - private static final long serialVersionUID = -1788199231038721040L; - - /** - * Constructs a new empty map with default size and load factor. - */ - public HashedMap() { - super(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_THRESHOLD); - } - - /** - * Constructs a new, empty map with the specified initial capacity. - * - * @param initialCapacity the initial capacity - * @throws IllegalArgumentException if the initial capacity is 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. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - doWriteObject(out); - } - - /** - * Read the map in using a custom routine. - * - * @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 - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - doReadObject(in); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/LRUMap.java b/src/main/java/repack/apache/commons/collections4/map/LRUMap.java deleted file mode 100644 index 738f04f42e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/LRUMap.java +++ /dev/null @@ -1,528 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.BoundedMap; - -/** - * A {@code 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 repack.apache.commons.collections4.MapIterator MapIterator} or {@link #entrySet()} iterator. - *

- *

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

- *

- * All the available iterators can be reset back to the start by casting to - * {@code ResettableIterator} and calling {@code 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 - * {@code NullPointerException}'s when accessed by concurrent threads. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 (previously in main package v1.0) - */ -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 behavior */ - private final 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 initialSize the initial size of the map - * @throws IllegalArgumentException if the maximum size is less than one - * @throws IllegalArgumentException if the initial size is negative or larger than the maximum size - * @since 4.1 - */ - public LRUMap(final int maxSize, final int initialSize) { - this(maxSize, initialSize, 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 removable 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 max 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 max / initial capacity and - * load factor. - * - * @param maxSize the maximum size of the map - * @param initialSize the initial size of the map - * @param loadFactor the load factor - * @throws IllegalArgumentException if the maximum size is less than one - * @throws IllegalArgumentException if the initial size is negative or larger than the maximum size - * @throws IllegalArgumentException if the load factor is less than zero - * @since 4.1 - */ - public LRUMap(final int maxSize, final int initialSize, final float loadFactor) { - this(maxSize, initialSize, loadFactor, false); - } - - /** - * Constructs a new, empty map with the specified max capacity and load factor. - * - * @param maxSize the maximum size of the map - * @param loadFactor the load factor - * @param scanUntilRemovable scan until a removable 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) { - this(maxSize, maxSize, loadFactor, scanUntilRemovable); - } - - /** - * Constructs a new, empty map with the specified max / initial capacity and load factor. - * - * @param maxSize the maximum size of the map - * @param initialSize the initial size of the map - * @param loadFactor the load factor - * @param scanUntilRemovable scan until a removable entry is found, default false - * @throws IllegalArgumentException if the maximum size is less than one - * @throws IllegalArgumentException if the initial size is negative or larger than the maximum size - * @throws IllegalArgumentException if the load factor is less than zero - * @since 4.1 - */ - public LRUMap(final int maxSize, - final int initialSize, - final float loadFactor, - final boolean scanUntilRemovable) { - - super(initialSize, loadFactor); - if (maxSize < 1) { - throw new IllegalArgumentException("LRUMap max size must be greater than 0"); - } - if (initialSize > maxSize) { - throw new IllegalArgumentException("LRUMap initial size must not be greater than max size"); - } - 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 removable 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 (last). - * - * @param key the key - * @return the mapped value, null if no match - */ - @Override - public V get(final Object key) { - return get(key, true); - } - - /** - * Gets the value mapped to the key specified. - *

- * If {@code updateToMRU} is {@code true}, the position of the key in the map - * is changed to the most recently used position (last), otherwise the iteration - * order is not changed by this operation. - * - * @param key the key - * @param updateToMRU whether the key shall be updated to the - * most recently used position - * @return the mapped value, null if no match - * @since 4.1 - */ - public V get(final Object key, final boolean updateToMRU) { - final LinkEntry entry = getEntry(key); - if (entry == null) { - return null; - } - if (updateToMRU) { - 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." + - " This should not occur if your keys are immutable, and you have used synchronization properly."); - } - 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" + - " This should not occur if your keys are immutable, and you have used synchronization properly."); - } - } - - /** - * Updates an existing key-value mapping. - *

- * This implementation moves the updated entry to the end 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 {@code size} and {@code 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 + - " This should not occur if your keys are immutable and you used synchronization properly."); - } - } 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 + - " This should not occur if your keys are immutable and you used synchronization properly."); - } - 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 + - " This should not occur if your keys are immutable, and you have used synchronization properly."); - } - - // 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 + - " This should not occur if your keys are immutable, and you have used synchronization properly."); - } - } - - /** - * 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 {@code true} if the map is full - */ - @Override - 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 - */ - @Override - 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. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - doWriteObject(out); - } - - /** - * Read the map in using a custom routine. - * - * @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 - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - doReadObject(in); - } - - /** - * Writes the data necessary for {@code 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 {@code 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/LazyMap.java b/src/main/java/repack/apache/commons/collections4/map/LazyMap.java deleted file mode 100644 index 2a0a852f29..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/LazyMap.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.Objects; - -import repack.apache.commons.collections4.Factory; -import repack.apache.commons.collections4.Transformer; -import repack.apache.commons.collections4.functors.FactoryTransformer; - -/** - * Decorates another {@code 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, {@code date} will refer to - * a new {@code Date} instance. Furthermore, that {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -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 NullPointerException if map or factory is null - * @since 4.0 - */ - public static LazyMap lazyMap(final Map map, final Factory 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 NullPointerException 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 NullPointerException if map or factory is null - */ - protected LazyMap(final Map map, final Factory factory) { - super(map); - this.factory = FactoryTransformer.factoryTransformer(Objects.requireNonNull(factory, "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 NullPointerException if map or factory is null - */ - protected LazyMap(final Map map, final Transformer factory) { - super(map); - this.factory = Objects.requireNonNull(factory, "factory"); - } - - /** - * Write the map out using a custom routine. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - * @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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @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)) { - @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. -} diff --git a/src/main/java/repack/apache/commons/collections4/map/LazySortedMap.java b/src/main/java/repack/apache/commons/collections4/map/LazySortedMap.java deleted file mode 100644 index 724b8b6cd9..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/LazySortedMap.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import java.util.Comparator; -import java.util.SortedMap; - -import repack.apache.commons.collections4.Factory; -import repack.apache.commons.collections4.Transformer; - -/** - * Decorates another {@code 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, {@code date} will refer to - * a new {@code Date} instance. Furthermore, that {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class LazySortedMap extends LazyMap implements SortedMap { - - /** Serialization version */ - private static final long serialVersionUID = 2715322183617658933L; - - /** - * Factory method to create a lazily instantiated sorted map. - * - * @param 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 NullPointerException 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 NullPointerException 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 NullPointerException 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 NullPointerException 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; - } - - @Override - public K firstKey() { - return getSortedMap().firstKey(); - } - - @Override - public K lastKey() { - return getSortedMap().lastKey(); - } - - @Override - public Comparator comparator() { - return getSortedMap().comparator(); - } - - @Override - public SortedMap subMap(final K fromKey, final K toKey) { - final SortedMap map = getSortedMap().subMap(fromKey, toKey); - return new LazySortedMap<>(map, factory); - } - - @Override - public SortedMap headMap(final K toKey) { - final SortedMap map = getSortedMap().headMap(toKey); - return new LazySortedMap<>(map, factory); - } - - @Override - public SortedMap tailMap(final K fromKey) { - final SortedMap map = getSortedMap().tailMap(fromKey); - return new LazySortedMap<>(map, factory); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/LinkedMap.java b/src/main/java/repack/apache/commons/collections4/map/LinkedMap.java deleted file mode 100644 index f1b0a39a43..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/LinkedMap.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.function.Predicate; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.iterators.UnmodifiableIterator; -import repack.apache.commons.collections4.iterators.UnmodifiableListIterator; -import repack.apache.commons.collections4.list.UnmodifiableList; - -/** - * A {@code 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 repack.apache.commons.collections4.MapIterator MapIterator} - * functionality, additional convenience methods and allowing - * bidirectional iteration. It also implements {@code OrderedMap}. - * In addition, non-interface methods are provided to access the map by index. - *

- *

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

- *

- * All the available iterators can be reset back to the start by casting to - * {@code ResettableIterator} and calling {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class LinkedMap extends AbstractLinkedMap implements Serializable, Cloneable { - - /** Serialisation version */ - private static final long serialVersionUID = 9077234323521161066L; - - /** - * Constructs a new empty map with default size and load factor. - */ - public LinkedMap() { - super(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_THRESHOLD); - } - - /** - * Constructs a new, empty map with the specified initial capacity. - * - * @param initialCapacity the initial capacity - * @throws IllegalArgumentException if the initial capacity is 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. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - doWriteObject(out); - } - - /** - * Read the map in using a custom routine. - * - * @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 - */ - 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 CollectionUtils.INDEX_NOT_FOUND; - } - - /** - * Removes the element at the specified index. - * - * @param index the index of the object to remove - * @return the previous value corresponding the {@code key}, - * or {@code 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - 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.unmodifiableListIterator(super.listIterator()); - } - - @Override - public ListIterator listIterator(final int fromIndex) { - return UnmodifiableListIterator.unmodifiableListIterator(super.listIterator(fromIndex)); - } - - @Override - public List subList(final int fromIndexInclusive, final int toIndexExclusive) { - return UnmodifiableList.unmodifiableList(super.subList(fromIndexInclusive, toIndexExclusive)); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/ListOrderedMap.java b/src/main/java/repack/apache/commons/collections4/map/ListOrderedMap.java deleted file mode 100644 index 1bc5f736b8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/ListOrderedMap.java +++ /dev/null @@ -1,791 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.OrderedMap; -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.ResettableIterator; -import repack.apache.commons.collections4.iterators.AbstractUntypedIteratorDecorator; -import repack.apache.commons.collections4.keyvalue.AbstractMapEntry; -import repack.apache.commons.collections4.list.UnmodifiableList; - -/** - * Decorates a {@code Map} to ensure that the order of addition is retained - * using a {@code 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 {@code MapIterator}. - * The {@code 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 {@code ListOrderedMap} (or, more precisely, the underlying {@code List}) - * is relying on {@link Object#equals(Object) equals()}. This is fine, as long as the - * decorated {@code 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 {@code ==}, 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class ListOrderedMap - extends AbstractMapDecorator - implements OrderedMap, Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 2728177751851003750L; - - /** Internal list to hold the sequence of objects */ - private final List insertOrder = new ArrayList<>(); - - /** - * Factory method to create an ordered map. - *

- * An {@code 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 NullPointerException if map is null - * @since 4.0 - */ - public static ListOrderedMap listOrderedMap(final Map map) { - return new ListOrderedMap<>(map); - } - - /** - * Constructs a new empty {@code ListOrderedMap} that decorates - * a {@code 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 NullPointerException 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 if an error occurs while writing to the stream - * @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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @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 - */ - @Override - public K firstKey() { - if (isEmpty()) { - 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 - */ - @Override - public K lastKey() { - if (isEmpty()) { - 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 - */ - @Override - 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 - */ - @Override - 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); - } - // 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; - } - 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 {@code 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) { - 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()) { - @Override - 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) { - 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()) { - @Override - public K next() { - return getIterator().next().getKey(); - } - }; - } - } - - static class EntrySetView extends AbstractSet> { - private final ListOrderedMap parent; - private final List insertOrder; - private Set> entrySet; - - EntrySetView(final ListOrderedMap parent, final List insertOrder) { - 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)) { - 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; - - ListOrderedIterator(final ListOrderedMap parent, final List insertOrder) { - super(insertOrder.iterator()); - this.parent = parent; - } - - @Override - 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; - private boolean readable; - - ListOrderedMapIterator(final ListOrderedMap parent) { - this.parent = parent; - this.iterator = parent.insertOrder.listIterator(); - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public K next() { - last = iterator.next(); - readable = true; - return last; - } - - @Override - public boolean hasPrevious() { - return iterator.hasPrevious(); - } - - @Override - public K previous() { - last = iterator.previous(); - readable = true; - return last; - } - - @Override - public void remove() { - if (!readable) { - throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID); - } - iterator.remove(); - parent.map.remove(last); - readable = false; - } - - @Override - public K getKey() { - if (!readable) { - throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); - } - return last; - } - - @Override - public V getValue() { - if (!readable) { - throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); - } - return parent.get(last); - } - - @Override - public V setValue(final V value) { - if (!readable) { - throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); - } - return parent.map.put(last, value); - } - - @Override - public void reset() { - iterator = parent.insertOrder.listIterator(); - last = null; - readable = false; - } - - @Override - public String toString() { - if (readable) { - return "Iterator[" + getKey() + "=" + getValue() + "]"; - } - return "Iterator[]"; - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/MultiKeyMap.java b/src/main/java/repack/apache/commons/collections4/map/MultiKeyMap.java deleted file mode 100644 index 05169a6249..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/MultiKeyMap.java +++ /dev/null @@ -1,904 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.Objects; - -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.keyvalue.MultiKey; - -/** - * A {@code 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 {@code get}, {@code containsKey}, {@code put} and - * {@code 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 {@code Map}. - *

- *

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

- *

- * This map is implemented as a decorator of a {@code AbstractHashedMap} which - * enables extra behavior to be added easily. - *

- *
    - *
  • {@code MultiKeyMap.decorate(new LinkedMap())} creates an ordered map. - *
  • {@code MultiKeyMap.decorate(new LRUMap())} creates an least recently used map. - *
  • {@code MultiKeyMap.decorate(new ReferenceMap())} creates a garbage collector sensitive map. - *
- *

- * Note that {@code IdentityMap} and {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.1 - */ -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 NullPointerException if map is null - * @throws IllegalArgumentException if the map is not empty - * @since 4.0 - */ - public static MultiKeyMap multiKeyMap(final AbstractHashedMap, V> map) { - Objects.requireNonNull(map, "map"); - if (map.isEmpty()) { - return new MultiKeyMap<>(map); - } - throw new IllegalArgumentException("Map must be empty"); - } - - /** - * Constructs a new MultiKeyMap that decorates a {@code HashedMap}. - */ - public MultiKeyMap() { - this(new HashedMap<>()); - } - - /** - * 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) || key2 != 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 {@code 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 {@code 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 {@code 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 {@code 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) { - Objects.requireNonNull(key, "key"); - } - - /** - * 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 if an error occurs while writing to the stream - */ - 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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - */ - @SuppressWarnings("unchecked") - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - map = (Map, V>) in.readObject(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/MultiValueMap.java b/src/main/java/repack/apache/commons/collections4/map/MultiValueMap.java deleted file mode 100644 index 6623eac799..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/MultiValueMap.java +++ /dev/null @@ -1,573 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.Factory; -import repack.apache.commons.collections4.FunctorException; -import repack.apache.commons.collections4.MultiMap; -import repack.apache.commons.collections4.Transformer; -import repack.apache.commons.collections4.iterators.EmptyIterator; -import repack.apache.commons.collections4.iterators.IteratorChain; -import repack.apache.commons.collections4.iterators.LazyIteratorChain; -import repack.apache.commons.collections4.iterators.TransformIterator; - -/** - * A MultiValueMap decorates another map, allowing it to have - * more than one value for a key. - *

- * A {@code 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 {@code ArrayList} - * is used, however a {@code Class} to instantiate may be specified, - * or a factory that returns a {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.2 - * @deprecated since 4.1, use {@link repack.apache.commons.collections4.MultiValuedMap MultiValuedMap} instead - */ -@Deprecated -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 {@code map} and - * maps keys to collections of type {@code 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 {@code map} and - * creates the value collections using the supplied {@code 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 {@code HashMap} and - * storing the multiple values in an {@code ArrayList}. - */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public MultiValueMap() { - this(new HashMap(), new ReflectionFactory(ArrayList.class)); - } - - /** - * Creates a MultiValueMap which decorates the given {@code map} and - * creates the value collections using the supplied {@code 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 if an error occurs while writing to the stream - * @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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @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, {@code null} will be returned - * from a subsequent {@code 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 - */ - @Override - 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) { - 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 {@code 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.isEmpty()) { - // 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 {@code put(Object,Object)}. - * If you call this method with a multi map, each entry is - * added using {@code 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() { // NOPMD - 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 {@code 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.isEmpty()) { - 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.isEmpty()) { - // 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(final int count) { - if ( ! keyIterator.hasNext() ) { - return null; - } - final K key = keyIterator.next(); - final Transformer> transformer = input -> new Entry() { - @Override - public K getKey() { - return key; - } - @Override - public V getValue() { - return input; - } - @Override - public V setValue(final 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; - - ValuesIterator(final Object key) { - this.key = key; - this.values = getCollection(key); - this.iterator = values.iterator(); - } - - @Override - public void remove() { - iterator.remove(); - if (values.isEmpty()) { - MultiValueMap.this.remove(key); - } - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - 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; - - ReflectionFactory(final Class clazz) { - this.clazz = clazz; - } - - @Override - public T create() { - try { - return clazz.getDeclaredConstructor().newInstance(); - } catch (final Exception ex) { - throw new FunctorException("Cannot instantiate class: " + clazz, ex); - } - } - - private void readObject(final ObjectInputStream is) throws IOException, ClassNotFoundException { - is.defaultReadObject(); - // ensure that the de-serialized class is a Collection, COLLECTIONS-580 - if (clazz != null && !Collection.class.isAssignableFrom(clazz)) { - throw new UnsupportedOperationException(); - } - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/PassiveExpiringMap.java b/src/main/java/repack/apache/commons/collections4/map/PassiveExpiringMap.java deleted file mode 100644 index 2c7200ea91..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/PassiveExpiringMap.java +++ /dev/null @@ -1,535 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.Objects; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -/** - * Decorates a {@code 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 {@code null} is returned. - *

- *

- * When invoking methods that involve accessing the entire map contents (i.e - * {@link #containsValue(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 this map - * @param the type of the values in this map - * @since 4.0 - */ -public class PassiveExpiringMap - extends AbstractMapDecorator - implements Serializable { - - /** - * A {@link repack.apache.commons.collections4.map.PassiveExpiringMap.ExpirationPolicy ExpirationPolicy} - * that returns an 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 - */ - 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) { - 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 {@code timeToLive} - * parameter, must not be null. - * @throws NullPointerException 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. - */ - @Override - public long expirationTime(final K key, final V value) { - if (timeToLiveMillis >= 0L) { - // avoid numerical overflow - final long nowMillis = System.currentTimeMillis(); - if (nowMillis > Long.MAX_VALUE - timeToLiveMillis) { - // expiration would be greater than Long.MAX_VALUE - // never expire - return -1; - } - - // timeToLiveMillis in the future - return nowMillis + 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 - */ - @FunctionalInterface - public 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. - * - * @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 {@code timeToLive} - * parameter, must not be null. - * @throws NullPointerException if the time unit is null. - */ - private static long validateAndConvertToMillis(final long timeToLive, - final TimeUnit timeUnit) { - Objects.requireNonNull(timeUnit, "timeUnit"); - 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. - * @throws NullPointerException if expiringPolicy is null - */ - 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 NullPointerException if the map or expiringPolicy is null. - */ - public PassiveExpiringMap(final ExpirationPolicy expiringPolicy, - final Map map) { - super(map); - this.expiringPolicy = Objects.requireNonNull(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 NullPointerException 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 {@code timeToLive} - * parameter, must not be null. - * @throws NullPointerException 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 {@code timeToLive} - * parameter, must not be null. - * @param map the map to decorate, must not be null. - * @throws NullPointerException if the map or time unit 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 NullPointerException 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 {@code 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 {@code true} if {@code expirationTimeObject} is ≥ 0 - * and {@code expirationTimeObject} < {@code now}. - * {@code 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(); - } - - /** - * 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 and this map's {@link #expiringPolicy}. - *

- * {@inheritDoc} - */ - @Override - public V put(final K key, final V value) { - // remove the previous record - removeIfExpired(key, 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 - * {@code now}. The exceptions are entries with negative expiration - * times; those entries are never removed. - * - * @see #isExpired(long, Long) - */ - private void removeAllExpired(final long nowMillis) { - final Iterator> iter = expirationMap.entrySet().iterator(); - while (iter.hasNext()) { - final Map.Entry expirationEntry = iter.next(); - if (isExpired(nowMillis, 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 {@code now}. If the entry has a negative expiration time, - * the entry is never removed. - */ - private void removeIfExpired(final Object key, final long nowMillis) { - final Long expirationTimeObject = expirationMap.get(key); - if (isExpired(nowMillis, 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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - */ - @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 if an error occurs while writing to the stream - */ - 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(); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/map/PredicatedMap.java b/src/main/java/repack/apache/commons/collections4/map/PredicatedMap.java deleted file mode 100644 index aabe11f725..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/PredicatedMap.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.Predicate; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class PredicatedMap - extends AbstractInputCheckedMapDecorator - implements Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 7412622456128415156L; - - /** The key predicate to use */ - protected final Predicate keyPredicate; - - /** The value predicate to use */ - protected final Predicate valuePredicate; - - /** - * Factory method to create a predicated (validating) map. - *

- * If there are any elements already in the list being decorated, they - * are validated. - * - * @param 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 NullPointerException 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 NullPointerException if the map is null - */ - protected PredicatedMap(final Map map, final Predicate keyPredicate, - final Predicate valuePredicate) { - super(map); - this.keyPredicate = keyPredicate; - this.valuePredicate = valuePredicate; - map.forEach(this::validate); - } - - /** - * Write the map out using a custom routine. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - * @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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @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)) { - throw new IllegalArgumentException("Cannot add key - Predicate rejected it"); - } - if (valuePredicate != null && !valuePredicate.evaluate(value)) { - throw new IllegalArgumentException("Cannot add value - Predicate rejected it"); - } - } - - /** - * Override to validate an object set into the map via {@code 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)) { - 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/PredicatedSortedMap.java b/src/main/java/repack/apache/commons/collections4/map/PredicatedSortedMap.java deleted file mode 100644 index fcfd4783eb..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/PredicatedSortedMap.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import java.util.Comparator; -import java.util.SortedMap; - -import repack.apache.commons.collections4.Predicate; - -/** - * Decorates another {@code 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 =
- *     PredicatedSortedMap.predicatedSortedMap(new TreeMap(),
- *                                             NotNullPredicate.notNullPredicate(),
- *                                             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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class PredicatedSortedMap extends PredicatedMap implements SortedMap { - - /** Serialization version */ - private static final long serialVersionUID = 3359846175935304332L; - - /** - * Factory method to create a predicated (validating) sorted map. - *

- * If there are any elements already in the list being decorated, they - * are validated. - * - * @param 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 NullPointerException 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 NullPointerException 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; - } - - @Override - public K firstKey() { - return getSortedMap().firstKey(); - } - - @Override - public K lastKey() { - return getSortedMap().lastKey(); - } - - @Override - public Comparator comparator() { - return getSortedMap().comparator(); - } - - @Override - public SortedMap subMap(final K fromKey, final K toKey) { - final SortedMap map = getSortedMap().subMap(fromKey, toKey); - return new PredicatedSortedMap<>(map, keyPredicate, valuePredicate); - } - - @Override - public SortedMap headMap(final K toKey) { - final SortedMap map = getSortedMap().headMap(toKey); - return new PredicatedSortedMap<>(map, keyPredicate, valuePredicate); - } - - @Override - public SortedMap tailMap(final K fromKey) { - final SortedMap map = getSortedMap().tailMap(fromKey); - return new PredicatedSortedMap<>(map, keyPredicate, valuePredicate); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/ReferenceIdentityMap.java b/src/main/java/repack/apache/commons/collections4/map/ReferenceIdentityMap.java deleted file mode 100644 index 5044436aa7..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/ReferenceIdentityMap.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 {@code Map} implementation that allows mappings to be - * removed by the garbage collector and matches keys and values based - * on {@code ==} not {@code equals()}. - *

- * When you construct a {@code 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 repack.apache.commons.collections4.map.ReferenceMap ReferenceMap}. - * It differs in that keys and values in this class are compared using {@code ==}. - *

- *

- * 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 {@code NullPointerException}. - *

- *

- * This implementation is not synchronized. - * You can use {@link java.util.Collections#synchronizedMap} to - * provide synchronized access to a {@code 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 - * {@code ResettableIterator} and calling {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * - * @see java.lang.ref.Reference - * @since 3.0 (previously in main package v2.1) - */ -public class ReferenceIdentityMap extends AbstractReferenceMap implements Serializable { - - /** Serialization version */ - private static final long serialVersionUID = -1266190134568365852L; - - /** - * Constructs a new {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code ==}. - * - * @param key1 the first key to compare passed in from outside - * @param key2 the second key extracted from the entry via {@code 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 {@code ==}. - * - * @param value1 the first value to compare passed in from outside - * @param value2 the second value extracted from the entry via {@code 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. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - doWriteObject(out); - } - - /** - * Read the map in using a custom routine. - * - * @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 - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - doReadObject(in); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/ReferenceMap.java b/src/main/java/repack/apache/commons/collections4/map/ReferenceMap.java deleted file mode 100644 index 7f29a2953f..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/ReferenceMap.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -/** - * A {@code Map} implementation that allows mappings to be - * removed by the garbage collector. - *

- * When you construct a {@code 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 - * - * {@code 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 repack.apache.commons.collections4.map.ReferenceIdentityMap ReferenceIdentityMap}. - * It differs in that keys and values in this class are compared using {@code 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 {@code NullPointerException}. - *

- *

- * This implementation is not synchronized. - * You can use {@link java.util.Collections#synchronizedMap} to - * provide synchronized access to a {@code 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 - * {@code ResettableIterator} and calling {@code 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 {@code AbstractReferenceMap} - * (previously it extended AbstractMap). As a result, the implementation is now - * extensible and provides a {@code MapIterator}. - *

- * - * @param the type of the keys in the map - * @param the type of the values in the map - * - * @see java.lang.ref.Reference - * @since 3.0 (previously in main package v2.1) - */ -public class ReferenceMap extends AbstractReferenceMap implements Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 1555089888138299607L; - - /** - * Constructs a new {@code 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 {@code 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 {@code 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 {@code 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 {@code 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. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - doWriteObject(out); - } - - /** - * Read the map in using a custom routine. - * - * @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 - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - doReadObject(in); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/SingletonMap.java b/src/main/java/repack/apache/commons/collections4/map/SingletonMap.java deleted file mode 100644 index 22174c02a5..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/SingletonMap.java +++ /dev/null @@ -1,594 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.BoundedMap; -import repack.apache.commons.collections4.KeyValue; -import repack.apache.commons.collections4.OrderedMap; -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.ResettableIterator; -import repack.apache.commons.collections4.iterators.SingletonIterator; -import repack.apache.commons.collections4.keyvalue.TiedMapEntry; - -/** - * A {@code 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 {@code put} or {@code 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 succeed 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 {@code MapIterator}, see {@link #mapIterator()} - *
  • the {@code KeyValue} interface (just cast - no object creation) - *
- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.1 - */ -public class SingletonMap - implements OrderedMap, BoundedMap, KeyValue, Serializable, Cloneable { - - /** Serialization version */ - private static final long serialVersionUID = -8931271118676803261L; - - /** Singleton key */ - private final K key; - /** Singleton value */ - private V value; - - /** - * Constructor that creates a map of {@code null} to {@code null}. - */ - public SingletonMap() { - 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) { - this.key = key; - this.value = value; - } - - /** - * Constructor specifying the key and value as a {@code KeyValue}. - * - * @param keyValue the key value pair to use - */ - public SingletonMap(final KeyValue keyValue) { - this.key = keyValue.getKey(); - this.value = keyValue.getValue(); - } - - /** - * Constructor specifying the key and value as a {@code MapEntry}. - * - * @param mapEntry the mapEntry to use - */ - public SingletonMap(final Map.Entry mapEntry) { - 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) { - 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 - */ - @Override - public K getKey() { - return key; - } - - /** - * Gets the value. - * - * @return the value - */ - @Override - 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 - */ - @Override - public boolean isFull() { - return true; - } - - /** - * Gets the maximum size of the map, always 1. - * - * @return 1 always - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - public int size() { - return 1; - } - - /** - * Checks whether the map is currently empty, which it never is. - * - * @return false always - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - public V remove(final Object key) { - throw new UnsupportedOperationException(); - } - - /** - * Unsupported operation. - */ - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - - /** - * Gets the entrySet view of the map. - * Changes made via {@code setValue} affect this map. - * To simply iterate through the entries, use {@link #mapIterator()}. - * - * @return the entrySet view - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - public Collection values() { - return new SingletonValues<>(this); - } - - /** - * {@inheritDoc} - */ - @Override - public OrderedMapIterator mapIterator() { - return new SingletonMapIterator<>(this); - } - - /** - * Gets the first (and only) key in the map. - * - * @return the key - */ - @Override - public K firstKey() { - return getKey(); - } - - /** - * Gets the last (and only) key in the map. - * - * @return the key - */ - @Override - public K lastKey() { - return getKey(); - } - - /** - * Gets the next key after the key specified, always null. - * - * @param key the next key - * @return null always - */ - @Override - 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 - */ - @Override - 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; - - SingletonMapIterator(final SingletonMap parent) { - this.parent = parent; - } - - @Override - public boolean hasNext() { - return hasNext; - } - - @Override - public K next() { - if (!hasNext) { - throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY); - } - hasNext = false; - canGetSet = true; - return parent.getKey(); - } - - @Override - public boolean hasPrevious() { - return !hasNext; - } - - @Override - public K previous() { - if (hasNext) { - throw new NoSuchElementException(AbstractHashedMap.NO_PREVIOUS_ENTRY); - } - hasNext = true; - return parent.getKey(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public K getKey() { - if (!canGetSet) { - throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); - } - return parent.getKey(); - } - - @Override - public V getValue() { - if (!canGetSet) { - throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); - } - return parent.getValue(); - } - - @Override - public V setValue(final V value) { - if (!canGetSet) { - throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); - } - return parent.setValue(value); - } - - @Override - 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) { - 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)) { - 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/StaticBucketMap.java b/src/main/java/repack/apache/commons/collections4/map/StaticBucketMap.java deleted file mode 100644 index 90beec44a1..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/StaticBucketMap.java +++ /dev/null @@ -1,728 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.KeyValue; - -/** - * A StaticBucketMap is an efficient, thread-safe implementation of - * {@code java.util.Map} that performs well 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 {@code staticBucketMapInstance} essentially - * unchanged, or they could leave some random subset of {@code map} in - * {@code 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.

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 (previously in main package v2.1) - */ -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 - */ - @Override - 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 - */ - @Override - public boolean isEmpty() { - return size() == 0; - } - - /** - * Gets the value associated with the key. - * - * @param key the key to retrieve - * @return the associated value - */ - @Override - public V get(final Object key) { - final int hash = getHash(key); - - synchronized (locks[hash]) { - Node n = buckets[hash]; - - while (n != null) { - if (Objects.equals(n.key, 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 - */ - @Override - public boolean containsKey(final Object key) { - final int hash = getHash(key); - - synchronized (locks[hash]) { - Node n = buckets[hash]; - - while (n != null) { - if (Objects.equals(n.key, 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 - */ - @Override - 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 (Objects.equals(n.value, 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 - */ - @Override - 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 (Objects.equals(n.key, 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 - */ - @Override - 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 (Objects.equals(n.key, 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 - */ - @Override - public Set keySet() { - return new KeySet(); - } - - /** - * Gets the values. - * - * @return the values - */ - @Override - public Collection values() { - return new Values(); - } - - /** - * Gets the entry set. - * - * @return the entry set - */ - @Override - 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 - */ - @Override - public void putAll(final Map map) { - for (final Map.Entry entry : map.entrySet()) { - put(entry.getKey(), entry.getValue()); - } - } - - /** - * Clears the map of all entries. - */ - @Override - 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)) { - 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; - - @Override - public K getKey() { - return key; - } - - @Override - 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)) { - 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())); - } - - @Override - 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 static final 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.isEmpty()) { - 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.isEmpty()) { - 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> { - - @Override - public Map.Entry next() { - return nextEntry(); - } - - } - - private class ValueIterator extends BaseIterator implements Iterator { - - @Override - public V next() { - return nextEntry().getValue(); - } - - } - - private class KeyIterator extends BaseIterator implements Iterator { - - @Override - 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)) { - 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 (Objects.equals(k, 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 runnable the code to execute atomically - */ - public void atomic(final Runnable runnable) { - atomic(Objects.requireNonNull(runnable, "runnable"), 0); - } - - private void atomic(final Runnable r, final int bucket) { - if (bucket >= buckets.length) { - r.run(); - return; - } - synchronized (locks[bucket]) { - atomic(r, bucket + 1); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/TransformedMap.java b/src/main/java/repack/apache/commons/collections4/map/TransformedMap.java deleted file mode 100644 index feb78fc608..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/TransformedMap.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.Transformer; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * - * @see repack.apache.commons.collections4.splitmap.TransformedSplitMap - * @since 3.0 - */ -public class TransformedMap - extends AbstractInputCheckedMapDecorator - implements Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 7023152376788900464L; - - /** The transformer to use for the key */ - protected final Transformer keyTransformer; - /** The transformer to use for the value */ - protected final Transformer valueTransformer; - - /** - * Factory method to create a transforming map. - *

- * If there are any elements already in the map being decorated, they - * are NOT transformed. - * 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 NullPointerException 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 NullPointerException 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.isEmpty()) { - 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 NullPointerException 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 if an error occurs while writing to the stream - * @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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @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 {@code 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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/TransformedSortedMap.java b/src/main/java/repack/apache/commons/collections4/map/TransformedSortedMap.java deleted file mode 100644 index 615bd8b4f0..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/TransformedSortedMap.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.map; - -import java.util.Comparator; -import java.util.Map; -import java.util.SortedMap; - -import repack.apache.commons.collections4.Transformer; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public class TransformedSortedMap - extends TransformedMap - implements SortedMap { - - /** Serialization version */ - private static final long serialVersionUID = -8751771676410385778L; - - /** - * Factory method to create a transforming sorted map. - *

- * If there are any elements already in the map being decorated, they are NOT transformed. - * 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 NullPointerException 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 NullPointerException 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.isEmpty()) { - 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 NullPointerException 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; - } - - @Override - public K firstKey() { - return getSortedMap().firstKey(); - } - - @Override - public K lastKey() { - return getSortedMap().lastKey(); - } - - @Override - public Comparator comparator() { - return getSortedMap().comparator(); - } - - @Override - public SortedMap subMap(final K fromKey, final K toKey) { - final SortedMap map = getSortedMap().subMap(fromKey, toKey); - return new TransformedSortedMap<>(map, keyTransformer, valueTransformer); - } - - @Override - public SortedMap headMap(final K toKey) { - final SortedMap map = getSortedMap().headMap(toKey); - return new TransformedSortedMap<>(map, keyTransformer, valueTransformer); - } - - @Override - public SortedMap tailMap(final K fromKey) { - final SortedMap map = getSortedMap().tailMap(fromKey); - return new TransformedSortedMap<>(map, keyTransformer, valueTransformer); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/UnmodifiableEntrySet.java b/src/main/java/repack/apache/commons/collections4/map/UnmodifiableEntrySet.java deleted file mode 100644 index a2e2d86702..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/UnmodifiableEntrySet.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.function.Predicate; - -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.AbstractIteratorDecorator; -import repack.apache.commons.collections4.keyvalue.AbstractMapEntryDecorator; -import repack.apache.commons.collections4.set.AbstractSetDecorator; - -/** - * Decorates a map entry {@code Set} to ensure it can't be altered. - *

- * Attempts to modify it will result in an UnsupportedOperationException. - *

- * - * @param the type of the keys in the map - * @param the type of the values in the map - * - * @since 3.0 - */ -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 NullPointerException 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 NullPointerException 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate> filter) { - 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 multithreaded 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(); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/UnmodifiableMap.java b/src/main/java/repack/apache/commons/collections4/map/UnmodifiableMap.java deleted file mode 100644 index 81919317fc..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/UnmodifiableMap.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.IterableMap; -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.collection.UnmodifiableCollection; -import repack.apache.commons.collections4.iterators.EntrySetMapIterator; -import repack.apache.commons.collections4.iterators.UnmodifiableMapIterator; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -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 NullPointerException 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 NullPointerException 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 if an error occurs while writing to the stream - * @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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/UnmodifiableOrderedMap.java b/src/main/java/repack/apache/commons/collections4/map/UnmodifiableOrderedMap.java deleted file mode 100644 index 0703d3b7fb..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/UnmodifiableOrderedMap.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.OrderedMap; -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.collection.UnmodifiableCollection; -import repack.apache.commons.collections4.iterators.UnmodifiableOrderedMapIterator; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public final class UnmodifiableOrderedMap extends AbstractOrderedMapDecorator implements - Unmodifiable, Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 8136428161720526266L; - - /** - * Factory method to create an unmodifiable sorted map. - * - * @param the key type - * @param the value type - * @param map the map to decorate, must not be null - * @return a new ordered map - * @throws NullPointerException 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 NullPointerException 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 if an error occurs while writing to the stream - * @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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/UnmodifiableSortedMap.java b/src/main/java/repack/apache/commons/collections4/map/UnmodifiableSortedMap.java deleted file mode 100644 index a1c2201645..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/UnmodifiableSortedMap.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.collection.UnmodifiableCollection; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 3.0 - */ -public final class UnmodifiableSortedMap - extends AbstractSortedMapDecorator - implements Unmodifiable, Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 5805344239827376360L; - - /** - * Factory method to create an unmodifiable sorted map. - * - * @param the key type - * @param the value type - * @param map the map to decorate, must not be null - * @return a new unmodifiable sorted map - * @throws NullPointerException 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 NullPointerException 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 if an error occurs while writing to the stream - * @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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @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)); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/map/package-info.java b/src/main/java/repack/apache/commons/collections4/map/package-info.java deleted file mode 100644 index b06a305321..0000000000 --- a/src/main/java/repack/apache/commons/collections4/map/package-info.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 repack.apache.commons.collections4.IterableMap IterableMap}, - * {@link repack.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 - *
- * - */ -package repack.apache.commons.collections4.map; - diff --git a/src/main/java/repack/apache/commons/collections4/multimap/AbstractListValuedMap.java b/src/main/java/repack/apache/commons/collections4/multimap/AbstractListValuedMap.java deleted file mode 100644 index a140012755..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multimap/AbstractListValuedMap.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multimap; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; - -import repack.apache.commons.collections4.ListUtils; -import repack.apache.commons.collections4.ListValuedMap; - -/** - * Abstract implementation of the {@link ListValuedMap} interface to simplify - * the creation of subclass implementations. - *

- * Subclasses specify a Map implementation to use as the internal storage and - * the List implementation to use as values. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.1 - */ -public abstract class AbstractListValuedMap extends AbstractMultiValuedMap - implements ListValuedMap { - - /** - * Constructor needed for subclass serialisation. - */ - protected AbstractListValuedMap() { - } - - /** - * A constructor that wraps, not copies - * - * @param map the map to wrap, must not be null - * @throws NullPointerException if the map is null - */ - protected AbstractListValuedMap(final Map> map) { - super(map); - } - - @Override - @SuppressWarnings("unchecked") - protected Map> getMap() { - return (Map>) super.getMap(); - } - - /** - * Creates a new value collection using the provided factory. - * @return a new list - */ - @Override - protected abstract List createCollection(); - - /** - * Gets the list of values associated with the specified key. This would - * return an empty list in case the mapping is not present - * - * @param key the key to retrieve - * @return the {@code List} of values, will return an empty {@link List} for no mapping - */ - @Override - public List get(final K key) { - return wrappedCollection(key); - } - - @Override - List wrappedCollection(final K key) { - return new WrappedList(key); - } - - /** - * Removes all values associated with the specified key. - *

- * A subsequent {@code get(Object)} would return an empty list. - * - * @param key the key to remove values from - * @return the {@code List} of values removed, will return an empty, - * unmodifiable list for no mapping found. - */ - @Override - public List remove(final Object key) { - return ListUtils.emptyIfNull(getMap().remove(key)); - } - - /** - * Wrapped list to handle add and remove on the list returned by get(object) - */ - private class WrappedList extends WrappedCollection implements List { - - WrappedList(final K key) { - super(key); - } - - @Override - protected List getMapping() { - return getMap().get(key); - } - - @Override - public void add(final int index, final V value) { - List list = getMapping(); - if (list == null) { - list = createCollection(); - getMap().put(key, list); - } - list.add(index, value); - } - - @Override - public boolean addAll(final int index, final Collection c) { - List list = getMapping(); - if (list == null) { - list = createCollection(); - final boolean changed = list.addAll(index, c); - if (changed) { - getMap().put(key, list); - } - return changed; - } - return list.addAll(index, c); - } - - @Override - public V get(final int index) { - final List list = ListUtils.emptyIfNull(getMapping()); - return list.get(index); - } - - @Override - public int indexOf(final Object o) { - final List list = ListUtils.emptyIfNull(getMapping()); - return list.indexOf(o); - } - - @Override - public int lastIndexOf(final Object o) { - final List list = ListUtils.emptyIfNull(getMapping()); - return list.lastIndexOf(o); - } - - @Override - public ListIterator listIterator() { - return new ValuesListIterator(key); - } - - @Override - public ListIterator listIterator(final int index) { - return new ValuesListIterator(key, index); - } - - @Override - public V remove(final int index) { - final List list = ListUtils.emptyIfNull(getMapping()); - final V value = list.remove(index); - if (list.isEmpty()) { - AbstractListValuedMap.this.remove(key); - } - return value; - } - - @Override - public V set(final int index, final V value) { - final List list = ListUtils.emptyIfNull(getMapping()); - return list.set(index, value); - } - - @Override - public List subList(final int fromIndex, final int toIndex) { - final List list = ListUtils.emptyIfNull(getMapping()); - return list.subList(fromIndex, toIndex); - } - - @Override - public boolean equals(final Object other) { - final List list = getMapping(); - if (list == null) { - return Collections.emptyList().equals(other); - } - if (!(other instanceof List)) { - return false; - } - final List otherList = (List) other; - return ListUtils.isEqualList(list, otherList); - } - - @Override - public int hashCode() { - final List list = getMapping(); - return ListUtils.hashCodeForList(list); - } - - } - - /** Values ListIterator */ - private class ValuesListIterator implements ListIterator { - - private final K key; - private List values; - private ListIterator iterator; - - ValuesListIterator(final K key) { - this.key = key; - this.values = ListUtils.emptyIfNull(getMap().get(key)); - this.iterator = values.listIterator(); - } - - ValuesListIterator(final K key, final int index) { - this.key = key; - this.values = ListUtils.emptyIfNull(getMap().get(key)); - this.iterator = values.listIterator(index); - } - - @Override - public void add(final V value) { - if (getMap().get(key) == null) { - final List list = createCollection(); - getMap().put(key, list); - this.values = list; - this.iterator = list.listIterator(); - } - this.iterator.add(value); - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public boolean hasPrevious() { - return iterator.hasPrevious(); - } - - @Override - public V next() { - return iterator.next(); - } - - @Override - public int nextIndex() { - return iterator.nextIndex(); - } - - @Override - public V previous() { - return iterator.previous(); - } - - @Override - public int previousIndex() { - return iterator.previousIndex(); - } - - @Override - public void remove() { - iterator.remove(); - if (values.isEmpty()) { - getMap().remove(key); - } - } - - @Override - public void set(final V value) { - iterator.set(value); - } - - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multimap/AbstractMultiValuedMap.java b/src/main/java/repack/apache/commons/collections4/multimap/AbstractMultiValuedMap.java deleted file mode 100644 index f3d1328da8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multimap/AbstractMultiValuedMap.java +++ /dev/null @@ -1,921 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multimap; - -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.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.IteratorUtils; -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.MultiSet; -import repack.apache.commons.collections4.MultiValuedMap; -import repack.apache.commons.collections4.Transformer; -import repack.apache.commons.collections4.iterators.AbstractIteratorDecorator; -import repack.apache.commons.collections4.iterators.EmptyMapIterator; -import repack.apache.commons.collections4.iterators.IteratorChain; -import repack.apache.commons.collections4.iterators.LazyIteratorChain; -import repack.apache.commons.collections4.iterators.TransformIterator; -import repack.apache.commons.collections4.keyvalue.AbstractMapEntry; -import repack.apache.commons.collections4.keyvalue.UnmodifiableMapEntry; -import repack.apache.commons.collections4.multiset.AbstractMultiSet; -import repack.apache.commons.collections4.multiset.UnmodifiableMultiSet; - -/** - * Abstract implementation of the {@link MultiValuedMap} interface to simplify - * the creation of subclass implementations. - *

- * Subclasses specify a Map implementation to use as the internal storage. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.1 - */ -public abstract class AbstractMultiValuedMap implements MultiValuedMap { - - /** The values view */ - private transient Collection valuesView; - - /** The EntryValues view */ - private transient EntryValues entryValuesView; - - /** The KeyMultiSet view */ - private transient MultiSet keysMultiSetView; - - /** The AsMap view */ - private transient AsMap asMapView; - - /** The map used to store the data */ - private transient Map> map; - - /** - * Constructor needed for subclass serialisation. - */ - protected AbstractMultiValuedMap() { - } - - /** - * Constructor that wraps (not copies). - * - * @param map the map to wrap, must not be null - * @throws NullPointerException if the map is null - */ - @SuppressWarnings("unchecked") - protected AbstractMultiValuedMap(final Map> map) { - this.map = (Map>) Objects.requireNonNull(map, "map"); - } - - /** - * Gets the map being wrapped. - * - * @return the wrapped map - */ - protected Map> getMap() { - return map; - } - - /** - * Sets the map being wrapped. - *

- * NOTE: this method should only be used during deserialization - * - * @param map the map to wrap - */ - @SuppressWarnings("unchecked") - protected void setMap(final Map> map) { - this.map = (Map>) map; - } - - protected abstract Collection createCollection(); - - @Override - public boolean containsKey(final Object key) { - return getMap().containsKey(key); - } - - @Override - public boolean containsValue(final Object value) { - return values().contains(value); - } - - @Override - public boolean containsMapping(final Object key, final Object value) { - final Collection coll = getMap().get(key); - return coll != null && coll.contains(value); - } - - @Override - public Collection> entries() { - return entryValuesView != null ? entryValuesView : (entryValuesView = new EntryValues()); - } - - /** - * Gets the collection of values associated with the specified key. This - * would return an empty collection in case the mapping is not present - * - * @param key the key to retrieve - * @return the {@code Collection} of values, will return an empty {@code Collection} for no mapping - */ - @Override - public Collection get(final K key) { - return wrappedCollection(key); - } - - Collection wrappedCollection(final K key) { - return new WrappedCollection(key); - } - - /** - * Removes all values associated with the specified key. - *

- * A subsequent {@code get(Object)} would return an empty collection. - * - * @param key the key to remove values from - * @return the {@code Collection} of values removed, will return an - * empty, unmodifiable collection for no mapping found - */ - @Override - public Collection remove(final Object key) { - return CollectionUtils.emptyIfNull(getMap().remove(key)); - } - - /** - * Removes a specific key/value mapping from the multivalued map. - *

- * The value 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, an empty collection would be - * returned from a subsequent {@link #get(Object)}. - * - * @param key the key to remove from - * @param value the value to remove - * @return true if the mapping was removed, false otherwise - */ - @Override - public boolean removeMapping(final Object key, final Object value) { - final Collection coll = getMap().get(key); - if (coll == null) { - return false; - } - final boolean changed = coll.remove(value); - if (coll.isEmpty()) { - getMap().remove(key); - } - return changed; - } - - @Override - public boolean isEmpty() { - return getMap().isEmpty(); - } - - @Override - public Set keySet() { - return getMap().keySet(); - } - - /** - * {@inheritDoc} - *

- * This implementation does not cache the total size - * of the multivalued map, but rather calculates it by iterating - * over the entries of the underlying map. - */ - @Override - public int size() { - // the total size should be cached to improve performance - // but this requires that all modifications of the multimap - // (including the wrapped collections and entry/value - // collections) are tracked. - int size = 0; - for (final Collection col : getMap().values()) { - size += col.size(); - } - return size; - } - - /** - * Gets a collection containing all the values in the map. - *

- * Returns a collection containing all the values from all keys. - * - * @return a collection view of the values contained in this map - */ - @Override - public Collection values() { - final Collection vs = valuesView; - return vs != null ? vs : (valuesView = new Values()); - } - - @Override - public void clear() { - getMap().clear(); - } - - /** - * Adds the value to the collection associated with the specified key. - *

- * Unlike a normal {@code 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 - public boolean put(final K key, final V value) { - Collection coll = getMap().get(key); - if (coll == null) { - coll = createCollection(); - if (coll.add(value)) { - map.put(key, coll); - return true; - } - return false; - } - return coll.add(value); - } - - /** - * Copies all of the mappings from the specified map to this map. 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 {@code k} to value - * {@code v} in the specified map. The behavior of this operation is - * undefined if the specified map is modified while the operation is in - * progress. - * - * @param map mappings to be stored in this map, may not be null - * @return true if the map changed as a result of this operation - * @throws NullPointerException if map is null - */ - @Override - public boolean putAll(final Map map) { - Objects.requireNonNull(map, "map"); - boolean changed = false; - for (final Map.Entry entry : map.entrySet()) { - changed |= put(entry.getKey(), entry.getValue()); - } - return changed; - } - - /** - * Copies all of the mappings from the specified MultiValuedMap to this map. - * 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 {@code k} to value {@code v} in the specified map. The - * behavior of this operation is undefined if the specified map is modified - * while the operation is in progress. - * - * @param map mappings to be stored in this map, may not be null - * @return true if the map changed as a result of this operation - * @throws NullPointerException if map is null - */ - @Override - public boolean putAll(final MultiValuedMap map) { - Objects.requireNonNull(map, "map"); - boolean changed = false; - for (final Map.Entry entry : map.entries()) { - changed |= put(entry.getKey(), entry.getValue()); - } - return changed; - } - - /** - * Returns a {@link MultiSet} view of the key mapping contained in this map. - *

- * Returns a MultiSet of keys with its values count as the count of the MultiSet. - * This multiset is backed by the map, so any changes in the map is reflected here. - * Any method which modifies this multiset like {@code add}, {@code remove}, - * {@link Iterator#remove()} etc throws {@code UnsupportedOperationException}. - * - * @return a bag view of the key mapping contained in this map - */ - @Override - public MultiSet keys() { - if (keysMultiSetView == null) { - keysMultiSetView = UnmodifiableMultiSet.unmodifiableMultiSet(new KeysMultiSet()); - } - return keysMultiSetView; - } - - @Override - public Map> asMap() { - return asMapView != null ? asMapView : (asMapView = new AsMap(map)); - } - - /** - * Adds Iterable 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, may not be null - * @return true if this map changed - * @throws NullPointerException if values is null - */ - @Override - public boolean putAll(final K key, final Iterable values) { - Objects.requireNonNull(values, "values"); - - if (values instanceof Collection) { - final Collection valueCollection = (Collection) values; - return !valueCollection.isEmpty() && get(key).addAll(valueCollection); - } - final Iterator it = values.iterator(); - return it.hasNext() && CollectionUtils.addAll(get(key), it); - } - - @Override - public MapIterator mapIterator() { - if (isEmpty()) { - return EmptyMapIterator.emptyMapIterator(); - } - return new MultiValuedMapIterator(); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof MultiValuedMap) { - return asMap().equals(((MultiValuedMap) obj).asMap()); - } - return false; - } - - @Override - public int hashCode() { - return getMap().hashCode(); - } - - @Override - public String toString() { - return getMap().toString(); - } - - /** - * Wrapped collection to handle add and remove on the collection returned - * by get(object). - *

- * Currently, the wrapped collection is not cached and has to be retrieved - * from the underlying map. This is safe, but not very efficient and - * should be improved in subsequent releases. For this purpose, the - * scope of this collection is set to package private to simplify later - * refactoring. - */ - class WrappedCollection implements Collection { - - protected final K key; - - WrappedCollection(final K key) { - this.key = key; - } - - protected Collection getMapping() { - return getMap().get(key); - } - - @Override - public boolean add(final V value) { - Collection coll = getMapping(); - if (coll == null) { - coll = createCollection(); - AbstractMultiValuedMap.this.map.put(key, coll); - } - return coll.add(value); - } - - @Override - public boolean addAll(final Collection other) { - Collection coll = getMapping(); - if (coll == null) { - coll = createCollection(); - AbstractMultiValuedMap.this.map.put(key, coll); - } - return coll.addAll(other); - } - - @Override - public void clear() { - final Collection coll = getMapping(); - if (coll != null) { - coll.clear(); - AbstractMultiValuedMap.this.remove(key); - } - } - - @Override - public Iterator iterator() { - final Collection coll = getMapping(); - if (coll == null) { - return IteratorUtils.EMPTY_ITERATOR; - } - return new ValuesIterator(key); - } - - @Override - public int size() { - final Collection coll = getMapping(); - return coll == null ? 0 : coll.size(); - } - - @Override - public boolean contains(final Object obj) { - final Collection coll = getMapping(); - return coll != null && coll.contains(obj); - } - - @Override - public boolean containsAll(final Collection other) { - final Collection coll = getMapping(); - return coll != null && coll.containsAll(other); - } - - @Override - public boolean isEmpty() { - final Collection coll = getMapping(); - return coll == null || coll.isEmpty(); - } - - @Override - public boolean remove(final Object item) { - final Collection coll = getMapping(); - if (coll == null) { - return false; - } - - final boolean result = coll.remove(item); - if (coll.isEmpty()) { - AbstractMultiValuedMap.this.remove(key); - } - return result; - } - - @Override - public boolean removeAll(final Collection c) { - final Collection coll = getMapping(); - if (coll == null) { - return false; - } - - final boolean result = coll.removeAll(c); - if (coll.isEmpty()) { - AbstractMultiValuedMap.this.remove(key); - } - return result; - } - - @Override - public boolean retainAll(final Collection c) { - final Collection coll = getMapping(); - if (coll == null) { - return false; - } - - final boolean result = coll.retainAll(c); - if (coll.isEmpty()) { - AbstractMultiValuedMap.this.remove(key); - } - return result; - } - - @Override - public Object[] toArray() { - final Collection coll = getMapping(); - if (coll == null) { - return CollectionUtils.EMPTY_COLLECTION.toArray(); - } - return coll.toArray(); - } - - @Override - @SuppressWarnings("unchecked") - public T[] toArray(final T[] a) { - final Collection coll = getMapping(); - if (coll == null) { - return (T[]) CollectionUtils.EMPTY_COLLECTION.toArray(a); - } - return coll.toArray(a); - } - - @Override - public String toString() { - final Collection coll = getMapping(); - if (coll == null) { - return CollectionUtils.EMPTY_COLLECTION.toString(); - } - return coll.toString(); - } - - } - - /** - * Inner class that provides a MultiSet keys view. - */ - private class KeysMultiSet extends AbstractMultiSet { - - @Override - public boolean contains(final Object o) { - return getMap().containsKey(o); - } - - @Override - public boolean isEmpty() { - return getMap().isEmpty(); - } - - @Override - public int size() { - return AbstractMultiValuedMap.this.size(); - } - - @Override - protected int uniqueElements() { - return getMap().size(); - } - - @Override - public int getCount(final Object object) { - int count = 0; - final Collection col = AbstractMultiValuedMap.this.getMap().get(object); - if (col != null) { - count = col.size(); - } - return count; - } - - @Override - protected Iterator> createEntrySetIterator() { - final MapEntryTransformer transformer = new MapEntryTransformer(); - return IteratorUtils.transformedIterator(map.entrySet().iterator(), transformer); - } - - private final class MapEntryTransformer - implements Transformer>, MultiSet.Entry> { - @Override - public MultiSet.Entry transform(final Map.Entry> mapEntry) { - return new AbstractMultiSet.AbstractEntry() { - @Override - public K getElement() { - return mapEntry.getKey(); - } - - @Override - public int getCount() { - return mapEntry.getValue().size(); - } - }; - } - } - } - - /** - * Inner class that provides the Entry view - */ - private class EntryValues extends AbstractCollection> { - - @Override - public Iterator> iterator() { - return new LazyIteratorChain>() { - - final Collection keysCol = new ArrayList<>(getMap().keySet()); - final Iterator keyIterator = keysCol.iterator(); - - @Override - protected Iterator> nextIterator(final int count) { - if (!keyIterator.hasNext()) { - return null; - } - final K key = keyIterator.next(); - final Transformer> entryTransformer = input -> new MultiValuedMapEntry(key, input); - return new TransformIterator<>(new ValuesIterator(key), entryTransformer); - } - }; - } - - @Override - public int size() { - return AbstractMultiValuedMap.this.size(); - } - - } - - /** - * Inner class for MultiValuedMap Entries. - */ - private class MultiValuedMapEntry extends AbstractMapEntry { - - MultiValuedMapEntry(final K key, final V value) { - super(key, value); - } - - @Override - public V setValue(final V value) { - throw new UnsupportedOperationException(); - } - - } - - /** - * Inner class for MapIterator. - */ - private class MultiValuedMapIterator implements MapIterator { - - private final Iterator> it; - - private Entry current; - - MultiValuedMapIterator() { - this.it = AbstractMultiValuedMap.this.entries().iterator(); - } - - @Override - public boolean hasNext() { - return it.hasNext(); - } - - @Override - public K next() { - current = it.next(); - return current.getKey(); - } - - @Override - public K getKey() { - if (current == null) { - throw new IllegalStateException(); - } - return current.getKey(); - } - - @Override - public V getValue() { - if (current == null) { - throw new IllegalStateException(); - } - return current.getValue(); - } - - @Override - public void remove() { - it.remove(); - } - - @Override - public V setValue(final V value) { - if (current == null) { - throw new IllegalStateException(); - } - return current.setValue(value); - } - - } - - /** - * 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 AbstractMultiValuedMap.this.size(); - } - - @Override - public void clear() { - AbstractMultiValuedMap.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; - - ValuesIterator(final Object key) { - this.key = key; - this.values = getMap().get(key); - this.iterator = values.iterator(); - } - - @Override - public void remove() { - iterator.remove(); - if (values.isEmpty()) { - AbstractMultiValuedMap.this.remove(key); - } - } - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public V next() { - return iterator.next(); - } - } - - /** - * Inner class that provides the AsMap view. - */ - private class AsMap extends AbstractMap> { - final transient Map> decoratedMap; - - AsMap(final Map> map) { - this.decoratedMap = map; - } - - @Override - public Set>> entrySet() { - return new AsMapEntrySet(); - } - - @Override - public boolean containsKey(final Object key) { - return decoratedMap.containsKey(key); - } - - @Override - public Collection get(final Object key) { - final Collection collection = decoratedMap.get(key); - if (collection == null) { - return null; - } - @SuppressWarnings("unchecked") - final K k = (K) key; - return wrappedCollection(k); - } - - @Override - public Set keySet() { - return AbstractMultiValuedMap.this.keySet(); - } - - @Override - public int size() { - return decoratedMap.size(); - } - - @Override - public Collection remove(final Object key) { - final Collection collection = decoratedMap.remove(key); - if (collection == null) { - return null; - } - - final Collection output = createCollection(); - output.addAll(collection); - collection.clear(); - return output; - } - - @Override - public boolean equals(final Object object) { - return this == object || decoratedMap.equals(object); - } - - @Override - public int hashCode() { - return decoratedMap.hashCode(); - } - - @Override - public String toString() { - return decoratedMap.toString(); - } - - @Override - public void clear() { - AbstractMultiValuedMap.this.clear(); - } - - class AsMapEntrySet extends AbstractSet>> { - - @Override - public Iterator>> iterator() { - return new AsMapEntrySetIterator(decoratedMap.entrySet().iterator()); - } - - @Override - public int size() { - return AsMap.this.size(); - } - - @Override - public void clear() { - AsMap.this.clear(); - } - - @Override - public boolean contains(final Object o) { - return decoratedMap.entrySet().contains(o); - } - - @Override - public boolean remove(final Object o) { - if (!contains(o)) { - return false; - } - final Map.Entry entry = (Map.Entry) o; - AbstractMultiValuedMap.this.remove(entry.getKey()); - return true; - } - } - - /** - * EntrySet iterator for the asMap view. - */ - class AsMapEntrySetIterator extends AbstractIteratorDecorator>> { - - AsMapEntrySetIterator(final Iterator>> iterator) { - super(iterator); - } - - @Override - public Map.Entry> next() { - final Map.Entry> entry = super.next(); - final K key = entry.getKey(); - return new UnmodifiableMapEntry<>(key, wrappedCollection(key)); - } - } - } - - /** - * 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 Map.Entry> entry : map.entrySet()) { - out.writeObject(entry.getKey()); - out.writeInt(entry.getValue().size()); - for (final V value : entry.getValue()) { - out.writeObject(value); - } - } - } - - /** - * Read the map in using a custom routine. - * @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 ObjectInputStream in) - throws IOException, ClassNotFoundException { - 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 K key = (K) in.readObject(); - final Collection values = get(key); - final int valueSize = in.readInt(); - for (int j = 0; j < valueSize; j++) { - @SuppressWarnings("unchecked") // see above - final V value = (V) in.readObject(); - values.add(value); - } - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multimap/AbstractMultiValuedMapDecorator.java b/src/main/java/repack/apache/commons/collections4/multimap/AbstractMultiValuedMapDecorator.java deleted file mode 100644 index 15ea3b4803..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multimap/AbstractMultiValuedMapDecorator.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multimap; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.MultiSet; -import repack.apache.commons.collections4.MultiValuedMap; - -/** - * Decorates another {@code MultiValuedMap} to provide additional behavior. - *

- * Each method call made on this {@code MultiValuedMap} is forwarded to the - * decorated {@code MultiValuedMap}. This class is used as a framework to build - * to extensions such as synchronized and unmodifiable behavior. - *

- * - * @param the type of key elements - * @param the type of value elements - * - * @since 4.1 - */ -public abstract class AbstractMultiValuedMapDecorator - implements MultiValuedMap, Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 20150612L; - - /** MultiValuedMap to decorate */ - private final MultiValuedMap map; - - /** - * Constructor that wraps (not copies). - * - * @param map the map to decorate, must not be null - * @throws NullPointerException if the map is null - */ - protected AbstractMultiValuedMapDecorator(final MultiValuedMap map) { - this.map = Objects.requireNonNull(map, "map"); - } - - /** - * The decorated multivalued map. - * - * @return the map to decorate - */ - protected MultiValuedMap decorated() { - return map; - } - - @Override - public int size() { - return decorated().size(); - } - - @Override - public boolean isEmpty() { - return decorated().isEmpty(); - } - - @Override - public boolean containsKey(final Object key) { - return decorated().containsKey(key); - } - - @Override - public boolean containsValue(final Object value) { - return decorated().containsValue(value); - } - - @Override - public boolean containsMapping(final Object key, final Object value) { - return decorated().containsMapping(key, value); - } - - @Override - public Collection get(final K key) { - return decorated().get(key); - } - - @Override - public Collection remove(final Object key) { - return decorated().remove(key); - } - - @Override - public boolean removeMapping(final Object key, final Object item) { - return decorated().removeMapping(key, item); - } - - @Override - public void clear() { - decorated().clear(); - } - - @Override - public boolean put(final K key, final V value) { - return decorated().put(key, value); - } - - @Override - public Set keySet() { - return decorated().keySet(); - } - - @Override - public Collection> entries() { - return decorated().entries(); - } - - @Override - public MultiSet keys() { - return decorated().keys(); - } - - @Override - public Collection values() { - return decorated().values(); - } - - @Override - public Map> asMap() { - return decorated().asMap(); - } - - @Override - public boolean putAll(final K key, final Iterable values) { - return decorated().putAll(key, values); - } - - @Override - public boolean putAll(final Map map) { - return decorated().putAll(map); - } - - @Override - public boolean putAll(final MultiValuedMap map) { - return decorated().putAll(map); - } - - @Override - public MapIterator mapIterator() { - return decorated().mapIterator(); - } - - @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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multimap/AbstractSetValuedMap.java b/src/main/java/repack/apache/commons/collections4/multimap/AbstractSetValuedMap.java deleted file mode 100644 index ec6c74ad29..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multimap/AbstractSetValuedMap.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multimap; - -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import repack.apache.commons.collections4.SetUtils; -import repack.apache.commons.collections4.SetValuedMap; - -/** - * Abstract implementation of the {@link SetValuedMap} interface to simplify the - * creation of subclass implementations. - *

- * Subclasses specify a Map implementation to use as the internal storage and - * the Set implementation to use as values. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.1 - */ -public abstract class AbstractSetValuedMap extends AbstractMultiValuedMap - implements SetValuedMap { - - /** - * Constructor needed for subclass serialisation. - */ - protected AbstractSetValuedMap() { - } - - /** - * A constructor that wraps, not copies - * - * @param map the map to wrap, must not be null - * @throws NullPointerException if the map is null - */ - protected AbstractSetValuedMap(final Map> map) { - super(map); - } - - @Override - @SuppressWarnings("unchecked") - protected Map> getMap() { - return (Map>) super.getMap(); - } - - /** - * Creates a new value collection using the provided factory. - * @return a new list - */ - @Override - protected abstract Set createCollection(); - - /** - * Gets the set of values associated with the specified key. This would - * return an empty set in case the mapping is not present - * - * @param key the key to retrieve - * @return the {@code Set} of values, will return an empty - * {@code Set} for no mapping - */ - @Override - public Set get(final K key) { - return wrappedCollection(key); - } - - @Override - Set wrappedCollection(final K key) { - return new WrappedSet(key); - } - - /** - * Removes all values associated with the specified key. - *

- * A subsequent {@code get(Object)} would return an empty set. - * - * @param key the key to remove values from - * @return the {@code Set} of values removed, will return an empty, - * unmodifiable set for no mapping found. - */ - @Override - public Set remove(final Object key) { - return SetUtils.emptyIfNull(getMap().remove(key)); - } - - /** - * Wrapped set to handle add and remove on the collection returned by - * {@code get(Object)}. - */ - private class WrappedSet extends WrappedCollection implements Set { - - WrappedSet(final K key) { - super(key); - } - - @Override - public boolean equals(final Object other) { - final Set set = (Set) getMapping(); - if (set == null) { - return Collections.emptySet().equals(other); - } - if (!(other instanceof Set)) { - return false; - } - final Set otherSet = (Set) other; - return SetUtils.isEqualSet(set, otherSet); - } - - @Override - public int hashCode() { - final Set set = (Set) getMapping(); - return SetUtils.hashCodeForSet(set); - } - - } -} diff --git a/src/main/java/repack/apache/commons/collections4/multimap/ArrayListValuedHashMap.java b/src/main/java/repack/apache/commons/collections4/multimap/ArrayListValuedHashMap.java deleted file mode 100644 index 683a446254..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multimap/ArrayListValuedHashMap.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multimap; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import repack.apache.commons.collections4.MultiValuedMap; - -/** - * Implements a {@code ListValuedMap}, using a {@link HashMap} to provide data - * storage and {@link ArrayList}s as value collections. This is the standard - * implementation of a ListValuedMap. - *

- * Note that ArrayListValuedHashMap 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.1 - */ -public class ArrayListValuedHashMap extends AbstractListValuedMap - implements Serializable { - - /** Serialization Version */ - private static final long serialVersionUID = 20151118L; - - /** - * The initial map capacity used when none specified in constructor. - */ - private static final int DEFAULT_INITIAL_MAP_CAPACITY = 16; - - /** - * The initial list capacity when using none specified in constructor. - */ - private static final int DEFAULT_INITIAL_LIST_CAPACITY = 3; - - /** - * The initial list capacity when creating a new value collection. - */ - private final int initialListCapacity; - - /** - * Creates an empty ArrayListValuedHashMap with the default initial - * map capacity (16) and the default initial list capacity (3). - */ - public ArrayListValuedHashMap() { - this(DEFAULT_INITIAL_MAP_CAPACITY, DEFAULT_INITIAL_LIST_CAPACITY); - } - - /** - * Creates an empty ArrayListValuedHashMap with the default initial - * map capacity (16) and the specified initial list capacity. - * - * @param initialListCapacity the initial capacity used for value collections - */ - public ArrayListValuedHashMap(final int initialListCapacity) { - this(DEFAULT_INITIAL_MAP_CAPACITY, initialListCapacity); - } - - /** - * Creates an empty ArrayListValuedHashMap with the specified initial - * map and list capacities. - * - * @param initialMapCapacity the initial hashmap capacity - * @param initialListCapacity the initial capacity used for value collections - */ - public ArrayListValuedHashMap(final int initialMapCapacity, final int initialListCapacity) { - super(new HashMap>(initialMapCapacity)); - this.initialListCapacity = initialListCapacity; - } - - /** - * Creates an ArrayListValuedHashMap copying all the mappings of the given map. - * - * @param map a {@code MultiValuedMap} to copy into this map - */ - public ArrayListValuedHashMap(final MultiValuedMap map) { - this(map.size(), DEFAULT_INITIAL_LIST_CAPACITY); - super.putAll(map); - } - - /** - * Creates an ArrayListValuedHashMap copying all the mappings of the given map. - * - * @param map a {@code Map} to copy into this map - */ - public ArrayListValuedHashMap(final Map map) { - this(map.size(), DEFAULT_INITIAL_LIST_CAPACITY); - super.putAll(map); - } - - @Override - protected ArrayList createCollection() { - return new ArrayList<>(initialListCapacity); - } - - /** - * Trims the capacity of all value collections to their current size. - */ - public void trimToSize() { - for (final Collection coll : getMap().values()) { - final ArrayList list = (ArrayList) coll; - list.trimToSize(); - } - } - - private void writeObject(final ObjectOutputStream oos) throws IOException { - oos.defaultWriteObject(); - doWriteObject(oos); - } - - private void readObject(final ObjectInputStream ois) throws IOException, ClassNotFoundException { - ois.defaultReadObject(); - setMap(new HashMap>()); - doReadObject(ois); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multimap/HashSetValuedHashMap.java b/src/main/java/repack/apache/commons/collections4/multimap/HashSetValuedHashMap.java deleted file mode 100644 index 91e88f9e5b..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multimap/HashSetValuedHashMap.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multimap; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -import repack.apache.commons.collections4.MultiValuedMap; - -/** - * Implements a {@code SetValuedMap}, using a {@link HashMap} to provide data - * storage and {@link HashSet}s as value collections. This is the standard - * implementation of a SetValuedMap. - *

- * Note that HashSetValuedHashMap 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. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.1 - */ -public class HashSetValuedHashMap extends AbstractSetValuedMap - implements Serializable { - - /** Serialization Version */ - private static final long serialVersionUID = 20151118L; - - /** - * The initial map capacity used when none specified in constructor. - */ - private static final int DEFAULT_INITIAL_MAP_CAPACITY = 16; - - /** - * The initial set capacity when using none specified in constructor. - */ - private static final int DEFAULT_INITIAL_SET_CAPACITY = 3; - - /** - * The initial list capacity when creating a new value collection. - */ - private final int initialSetCapacity; - - /** - * Creates an empty HashSetValuedHashMap with the default initial - * map capacity (16) and the default initial set capacity (3). - */ - public HashSetValuedHashMap() { - this(DEFAULT_INITIAL_MAP_CAPACITY, DEFAULT_INITIAL_SET_CAPACITY); - } - - /** - * Creates an empty HashSetValuedHashMap with the default initial - * map capacity (16) and the specified initial set capacity. - * - * @param initialSetCapacity the initial capacity used for value collections - */ - public HashSetValuedHashMap(final int initialSetCapacity) { - this(DEFAULT_INITIAL_MAP_CAPACITY, initialSetCapacity); - } - - /** - * Creates an empty HashSetValuedHashMap with the specified initial - * map and list capacities. - * - * @param initialMapCapacity the initial hashmap capacity - * @param initialSetCapacity the initial capacity used for value collections - */ - public HashSetValuedHashMap(final int initialMapCapacity, final int initialSetCapacity) { - super(new HashMap>(initialMapCapacity)); - this.initialSetCapacity = initialSetCapacity; - } - - /** - * Creates an HashSetValuedHashMap copying all the mappings of the given map. - * - * @param map a {@code MultiValuedMap} to copy into this map - */ - public HashSetValuedHashMap(final MultiValuedMap map) { - this(map.size(), DEFAULT_INITIAL_SET_CAPACITY); - super.putAll(map); - } - - /** - * Creates an HashSetValuedHashMap copying all the mappings of the given map. - * - * @param map a {@code Map} to copy into this map - */ - public HashSetValuedHashMap(final Map map) { - this(map.size(), DEFAULT_INITIAL_SET_CAPACITY); - super.putAll(map); - } - - @Override - protected HashSet createCollection() { - return new HashSet<>(initialSetCapacity); - } - - private void writeObject(final ObjectOutputStream oos) throws IOException { - oos.defaultWriteObject(); - doWriteObject(oos); - } - - private void readObject(final ObjectInputStream ois) throws IOException, ClassNotFoundException { - ois.defaultReadObject(); - setMap(new HashMap>()); - doReadObject(ois); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multimap/TransformedMultiValuedMap.java b/src/main/java/repack/apache/commons/collections4/multimap/TransformedMultiValuedMap.java deleted file mode 100644 index 6de75335b4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multimap/TransformedMultiValuedMap.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multimap; - -import java.util.Iterator; -import java.util.Map; -import java.util.Objects; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.FluentIterable; -import repack.apache.commons.collections4.MultiValuedMap; -import repack.apache.commons.collections4.Transformer; - -/** - * Decorates another {@code MultiValuedMap} to transform objects that are added. - *

- * This class affects the MultiValuedMap put methods. 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 TransformedMultiValuedMap is not synchronized and is not thread-safe. - *

- * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.1 - */ -public class TransformedMultiValuedMap extends AbstractMultiValuedMapDecorator { - - /** Serialization Version */ - private static final long serialVersionUID = 20150612L; - - /** The key transformer */ - private final Transformer keyTransformer; - - /** The value transformer */ - private final Transformer valueTransformer; - - /** - * Factory method to create a transforming MultiValuedMap. - *

- * If there are any elements already in the map being decorated, they are - * NOT transformed. Contrast this with - * {@link #transformedMap(MultiValuedMap, Transformer, Transformer)}. - * - * @param the key type - * @param the value type - * @param map the MultiValuedMap to decorate, may 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 - * @return a new transformed MultiValuedMap - * @throws NullPointerException if map is null - */ - public static TransformedMultiValuedMap transformingMap(final MultiValuedMap map, - final Transformer keyTransformer, - final Transformer valueTransformer) { - return new TransformedMultiValuedMap<>(map, keyTransformer, valueTransformer); - } - - /** - * Factory method to create a transforming MultiValuedMap 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(MultiValuedMap, Transformer, Transformer)}. - * - * @param the key type - * @param the value type - * @param map the MultiValuedMap to decorate, may 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 - * @return a new transformed MultiValuedMap - * @throws NullPointerException if map is null - */ - public static TransformedMultiValuedMap transformedMap(final MultiValuedMap map, - final Transformer keyTransformer, - final Transformer valueTransformer) { - final TransformedMultiValuedMap decorated = - new TransformedMultiValuedMap<>(map, keyTransformer, valueTransformer); - if (!map.isEmpty()) { - final MultiValuedMap mapCopy = new ArrayListValuedHashMap<>(map); - decorated.clear(); - decorated.putAll(mapCopy); - } - 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 MultiValuedMap to decorate, may 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 NullPointerException if map is null - */ - protected TransformedMultiValuedMap(final MultiValuedMap map, - final Transformer keyTransformer, - final Transformer valueTransformer) { - super(map); - this.keyTransformer = keyTransformer; - this.valueTransformer = valueTransformer; - } - - /** - * 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); - } - - @Override - public boolean put(final K key, final V value) { - return decorated().put(transformKey(key), transformValue(value)); - } - - @Override - public boolean putAll(final K key, final Iterable values) { - Objects.requireNonNull(values, "values"); - - final Iterable transformedValues = FluentIterable.of(values).transform(valueTransformer); - final Iterator it = transformedValues.iterator(); - return it.hasNext() && CollectionUtils.addAll(decorated().get(transformKey(key)), it); - } - - @Override - public boolean putAll(final Map map) { - Objects.requireNonNull(map, "map"); - boolean changed = false; - for (final Map.Entry entry : map.entrySet()) { - changed |= put(entry.getKey(), entry.getValue()); - } - return changed; - } - - @Override - public boolean putAll(final MultiValuedMap map) { - Objects.requireNonNull(map, "map"); - boolean changed = false; - for (final Map.Entry entry : map.entries()) { - changed |= put(entry.getKey(), entry.getValue()); - } - return changed; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multimap/UnmodifiableMultiValuedMap.java b/src/main/java/repack/apache/commons/collections4/multimap/UnmodifiableMultiValuedMap.java deleted file mode 100644 index 45c74cf015..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multimap/UnmodifiableMultiValuedMap.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multimap; - -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.MultiSet; -import repack.apache.commons.collections4.MultiValuedMap; -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.collection.UnmodifiableCollection; -import repack.apache.commons.collections4.iterators.UnmodifiableMapIterator; -import repack.apache.commons.collections4.map.UnmodifiableMap; -import repack.apache.commons.collections4.multiset.UnmodifiableMultiSet; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates another {@link MultiValuedMap} to ensure it can't be altered. - *

- * Attempts to modify it will result in an UnsupportedOperationException. - *

- * - * @param the type of key elements - * @param the type of value elements - * - * @since 4.1 - */ -public final class UnmodifiableMultiValuedMap - extends AbstractMultiValuedMapDecorator implements Unmodifiable { - - /** Serialization version */ - private static final long serialVersionUID = 20150612L; - - /** - * Factory method to create an unmodifiable MultiValuedMap. - *

- * If the map passed in is already unmodifiable, it is returned. - * - * @param the type of key elements - * @param the type of value elements - * @param map the map to decorate, may not be null - * @return an unmodifiable MultiValuedMap - * @throws NullPointerException if map is null - */ - @SuppressWarnings("unchecked") - public static UnmodifiableMultiValuedMap unmodifiableMultiValuedMap( - final MultiValuedMap map) { - if (map instanceof Unmodifiable) { - return (UnmodifiableMultiValuedMap) map; - } - return new UnmodifiableMultiValuedMap<>(map); - } - - /** - * Constructor that wraps (not copies). - * - * @param map the MultiValuedMap to decorate, may not be null - * @throws NullPointerException if the map is null - */ - @SuppressWarnings("unchecked") - private UnmodifiableMultiValuedMap(final MultiValuedMap map) { - super((MultiValuedMap) map); - } - - @Override - public Collection remove(final Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeMapping(final Object key, final Object item) { - throw new UnsupportedOperationException(); - } - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - - @Override - public Collection get(final K key) { - return UnmodifiableCollection.unmodifiableCollection(decorated().get(key)); - } - - @Override - public boolean put(final K key, final V value) { - throw new UnsupportedOperationException(); - } - - @Override - public Set keySet() { - return UnmodifiableSet.unmodifiableSet(decorated().keySet()); - } - - @Override - public Collection> entries() { - return UnmodifiableCollection.unmodifiableCollection(decorated().entries()); - } - - @Override - public MultiSet keys() { - return UnmodifiableMultiSet.unmodifiableMultiSet(decorated().keys()); - } - - @Override - public Collection values() { - return UnmodifiableCollection.unmodifiableCollection(decorated().values()); - } - - @Override - public Map> asMap() { - return UnmodifiableMap.unmodifiableMap(decorated().asMap()); - } - - @Override - public MapIterator mapIterator() { - return UnmodifiableMapIterator.unmodifiableMapIterator(decorated().mapIterator()); - } - - @Override - public boolean putAll(final K key, final Iterable values) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean putAll(final Map map) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean putAll(final MultiValuedMap map) { - throw new UnsupportedOperationException(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multimap/package-info.java b/src/main/java/repack/apache/commons/collections4/multimap/package-info.java deleted file mode 100644 index 26f5589050..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multimap/package-info.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 repack.apache.commons.collections4.MultiValuedMap} interfaces. - * A MultiValuedMap holds a collection of values against each key. - *

- * The following implementations are provided in the package: - *

    - *
  • ArrayListValuedHashMap - ListValuedMap implementation using a HashMap/ArrayList - *
  • HashSetValuedHashMap - SetValuedMap implementation using a HashMap/HashSet - *
- *

- * The following decorators are provided in the package: - *

    - *
  • Transformed - transforms elements added to the MultiValuedMap - *
  • Unmodifiable - ensures the collection cannot be altered - *
- * - */ -package repack.apache.commons.collections4.multimap; diff --git a/src/main/java/repack/apache/commons/collections4/multiset/AbstractMapMultiSet.java b/src/main/java/repack/apache/commons/collections4/multiset/AbstractMapMultiSet.java deleted file mode 100644 index 0a2ca6cb65..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multiset/AbstractMapMultiSet.java +++ /dev/null @@ -1,553 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multiset; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.reflect.Array; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.Map; - -import repack.apache.commons.collections4.MultiSet; -import repack.apache.commons.collections4.iterators.AbstractIteratorDecorator; - -/** - * Abstract implementation of the {@link MultiSet} 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 multiset elements to a number; the number represents the - * number of occurrences of that element in the multiset. - *

- * - * @param the type held in the multiset - * @since 4.1 - */ -public abstract class AbstractMapMultiSet extends AbstractMultiSet { - - /** The map to use to store the data */ - private transient Map map; - /** The current total size of the multiset */ - private transient int size; - /** The modification count for fail fast iterators */ - private transient int modCount; - - /** - * Constructor needed for subclass serialisation. - */ - protected AbstractMapMultiSet() { - } - - /** - * 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 AbstractMapMultiSet(final Map map) { - this.map = map; - } - - /** - * Utility method for implementations to access the map that backs this multiset. - * Not intended for interactive use outside of subclasses. - * - * @return the map being used by the MultiSet - */ - protected Map getMap() { - return map; - } - - /** - * Sets the map being wrapped. - *

- * NOTE: this method should only be used during deserialization - * - * @param map the map to wrap - */ - protected void setMap(final Map map) { - this.map = map; - } - - /** - * Returns the number of elements in this multiset. - * - * @return current size of the multiset - */ - @Override - public int size() { - return size; - } - - /** - * Returns true if the underlying map is empty. - * - * @return true if multiset is empty - */ - @Override - public boolean isEmpty() { - return map.isEmpty(); - } - - /** - * Returns the number of occurrence of the given element in this multiset 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 - */ - @Override - public int getCount(final Object object) { - final MutableInteger count = map.get(object); - if (count != null) { - return count.value; - } - return 0; - } - - /** - * Determines if the multiset 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 multiset contains the given element - */ - @Override - public boolean contains(final Object object) { - return map.containsKey(object); - } - - /** - * Gets an iterator over the multiset elements. Elements present in the - * MultiSet more than once will be returned repeatedly. - * - * @return the iterator - */ - @Override - public Iterator iterator() { - return new MapBasedMultiSetIterator<>(this); - } - - /** - * Inner class iterator for the MultiSet. - */ - private static class MapBasedMultiSetIterator implements Iterator { - private final AbstractMapMultiSet parent; - private final Iterator> entryIterator; - private Map.Entry current; - private int itemCount; - private final int mods; - private boolean canRemove; - - /** - * Constructor. - * - * @param parent the parent multiset - */ - MapBasedMultiSetIterator(final AbstractMapMultiSet parent) { - this.parent = parent; - this.entryIterator = parent.map.entrySet().iterator(); - this.current = null; - this.mods = parent.modCount; - this.canRemove = false; - } - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return itemCount > 0 || entryIterator.hasNext(); - } - - /** {@inheritDoc} */ - @Override - 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} */ - @Override - public void remove() { - if (parent.modCount != mods) { - throw new ConcurrentModificationException(); - } - if (!canRemove) { - throw new IllegalStateException(); - } - final MutableInteger mut = current.getValue(); - if (mut.value > 1) { - mut.value--; - } else { - entryIterator.remove(); - } - parent.size--; - canRemove = false; - } - } - - @Override - public int add(final E object, final int occurrences) { - if (occurrences < 0) { - throw new IllegalArgumentException("Occurrences must not be negative."); - } - - final MutableInteger mut = map.get(object); - final int oldCount = mut != null ? mut.value : 0; - - if (occurrences > 0) { - modCount++; - size += occurrences; - if (mut == null) { - map.put(object, new MutableInteger(occurrences)); - } else { - mut.value += occurrences; - } - } - return oldCount; - } - - /** - * Clears the multiset by clearing the underlying map. - */ - @Override - public void clear() { - modCount++; - map.clear(); - size = 0; - } - - @Override - public int remove(final Object object, final int occurrences) { - if (occurrences < 0) { - throw new IllegalArgumentException("Occurrences must not be negative."); - } - - final MutableInteger mut = map.get(object); - if (mut == null) { - return 0; - } - final int oldCount = mut.value; - if (occurrences > 0) { - modCount++; - if (occurrences < mut.value) { - mut.value -= occurrences; - size -= occurrences; - } else { - map.remove(object); - size -= mut.value; - mut.value = 0; - } - } - return oldCount; - } - - /** - * 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)) { - return false; - } - return ((MutableInteger) obj).value == value; - } - - @Override - public int hashCode() { - return value; - } - } - - @Override - protected Iterator createUniqueSetIterator() { - return new UniqueSetIterator<>(getMap().keySet().iterator(), this); - } - - @Override - protected int uniqueElements() { - return map.size(); - } - - @Override - protected Iterator> createEntrySetIterator() { - return new EntrySetIterator<>(map.entrySet().iterator(), this); - } - - /** - * Inner class UniqueSetIterator. - */ - protected static class UniqueSetIterator extends AbstractIteratorDecorator { - - /** The parent multiset */ - protected final AbstractMapMultiSet parent; - - /** The last returned element */ - protected E lastElement; - - /** Whether remove is allowed at present */ - protected boolean canRemove; - - /** - * Constructor. - * @param iterator the iterator to decorate - * @param parent the parent multiset - */ - protected UniqueSetIterator(final Iterator iterator, final AbstractMapMultiSet parent) { - super(iterator); - this.parent = parent; - } - - @Override - public E next() { - lastElement = super.next(); - canRemove = true; - return lastElement; - } - - @Override - public void remove() { - if (!canRemove) { - throw new IllegalStateException("Iterator remove() can only be called once after next()"); - } - final int count = parent.getCount(lastElement); - super.remove(); - parent.remove(lastElement, count); - lastElement = null; - canRemove = false; - } - } - - /** - * Inner class EntrySetIterator. - */ - protected static class EntrySetIterator implements Iterator> { - - /** The parent map */ - protected final AbstractMapMultiSet parent; - - protected final Iterator> decorated; - - /** The last returned entry */ - protected Entry last; - - /** Whether remove is allowed at present */ - protected boolean canRemove; - - /** - * Constructor. - * @param iterator the iterator to decorate - * @param parent the parent multiset - */ - protected EntrySetIterator(final Iterator> iterator, - final AbstractMapMultiSet parent) { - this.decorated = iterator; - this.parent = parent; - } - - @Override - public boolean hasNext() { - return decorated.hasNext(); - } - - @Override - public Entry next() { - last = new MultiSetEntry<>(decorated.next()); - canRemove = true; - return last; - } - - @Override - public void remove() { - if (!canRemove) { - throw new IllegalStateException("Iterator remove() can only be called once after next()"); - } - decorated.remove(); - last = null; - canRemove = false; - } - } - - /** - * Inner class MultiSetEntry. - */ - protected static class MultiSetEntry extends AbstractEntry { - - protected final Map.Entry parentEntry; - - /** - * Constructor. - * @param parentEntry the entry to decorate - */ - protected MultiSetEntry(final Map.Entry parentEntry) { - this.parentEntry = parentEntry; - } - - @Override - public E getElement() { - return parentEntry.getKey(); - } - - @Override - public int getCount() { - return parentEntry.getValue().value; - } - } - - /** - * Write the multiset out using a custom routine. - * @param out the output stream - * @throws IOException any of the usual I/O related exceptions - */ - @Override - protected void doWriteObject(final ObjectOutputStream out) throws IOException { - out.writeInt(map.size()); - for (final Map.Entry entry : map.entrySet()) { - out.writeObject(entry.getKey()); - out.writeInt(entry.getValue().value); - } - } - - /** - * Read the multiset in using a custom routine. - * @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 - */ - @Override - protected void doReadObject(final ObjectInputStream in) - throws IOException, ClassNotFoundException { - 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; - } - } - - /** - * Returns an array of all of this multiset's elements. - * - * @return an array of all of this multiset's elements - */ - @Override - public Object[] toArray() { - final Object[] result = new Object[size()]; - int i = 0; - for (final Map.Entry entry : map.entrySet()) { - final E current = entry.getKey(); - final MutableInteger count = entry.getValue(); - for (int index = count.value; index > 0; index--) { - result[i++] = current; - } - } - return result; - } - - /** - * Returns an array of all of this multiset's elements. - * If the input array has more elements than are in the multiset, - * 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 multiset'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 - */ - @Override - 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; - for (final Map.Entry entry : map.entrySet()) { - final E current = entry.getKey(); - final MutableInteger count = entry.getValue(); - for (int index = count.value; 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; - } - - @Override - public boolean equals(final Object object) { - if (object == this) { - return true; - } - if (!(object instanceof MultiSet)) { - return false; - } - final MultiSet other = (MultiSet) object; - if (other.size() != size()) { - return false; - } - for (final E element : map.keySet()) { - if (other.getCount(element) != getCount(element)) { - return false; - } - } - return true; - } - - @Override - public int hashCode() { - int total = 0; - for (final Map.Entry entry : map.entrySet()) { - final E element = entry.getKey(); - final MutableInteger count = entry.getValue(); - total += (element == null ? 0 : element.hashCode()) ^ count.value; - } - return total; - } -} diff --git a/src/main/java/repack/apache/commons/collections4/multiset/AbstractMultiSet.java b/src/main/java/repack/apache/commons/collections4/multiset/AbstractMultiSet.java deleted file mode 100644 index d267249f7c..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multiset/AbstractMultiSet.java +++ /dev/null @@ -1,489 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multiset; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.util.AbstractCollection; -import java.util.AbstractSet; -import java.util.Collection; -import java.util.Iterator; -import java.util.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.IteratorUtils; -import repack.apache.commons.collections4.MultiSet; -import repack.apache.commons.collections4.Transformer; - -/** - * Abstract implementation of the {@link MultiSet} interface to simplify the - * creation of subclass implementations. - * - * @param the type held in the multiset - * @since 4.1 - */ -public abstract class AbstractMultiSet extends AbstractCollection implements MultiSet { - - /** View of the elements */ - private transient Set uniqueSet; - /** View of the entries */ - private transient Set> entrySet; - - /** - * Constructor needed for subclass serialisation. - */ - protected AbstractMultiSet() { - } - - /** - * Returns the number of elements in this multiset. - * - * @return current size of the multiset - */ - @Override - public int size() { - int totalSize = 0; - for (final Entry entry : entrySet()) { - totalSize += entry.getCount(); - } - return totalSize; - } - - /** - * Returns the number of occurrence of the given element in this multiset by - * iterating over its entrySet. - * - * @param object the object to search for - * @return the number of occurrences of the object, zero if not found - */ - @Override - public int getCount(final Object object) { - for (final Entry entry : entrySet()) { - final E element = entry.getElement(); - if (Objects.equals(element, object)) { - return entry.getCount(); - } - } - return 0; - } - - @Override - public int setCount(final E object, final int count) { - if (count < 0) { - throw new IllegalArgumentException("Count must not be negative."); - } - - final int oldCount = getCount(object); - if (oldCount < count) { - add(object, count - oldCount); - } else { - remove(object, oldCount - count); - } - return oldCount; - } - - /** - * Determines if the multiset contains the given element. - * - * @param object the object to search for - * @return true if the multiset contains the given element - */ - @Override - public boolean contains(final Object object) { - return getCount(object) > 0; - } - - /** - * Gets an iterator over the multiset elements. Elements present in the - * MultiSet more than once will be returned repeatedly. - * - * @return the iterator - */ - @Override - public Iterator iterator() { - return new MultiSetIterator<>(this); - } - - /** - * Inner class iterator for the MultiSet. - */ - private static class MultiSetIterator implements Iterator { - private final AbstractMultiSet parent; - private final Iterator> entryIterator; - private Entry current; - private int itemCount; - private boolean canRemove; - - /** - * Constructor. - * - * @param parent the parent multiset - */ - MultiSetIterator(final AbstractMultiSet parent) { - this.parent = parent; - this.entryIterator = parent.entrySet().iterator(); - this.current = null; - this.canRemove = false; - } - - /** {@inheritDoc} */ - @Override - public boolean hasNext() { - return itemCount > 0 || entryIterator.hasNext(); - } - - /** {@inheritDoc} */ - @Override - public E next() { - if (itemCount == 0) { - current = entryIterator.next(); - itemCount = current.getCount(); - } - canRemove = true; - itemCount--; - return current.getElement(); - } - - /** {@inheritDoc} */ - @Override - public void remove() { - if (!canRemove) { - throw new IllegalStateException(); - } - final int count = current.getCount(); - if (count > 1) { - parent.remove(current.getElement()); - } else { - entryIterator.remove(); - } - canRemove = false; - } - } - - @Override - public boolean add(final E object) { - add(object, 1); - return true; - } - - @Override - public int add(final E object, final int occurrences) { - throw new UnsupportedOperationException(); - } - - /** - * Clears the multiset removing all elements from the entrySet. - */ - @Override - public void clear() { - final Iterator> it = entrySet().iterator(); - while (it.hasNext()) { - it.next(); - it.remove(); - } - } - - @Override - public boolean remove(final Object object) { - return remove(object, 1) != 0; - } - - @Override - public int remove(final Object object, final int occurrences) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeAll(final Collection coll) { - boolean result = false; - for (final Object obj : coll) { - final boolean changed = remove(obj, getCount(obj)) != 0; - result = result || changed; - } - return result; - } - - /** - * Returns a view of the unique elements of this multiset. - * - * @return the set of unique elements in this multiset - */ - @Override - public Set uniqueSet() { - if (uniqueSet == null) { - uniqueSet = createUniqueSet(); - } - return uniqueSet; - } - - /** - * Create a new view for the set of unique elements in this multiset. - * - * @return a view of the set of unique elements - */ - protected Set createUniqueSet() { - return new UniqueSet<>(this); - } - - /** - * Creates a unique set iterator. - * Subclasses can override this to return iterators with different properties. - * - * @return the uniqueSet iterator - */ - protected Iterator createUniqueSetIterator() { - final Transformer, E> transformer = Entry::getElement; - return IteratorUtils.transformedIterator(entrySet().iterator(), transformer); - } - - /** - * Returns an unmodifiable view of the entries of this multiset. - * - * @return the set of entries in this multiset - */ - @Override - public Set> entrySet() { - if (entrySet == null) { - entrySet = createEntrySet(); - } - return entrySet; - } - - /** - * Create a new view for the set of entries in this multiset. - * - * @return a view of the set of entries - */ - protected Set> createEntrySet() { - return new EntrySet<>(this); - } - - /** - * Returns the number of unique elements in this multiset. - * - * @return the number of unique elements - */ - protected abstract int uniqueElements(); - - /** - * Creates an entry set iterator. - * Subclasses can override this to return iterators with different properties. - * - * @return the entrySet iterator - */ - protected abstract Iterator> createEntrySetIterator(); - - /** - * Inner class UniqueSet. - */ - protected static class UniqueSet extends AbstractSet { - - /** The parent multiset */ - protected final AbstractMultiSet parent; - - /** - * Constructs a new unique element view of the MultiSet. - * - * @param parent the parent MultiSet - */ - protected UniqueSet(final AbstractMultiSet parent) { - this.parent = parent; - } - - @Override - public Iterator iterator() { - return parent.createUniqueSetIterator(); - } - - @Override - public boolean contains(final Object key) { - return parent.contains(key); - } - - @Override - public boolean containsAll(final Collection coll) { - return parent.containsAll(coll); - } - - @Override - public boolean remove(final Object key) { - return parent.remove(key, parent.getCount(key)) != 0; - } - - @Override - public int size() { - return parent.uniqueElements(); - } - - @Override - public void clear() { - parent.clear(); - } - } - - /** - * Inner class EntrySet. - */ - protected static class EntrySet extends AbstractSet> { - - private final AbstractMultiSet parent; - - /** - * Constructs a new view of the MultiSet. - * - * @param parent the parent MultiSet - */ - protected EntrySet(final AbstractMultiSet parent) { - this.parent = parent; - } - - @Override - public int size() { - return parent.uniqueElements(); - } - - @Override - public Iterator> iterator() { - return parent.createEntrySetIterator(); - } - - @Override - public boolean contains(final Object obj) { - if (!(obj instanceof Entry)) { - return false; - } - final Entry entry = (Entry) obj; - final Object element = entry.getElement(); - return parent.getCount(element) == entry.getCount(); - } - - @Override - public boolean remove(final Object obj) { - if (!(obj instanceof Entry)) { - return false; - } - final Entry entry = (Entry) obj; - final Object element = entry.getElement(); - if (parent.contains(element)) { - final int count = parent.getCount(element); - if (entry.getCount() == count) { - parent.remove(element, count); - return true; - } - } - return false; - } - } - - /** - * Inner class AbstractEntry. - */ - protected abstract static class AbstractEntry implements Entry { - - @Override - public boolean equals(final Object object) { - if (object instanceof Entry) { - final Entry other = (Entry) object; - final E element = this.getElement(); - final Object otherElement = other.getElement(); - - return this.getCount() == other.getCount() && - Objects.equals(element, otherElement); - } - return false; - } - - @Override - public int hashCode() { - final E element = getElement(); - return (element == null ? 0 : element.hashCode()) ^ getCount(); - } - - @Override - public String toString() { - return String.format("%s:%d", getElement(), getCount()); - } - } - - /** - * Write the multiset 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(entrySet().size()); - for (final Entry entry : entrySet()) { - out.writeObject(entry.getElement()); - out.writeInt(entry.getCount()); - } - } - - /** - * Read the multiset in using a custom routine. - * @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 ObjectInputStream in) - throws IOException, ClassNotFoundException { - 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(); - setCount(obj, count); - } - } - - @Override - public boolean equals(final Object object) { - if (object == this) { - return true; - } - if (!(object instanceof MultiSet)) { - return false; - } - final MultiSet other = (MultiSet) object; - if (other.size() != size()) { - return false; - } - for (final Entry entry : entrySet()) { - if (other.getCount(entry.getElement()) != getCount(entry.getElement())) { - return false; - } - } - return true; - } - - @Override - public int hashCode() { - return entrySet().hashCode(); - } - - /** - * Implement a toString() method suitable for debugging. - * - * @return a debugging toString - */ - @Override - public String toString() { - return entrySet().toString(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multiset/AbstractMultiSetDecorator.java b/src/main/java/repack/apache/commons/collections4/multiset/AbstractMultiSetDecorator.java deleted file mode 100644 index 6642d31e5d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multiset/AbstractMultiSetDecorator.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multiset; - -import java.util.Set; - -import repack.apache.commons.collections4.MultiSet; -import repack.apache.commons.collections4.collection.AbstractCollectionDecorator; - -/** - * Decorates another {@code MultiSet} to provide additional behavior. - *

- * Methods are forwarded directly to the decorated multiset. - *

- * - * @param the type held in the multiset - * @since 4.1 - */ -public abstract class AbstractMultiSetDecorator - extends AbstractCollectionDecorator implements MultiSet { - - /** Serialization version */ - private static final long serialVersionUID = 20150610L; - - /** - * Constructor only used in deserialization, do not use otherwise. - */ - protected AbstractMultiSetDecorator() { - } - - /** - * Constructor that wraps (not copies). - * - * @param multiset the multiset to decorate, must not be null - * @throws NullPointerException if multiset is null - */ - protected AbstractMultiSetDecorator(final MultiSet multiset) { - super(multiset); - } - - /** - * Gets the multiset being decorated. - * - * @return the decorated multiset - */ - @Override - protected MultiSet decorated() { - return (MultiSet) super.decorated(); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - - - @Override - public int getCount(final Object object) { - return decorated().getCount(object); - } - - @Override - public int setCount(final E object, final int count) { - return decorated().setCount(object, count); - } - - @Override - public int add(final E object, final int count) { - return decorated().add(object, count); - } - - @Override - public int remove(final Object object, final int count) { - return decorated().remove(object, count); - } - - @Override - public Set uniqueSet() { - return decorated().uniqueSet(); - } - - @Override - public Set> entrySet() { - return decorated().entrySet(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multiset/HashMultiSet.java b/src/main/java/repack/apache/commons/collections4/multiset/HashMultiSet.java deleted file mode 100644 index ae6a473e84..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multiset/HashMultiSet.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multiset; - -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 {@code MultiSet}, using a {@link HashMap} to provide the - * data storage. This is the standard implementation of a multiset. - *

- * A {@code MultiSet} 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. - *

- * - * @param the type held in the multiset - * @since 4.1 - */ -public class HashMultiSet extends AbstractMapMultiSet implements Serializable { - - /** Serial version lock */ - private static final long serialVersionUID = 20150610L; - - /** - * Constructs an empty {@link HashMultiSet}. - */ - public HashMultiSet() { - super(new HashMap<>()); - } - - /** - * Constructs a multiset containing all the members of the given collection. - * - * @param coll a collection to copy into this multiset - */ - public HashMultiSet(final Collection coll) { - this(); - addAll(coll); - } - - /** - * Write the multiset out using a custom routine. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - private void writeObject(final ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - super.doWriteObject(out); - } - - /** - * Read the multiset in using a custom routine. - * - * @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 - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - setMap(new HashMap<>()); - super.doReadObject(in); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multiset/PredicatedMultiSet.java b/src/main/java/repack/apache/commons/collections4/multiset/PredicatedMultiSet.java deleted file mode 100644 index e2419b2c0c..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multiset/PredicatedMultiSet.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multiset; - -import java.util.Set; - -import repack.apache.commons.collections4.MultiSet; -import repack.apache.commons.collections4.Predicate; -import repack.apache.commons.collections4.collection.PredicatedCollection; - -/** - * Decorates another {@link MultiSet} to validate that additions - * match a specified predicate. - *

- * This multiset exists to provide validation for the decorated multiset. - * It is normally created to decorate an empty multiset. - * If an object cannot be added to the multiset, an {@link IllegalArgumentException} - * is thrown. - *

- *

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

- *
- * MultiSet<E> set =
- *      PredicatedMultiSet.predicatedMultiSet(new HashMultiSet<E>(),
- *                                            NotNullPredicate.notNullPredicate());
- * 
- * - * @param the type held in the multiset - * @since 4.1 - */ -public class PredicatedMultiSet extends PredicatedCollection implements MultiSet { - - /** Serialization version */ - private static final long serialVersionUID = 20150629L; - - /** - * Factory method to create a predicated (validating) multiset. - *

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

- * If there are any elements already in the multiset being decorated, they - * are validated. - * - * @param multiset the multiset to decorate, must not be null - * @param predicate the predicate to use for validation, must not be null - * @throws NullPointerException if multiset or predicate is null - * @throws IllegalArgumentException if the multiset contains invalid elements - */ - protected PredicatedMultiSet(final MultiSet multiset, final Predicate predicate) { - super(multiset, predicate); - } - - /** - * Gets the decorated multiset. - * - * @return the decorated multiset - */ - @Override - protected MultiSet decorated() { - return (MultiSet) super.decorated(); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - - - @Override - public int add(final E object, final int count) { - validate(object); - return decorated().add(object, count); - } - - @Override - public int remove(final Object object, final int count) { - return decorated().remove(object, count); - } - - @Override - public int getCount(final Object object) { - return decorated().getCount(object); - } - - @Override - public int setCount(final E object, final int count) { - validate(object); - return decorated().setCount(object, count); - } - - @Override - public Set uniqueSet() { - return decorated().uniqueSet(); - } - - @Override - public Set> entrySet() { - return decorated().entrySet(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multiset/SynchronizedMultiSet.java b/src/main/java/repack/apache/commons/collections4/multiset/SynchronizedMultiSet.java deleted file mode 100644 index d3b48e793f..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multiset/SynchronizedMultiSet.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multiset; - -import java.util.Set; - -import repack.apache.commons.collections4.MultiSet; -import repack.apache.commons.collections4.collection.SynchronizedCollection; - -/** - * Decorates another {@link MultiSet} to synchronize its behavior - * for a multithreaded environment. - *

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

- * - * @param the type held in the multiset - * @since 4.1 - */ -public class SynchronizedMultiSet extends SynchronizedCollection implements MultiSet { - - /** Serialization version */ - private static final long serialVersionUID = 20150629L; - - /** - * Factory method to create a synchronized multiset. - * - * @param the type of the elements in the multiset - * @param multiset the multiset to decorate, must not be null - * @return a new synchronized MultiSet - * @throws NullPointerException if multiset is null - */ - public static SynchronizedMultiSet synchronizedMultiSet(final MultiSet multiset) { - return new SynchronizedMultiSet<>(multiset); - } - - /** - * Constructor that wraps (not copies). - * - * @param multiset the multiset to decorate, must not be null - * @throws NullPointerException if multiset is null - */ - protected SynchronizedMultiSet(final MultiSet multiset) { - super(multiset); - } - - /** - * Constructor that wraps (not copies). - * - * @param multiset the multiset to decorate, must not be null - * @param lock the lock to use, must not be null - * @throws NullPointerException if multiset or lock is null - */ - protected SynchronizedMultiSet(final MultiSet multiset, final Object lock) { - super(multiset, lock); - } - - /** - * Gets the multiset being decorated. - * - * @return the decorated multiset - */ - @Override - protected MultiSet decorated() { - return (MultiSet) super.decorated(); - } - - @Override - public boolean equals(final Object object) { - if (object == this) { - return true; - } - synchronized (lock) { - return decorated().equals(object); - } - } - - @Override - public int hashCode() { - synchronized (lock) { - return decorated().hashCode(); - } - } - - - @Override - public int add(final E object, final int count) { - synchronized (lock) { - return decorated().add(object, count); - } - } - - @Override - public int remove(final Object object, final int count) { - synchronized (lock) { - return decorated().remove(object, count); - } - } - - @Override - public int getCount(final Object object) { - synchronized (lock) { - return decorated().getCount(object); - } - } - - @Override - public int setCount(final E object, final int count) { - synchronized (lock) { - return decorated().setCount(object, count); - } - } - - @Override - public Set uniqueSet() { - synchronized (lock) { - final Set set = decorated().uniqueSet(); - return new SynchronizedSet<>(set, lock); - } - } - - @Override - public Set> entrySet() { - synchronized (lock) { - final Set> set = decorated().entrySet(); - return new SynchronizedSet<>(set, lock); - } - } - - /** - * Synchronized Set for the MultiSet class. - */ - static class SynchronizedSet extends SynchronizedCollection implements Set { - /** Serialization version */ - private static final long serialVersionUID = 20150629L; - - /** - * Constructor. - * @param set the set to decorate - * @param lock the lock to use, shared with the multiset - */ - SynchronizedSet(final Set set, final Object lock) { - super(set, lock); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multiset/UnmodifiableMultiSet.java b/src/main/java/repack/apache/commons/collections4/multiset/UnmodifiableMultiSet.java deleted file mode 100644 index c5c98bd72a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multiset/UnmodifiableMultiSet.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.multiset; - -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 java.util.function.Predicate; - -import repack.apache.commons.collections4.MultiSet; -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableIterator; -import repack.apache.commons.collections4.set.UnmodifiableSet; - -/** - * Decorates another {@link MultiSet} to ensure it can't be altered. - *

- * Attempts to modify it will result in an UnsupportedOperationException. - *

- * - * @param the type held in the multiset - * @since 4.1 - */ -public final class UnmodifiableMultiSet - extends AbstractMultiSetDecorator implements Unmodifiable { - - /** Serialization version */ - private static final long serialVersionUID = 20150611L; - - /** - * Factory method to create an unmodifiable multiset. - *

- * If the multiset passed in is already unmodifiable, it is returned. - * - * @param the type of the elements in the multiset - * @param multiset the multiset to decorate, may not be null - * @return an unmodifiable MultiSet - * @throws NullPointerException if multiset is null - */ - public static MultiSet unmodifiableMultiSet(final MultiSet multiset) { - if (multiset instanceof Unmodifiable) { - @SuppressWarnings("unchecked") // safe to upcast - final MultiSet tmpMultiSet = (MultiSet) multiset; - return tmpMultiSet; - } - return new UnmodifiableMultiSet<>(multiset); - } - - /** - * Constructor that wraps (not copies). - * - * @param multiset the multiset to decorate, may not be null - * @throws NullPointerException if multiset is null - */ - @SuppressWarnings("unchecked") // safe to upcast - private UnmodifiableMultiSet(final MultiSet multiset) { - super((MultiSet) multiset); - } - - /** - * Write the collection out using a custom routine. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the 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 error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @throws ClassCastException if deserialized 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - 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 int setCount(final E object, final int count) { - throw new UnsupportedOperationException(); - } - - @Override - public int add(final E object, final int count) { - throw new UnsupportedOperationException(); - } - - @Override - public int remove(final Object object, final int count) { - throw new UnsupportedOperationException(); - } - - @Override - public Set uniqueSet() { - final Set set = decorated().uniqueSet(); - return UnmodifiableSet.unmodifiableSet(set); - } - - @Override - public Set> entrySet() { - final Set> set = decorated().entrySet(); - return UnmodifiableSet.unmodifiableSet(set); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/multiset/package-info.java b/src/main/java/repack/apache/commons/collections4/multiset/package-info.java deleted file mode 100644 index 008338163e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/multiset/package-info.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 repack.apache.commons.collections4.MultiSet MultiSet} interface. - * A multiset stores an object and a count of the number of occurrences of the object. - *

- * The following implementations are provided in the package: - *

    - *
  • HashMultiSet - implementation that uses a HashMap to store the data - *
- *

- * The following decorators are provided in the package: - *

    - *
  • Predicated - ensures that only elements that are valid according to a predicate can be added - *
  • Synchronized - synchronizes method access for multithreaded environments - *
  • Unmodifiable - ensures the multiset cannot be altered - *
- * - */ -package repack.apache.commons.collections4.multiset; diff --git a/src/main/java/repack/apache/commons/collections4/overview.html b/src/main/java/repack/apache/commons/collections4/overview.html deleted file mode 100644 index d25f39bdd4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/overview.html +++ /dev/null @@ -1,112 +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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 {@code 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 behavior to various - collections and utilities. -
-

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

- - diff --git a/src/main/java/repack/apache/commons/collections4/package-info.java b/src/main/java/repack/apache/commons/collections4/package-info.java deleted file mode 100644 index 586e0d5a2e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/package-info.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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} - *
- * - */ -package repack.apache.commons.collections4; diff --git a/src/main/java/repack/apache/commons/collections4/properties/AbstractPropertiesFactory.java b/src/main/java/repack/apache/commons/collections4/properties/AbstractPropertiesFactory.java deleted file mode 100644 index 0b4cdf5e24..0000000000 --- a/src/main/java/repack/apache/commons/collections4/properties/AbstractPropertiesFactory.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package repack.apache.commons.collections4.properties; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.net.URI; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Objects; -import java.util.Properties; - -/** - * Subclasses create and load {@link Properties} and subclasses of {@link Properties} like {@link SortedProperties}. - * - * @param {@link Properties} or a subclass like {@link SortedProperties}. - * @see Properties - * @since 4.4 - */ -public abstract class AbstractPropertiesFactory { - - /** - * Enumerates property formats. - * - * @since 4.5 - */ - public enum PropertyFormat { - - /** Properties file format. */ - PROPERTIES, - - /** XML file format. */ - XML; - - static PropertyFormat toPropertyFormat(final String fileName) { - return Objects.requireNonNull(fileName, "fileName").endsWith(".xml") ? XML : PROPERTIES; - } - } - - /** - * Constructs an instance. - */ - protected AbstractPropertiesFactory() { - // no init. - } - - /** - * Subclasses override to provide customized properties instances. - * - * @return a new Properties instance. - */ - protected abstract T createProperties(); - - /** - * Creates and loads properties from the given file. - * - * @param classLoader the class loader to use to get the named resource. - * @param name the location of the properties file. - * @return a new properties object. - * @throws IOException Thrown if an error occurred reading the input stream. - * @throws IllegalArgumentException Thrown if the input contains a malformed Unicode escape sequence. - */ - public T load(final ClassLoader classLoader, final String name) throws IOException { - try (InputStream inputStream = classLoader.getResourceAsStream(name)) { - return load(inputStream, PropertyFormat.toPropertyFormat(name)); - } - } - - /** - * Creates and loads properties from the given file. - * - * @param file the location of the properties file. - * @return a new properties object. - * @throws IOException Thrown if an error occurred reading the input stream. - * @throws IllegalArgumentException Thrown if the input contains a malformed Unicode escape sequence. - * @throws FileNotFoundException Thrown if the file does not exist, is a directory, or cannot be opened for - * reading. - * @throws SecurityException Thrown if a security manager's {@code checkRead} method denies read access to - * the file. - */ - public T load(final File file) throws FileNotFoundException, IOException { - try (FileInputStream inputStream = new FileInputStream(file)) { - return load(inputStream, PropertyFormat.toPropertyFormat(file.getName())); - } - } - - /** - * Creates and loads properties from the given input stream. - * - * @param inputStream the location of the properties file. - * @return a new properties object. - * @throws IOException Thrown if an error occurred reading the input stream. - * @throws IllegalArgumentException Thrown if the input contains a malformed Unicode escape sequence. - */ - public T load(final InputStream inputStream) throws IOException { - if (inputStream == null) { - return null; - } - final T properties = createProperties(); - properties.load(inputStream); - return properties; - } - - /** - * Creates and loads properties from the given input stream. - * - * @param inputStream the location of the properties file. - * @param propertyFormat The format of the given file. - * @return a new properties object. - * @throws IOException Thrown if an error occurred reading the input stream. - * @throws IllegalArgumentException Thrown if the input contains a malformed Unicode escape sequence. - * @since 4.5 - */ - public T load(final InputStream inputStream, final PropertyFormat propertyFormat) throws IOException { - if (inputStream == null) { - return null; - } - final T properties = createProperties(); - if (propertyFormat == PropertyFormat.XML) { - properties.loadFromXML(inputStream); - } else { - properties.load(inputStream); - } - return properties; - } - - /** - * Creates and loads properties from the given path. - * - * @param path the location of the properties file. - * @return a new properties object. - * @throws IOException Thrown if an error occurred reading the input stream. - * @throws IllegalArgumentException Thrown if the input contains a malformed Unicode escape sequence. - */ - public T load(final Path path) throws IOException { - try (InputStream inputStream = Files.newInputStream(path)) { - return load(inputStream, PropertyFormat.toPropertyFormat(Objects.toString(path.getFileName(), null))); - } - } - - /** - * Creates and loads properties from the given reader. - * - * @param reader the location of the properties file. - * @return a new properties object. - * @throws IOException Thrown if an error occurred reading the input stream. - * @throws IllegalArgumentException Thrown if the input contains a malformed Unicode escape sequence. - */ - public T load(final Reader reader) throws IOException { - final T properties = createProperties(); - properties.load(reader); - return properties; - } - - /** - * Creates and loads properties from the given file name. - * - * @param name the location of the properties file. - * @return a new properties object. - * @throws IOException Thrown if an error occurred reading the input stream. - * @throws IllegalArgumentException Thrown if the input contains a malformed Unicode escape sequence. - */ - public T load(final String name) throws IOException { - try (FileInputStream inputStream = new FileInputStream(name)) { - return load(inputStream, PropertyFormat.toPropertyFormat(name)); - } - } - - /** - * Creates and loads properties from the given URI. - * - * @param uri the location of the properties file. - * @return a new properties object. - * @throws IOException Thrown if an error occurred reading the input stream. - * @throws IllegalArgumentException Thrown if the input contains a malformed Unicode escape sequence. - */ - public T load(final URI uri) throws IOException { - return load(Paths.get(uri)); - } - - /** - * Creates and loads properties from the given URL. - * - * @param url the location of the properties file. - * @return a new properties object. - * @throws IOException Thrown if an error occurred reading the input stream. - * @throws IllegalArgumentException Thrown if the input contains a malformed Unicode escape sequence. - */ - public T load(final URL url) throws IOException { - try (InputStream inputStream = url.openStream()) { - return load(inputStream, PropertyFormat.toPropertyFormat(url.getFile())); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/properties/PropertiesFactory.java b/src/main/java/repack/apache/commons/collections4/properties/PropertiesFactory.java deleted file mode 100644 index 317cc09c83..0000000000 --- a/src/main/java/repack/apache/commons/collections4/properties/PropertiesFactory.java +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package repack.apache.commons.collections4.properties; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.InvalidPropertiesFormatException; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Properties; -import java.util.Set; -import java.util.function.BiConsumer; -import java.util.function.BiFunction; -import java.util.function.Function; - -/** - * Creates and loads {@link Properties}. - * - * @see Properties - * @since 4.4 - */ -public class PropertiesFactory extends AbstractPropertiesFactory { - - private static class EmptyProperties extends Properties { - - private static final long serialVersionUID = 1L; - - @Override - public synchronized void clear() { - // Noop - } - - @Override - public synchronized Object compute(final Object key, - final BiFunction remappingFunction) { - Objects.requireNonNull(key); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized Object computeIfAbsent(final Object key, - final Function mappingFunction) { - Objects.requireNonNull(key); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized Object computeIfPresent(final Object key, - final BiFunction remappingFunction) { - Objects.requireNonNull(key); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized boolean contains(final Object value) { - return false; - } - - @Override - public synchronized boolean containsKey(final Object key) { - return false; - } - - @Override - public boolean containsValue(final Object value) { - return false; - } - - @Override - public synchronized Enumeration elements() { - return Collections.emptyEnumeration(); - } - - @Override - public Set> entrySet() { - return Collections.emptySet(); - } - - @Override - public synchronized boolean equals(final Object o) { - return o instanceof Properties && ((Properties) o).isEmpty(); - } - - @Override - public synchronized void forEach(final BiConsumer action) { - Objects.requireNonNull(action); - } - - @Override - public synchronized Object get(final Object key) { - return null; - } - - @Override - public synchronized Object getOrDefault(final Object key, final Object defaultValue) { - return defaultValue; - } - - @Override - public String getProperty(final String key) { - return null; - } - - @Override - public String getProperty(final String key, final String defaultValue) { - return defaultValue; - } - - @Override - public synchronized int hashCode() { - return 0; - } - - @Override - public synchronized boolean isEmpty() { - return true; - } - - @Override - public synchronized Enumeration keys() { - return Collections.emptyEnumeration(); - } - - @Override - public Set keySet() { - return Collections.emptySet(); - } - - /** - * Throws {@link UnsupportedOperationException}. - * Caller should use try-with-resources statement. - */ - @SuppressWarnings("resource") - @Override - public synchronized void load(final InputStream inStream) throws IOException { - Objects.requireNonNull(inStream); - throw new UnsupportedOperationException(); - } - - /** - * Throws {@link UnsupportedOperationException}. - * Caller should use try-with-resources statement. - */ - @SuppressWarnings("resource") - @Override - public synchronized void load(final Reader reader) throws IOException { - Objects.requireNonNull(reader); - throw new UnsupportedOperationException(); - } - - /** - * Throws {@link UnsupportedOperationException}. - * Caller should use try-with-resources statement. - */ - @SuppressWarnings("resource") - @Override - public synchronized void loadFromXML(final InputStream in) - throws IOException, InvalidPropertiesFormatException { - Objects.requireNonNull(in); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized Object merge(final Object key, final Object value, - final BiFunction remappingFunction) { - Objects.requireNonNull(key); - Objects.requireNonNull(value); - throw new UnsupportedOperationException(); - } - - @Override - public Enumeration propertyNames() { - return Collections.emptyEnumeration(); - } - - @Override - public synchronized Object put(final Object key, final Object value) { - Objects.requireNonNull(key); - Objects.requireNonNull(value); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized void putAll(final Map t) { - Objects.requireNonNull(t); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized Object putIfAbsent(final Object key, final Object value) { - Objects.requireNonNull(key); - Objects.requireNonNull(value); - throw new UnsupportedOperationException(); - } - - @Override - protected void rehash() { - // Noop - } - - @Override - public synchronized Object remove(final Object key) { - Objects.requireNonNull(key); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized boolean remove(final Object key, final Object value) { - Objects.requireNonNull(key); - Objects.requireNonNull(value); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized Object replace(final Object key, final Object value) { - Objects.requireNonNull(key); - Objects.requireNonNull(value); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized boolean replace(final Object key, final Object oldValue, final Object newValue) { - Objects.requireNonNull(key); - Objects.requireNonNull(oldValue); - Objects.requireNonNull(newValue); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized void replaceAll( - final BiFunction function) { - Objects.requireNonNull(function); - throw new UnsupportedOperationException(); - } - - @SuppressWarnings("deprecation") - @Override - public void save(final OutputStream out, final String comments) { - // Implement as super - super.save(out, comments); - } - - @Override - public synchronized Object setProperty(final String key, final String value) { - Objects.requireNonNull(key); - Objects.requireNonNull(value); - throw new UnsupportedOperationException(); - } - - @Override - public synchronized int size() { - return 0; - } - - @Override - public void store(final OutputStream out, final String comments) throws IOException { - // Implement as super - super.store(out, comments); - } - - @Override - public void store(final Writer writer, final String comments) throws IOException { - // Implement as super - super.store(writer, comments); - } - - @Override - public void storeToXML(final OutputStream os, final String comment) throws IOException { - // Implement as super - super.storeToXML(os, comment); - } - - @Override - public void storeToXML(final OutputStream os, final String comment, final String encoding) throws IOException { - // Implement as super - super.storeToXML(os, comment, encoding); - } - - @Override - public Set stringPropertyNames() { - return Collections.emptySet(); - } - - @Override - public synchronized String toString() { - // Implement as super - return super.toString(); - } - - @Override - public Collection values() { - return Collections.emptyList(); - } - - } - - /** - * The empty map (immutable). This map is serializable. - * - * @since 4.5 - */ - public static final Properties EMPTY_PROPERTIES = new EmptyProperties(); - - /** - * The singleton instance. - */ - public static final PropertiesFactory INSTANCE = new PropertiesFactory(); - - /** - * Constructs an instance. - */ - private PropertiesFactory() { - // There is only one instance. - } - - /** - * Subclasses override to provide customized properties instances. - * - * @return a new Properties instance. - */ - @Override - protected Properties createProperties() { - return new Properties(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/properties/SortedProperties.java b/src/main/java/repack/apache/commons/collections4/properties/SortedProperties.java deleted file mode 100644 index fe778bf4fc..0000000000 --- a/src/main/java/repack/apache/commons/collections4/properties/SortedProperties.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package repack.apache.commons.collections4.properties; - -import java.util.AbstractMap; -import java.util.AbstractMap.SimpleEntry; -import java.util.Enumeration; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import repack.apache.commons.collections4.iterators.IteratorEnumeration; - -/** - * A drop-in replacement for {@link Properties} for sorting keys. - *

- * Overrides {@link Properties#keys()} to sort keys. Allows other methods on the superclass to work with sorted keys. - *

- * - * @since 4.2 - */ -public class SortedProperties extends Properties { - - private static final long serialVersionUID = 1L; - - @Override - public Set> entrySet() { - final Stream> stream = sortedKeys().map(k -> new AbstractMap.SimpleEntry<>(k, getProperty(k))); - return stream.collect(Collectors.toCollection(LinkedHashSet::new)); - } - - @Override - public synchronized Enumeration keys() { - return new IteratorEnumeration<>(sortedKeys().collect(Collectors.toList()).iterator()); - } - - private Stream sortedKeys() { - return keySet().stream().map(Object::toString).sorted(); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/properties/SortedPropertiesFactory.java b/src/main/java/repack/apache/commons/collections4/properties/SortedPropertiesFactory.java deleted file mode 100644 index 004d31ae0b..0000000000 --- a/src/main/java/repack/apache/commons/collections4/properties/SortedPropertiesFactory.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package repack.apache.commons.collections4.properties; - -/** - * Creates and loads {@link SortedProperties}. - * - * @see SortedProperties - * @since 4.4 - */ -public class SortedPropertiesFactory extends AbstractPropertiesFactory { - - /** - * The singleton instance. - */ - public static final SortedPropertiesFactory INSTANCE = new SortedPropertiesFactory(); - - /** - * Constructs an instance. - */ - private SortedPropertiesFactory() { - // There is only one instance. - } - - /** - * Subclasses override to provide customized properties instances. - * - * @return a new Properties instance. - */ - @Override - protected SortedProperties createProperties() { - return new SortedProperties(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/properties/package-info.java b/src/main/java/repack/apache/commons/collections4/properties/package-info.java deleted file mode 100644 index a364e1aaf8..0000000000 --- a/src/main/java/repack/apache/commons/collections4/properties/package-info.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 classes to extend or customize the behavior of - * {@link java.util.Properties Properties}. - *

- * The following classes are provided in the package: - *

    - *
  • SortedProperties- A drop-in replacement for Properties for sorting keys.
  • - *
- */ -package repack.apache.commons.collections4.properties; diff --git a/src/main/java/repack/apache/commons/collections4/queue/AbstractQueueDecorator.java b/src/main/java/repack/apache/commons/collections4/queue/AbstractQueueDecorator.java deleted file mode 100644 index b0d3326305..0000000000 --- a/src/main/java/repack/apache/commons/collections4/queue/AbstractQueueDecorator.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.queue; - -import java.util.Queue; - -import repack.apache.commons.collections4.collection.AbstractCollectionDecorator; - -/** - * Decorates another {@link Queue} to provide additional behavior. - *

- * Methods are forwarded directly to the decorated queue. - *

- *

- * This implementation does not forward the hashCode and equals methods through - * to the backing object, but relies on Object's implementation. This is - * necessary as some Queue implementations, e.g. LinkedList, have custom a - * equals implementation for which symmetry can not be preserved. - * See class javadoc of AbstractCollectionDecorator for more information. - *

- * - * @param the type of the elements in the queue - * @since 4.0 - */ -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() { - } - - /** - * Constructor that wraps (not copies). - * - * @param queue the queue to decorate, must not be null - * @throws NullPointerException if queue 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(); - } - - - @Override - public boolean offer(final E obj) { - return decorated().offer(obj); - } - - @Override - public E poll() { - return decorated().poll(); - } - - @Override - public E peek() { - return decorated().peek(); - } - - @Override - public E element() { - return decorated().element(); - } - - @Override - public E remove() { - return decorated().remove(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/queue/CircularFifoQueue.java b/src/main/java/repack/apache/commons/collections4/queue/CircularFifoQueue.java deleted file mode 100644 index 72a15cfbd0..0000000000 --- a/src/main/java/repack/apache/commons/collections4/queue/CircularFifoQueue.java +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.Objects; -import java.util.Queue; - -import repack.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. - *

- * - * @param the type of elements in this collection - * @since 4.0 - */ -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; - - /** - * 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; - - /** Flag to indicate if the queue is currently full. */ - private transient boolean full; - - /** 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} - */ - @Override - public boolean isFull() { - return false; - } - - /** - * Returns {@code true} if the capacity limit of this queue has been reached, - * i.e. the number of elements stored in the queue equals its maximum size. - * - * @return {@code true} if the capacity limit has been reached, {@code false} otherwise - * @since 4.1 - */ - public boolean isAtFullCapacity() { - return size() == maxElements; - } - - /** - * Gets the maximum size of the collection (the bound). - * - * @return the maximum number of elements the collection can hold - */ - @Override - 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) { - Objects.requireNonNull(element, "element"); - - 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 - */ - @Override - public boolean offer(final E element) { - return add(element); - } - - @Override - public E poll() { - if (isEmpty()) { - return null; - } - return remove(); - } - - @Override - public E element() { - if (isEmpty()) { - throw new NoSuchElementException("queue is empty"); - } - return peek(); - } - - @Override - public E peek() { - if (isEmpty()) { - return null; - } - return elements[start]; - } - - @Override - 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; - - @Override - public boolean hasNext() { - return isFirst || index != end; - } - - @Override - public E next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - isFirst = false; - lastReturnedIndex = index; - index = increment(index); - return elements[lastReturnedIndex]; - } - - @Override - 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); - } - - }; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/queue/PredicatedQueue.java b/src/main/java/repack/apache/commons/collections4/queue/PredicatedQueue.java deleted file mode 100644 index 2bf89eaf5f..0000000000 --- a/src/main/java/repack/apache/commons/collections4/queue/PredicatedQueue.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.queue; - -import java.util.Queue; - -import repack.apache.commons.collections4.Predicate; -import repack.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);
- * - * @param the type of elements held in this queue - * @since 4.0 - */ -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 NullPointerException 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 NullPointerException 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 - */ - @Override - public boolean offer(final E object) { - validate(object); - return decorated().offer(object); - } - - @Override - public E poll() { - return decorated().poll(); - } - - @Override - public E peek() { - return decorated().peek(); - } - - @Override - public E element() { - return decorated().element(); - } - - @Override - public E remove() { - return decorated().remove(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/queue/SynchronizedQueue.java b/src/main/java/repack/apache/commons/collections4/queue/SynchronizedQueue.java deleted file mode 100644 index 21351b1481..0000000000 --- a/src/main/java/repack/apache/commons/collections4/queue/SynchronizedQueue.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.queue; - -import java.util.Queue; - -import repack.apache.commons.collections4.collection.SynchronizedCollection; - -/** - * Decorates another {@link Queue} to synchronize its behavior for a multithreaded environment. - *

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

- * - * @param the type of the elements in the collection - * @since 4.2 - */ -public class SynchronizedQueue extends SynchronizedCollection implements Queue { - - /** Serialization version */ - private static final long serialVersionUID = 1L; - - /** - * Factory method to create a synchronized queue. - * - * @param - * the type of the elements in the queue - * @param queue - * the queue to decorate, must not be null - * @return a new synchronized Queue - * @throws NullPointerException - * if queue is null - */ - public static SynchronizedQueue synchronizedQueue(final Queue queue) { - return new SynchronizedQueue<>(queue); - } - - /** - * Constructor that wraps (not copies). - * - * @param queue - * the queue to decorate, must not be null - * @throws NullPointerException - * if queue is null - */ - protected SynchronizedQueue(final Queue queue) { - super(queue); - } - - /** - * Constructor that wraps (not copies). - * - * @param queue - * the queue to decorate, must not be null - * @param lock - * the lock to use, must not be null - * @throws NullPointerException - * if queue or lock is null - */ - protected SynchronizedQueue(final Queue queue, final Object lock) { - super(queue, lock); - } - - /** - * Gets the queue being decorated. - * - * @return the decorated queue - */ - @Override - protected Queue decorated() { - return (Queue) super.decorated(); - } - - @Override - public E element() { - synchronized (lock) { - return decorated().element(); - } - } - - @Override - public boolean equals(final Object object) { - if (object == this) { - return true; - } - synchronized (lock) { - return decorated().equals(object); - } - } - - @Override - public int hashCode() { - synchronized (lock) { - return decorated().hashCode(); - } - } - - @Override - public boolean offer(final E e) { - synchronized (lock) { - return decorated().offer(e); - } - } - - @Override - public E peek() { - synchronized (lock) { - return decorated().peek(); - } - } - - @Override - public E poll() { - synchronized (lock) { - return decorated().poll(); - } - } - - @Override - public E remove() { - synchronized (lock) { - return decorated().remove(); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/queue/TransformedQueue.java b/src/main/java/repack/apache/commons/collections4/queue/TransformedQueue.java deleted file mode 100644 index 086efd1489..0000000000 --- a/src/main/java/repack/apache/commons/collections4/queue/TransformedQueue.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.queue; - -import java.util.Queue; - -import repack.apache.commons.collections4.Transformer; -import repack.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. - *

- * - * @param the type of elements held in this queue - * @since 4.0 - */ -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 NullPointerException 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 NullPointerException 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.isEmpty()) { - @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 NullPointerException 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(); - } - - - @Override - public boolean offer(final E obj) { - return getQueue().offer(transform(obj)); - } - - @Override - public E poll() { - return getQueue().poll(); - } - - @Override - public E peek() { - return getQueue().peek(); - } - - @Override - public E element() { - return getQueue().element(); - } - - @Override - public E remove() { - return getQueue().remove(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/queue/UnmodifiableQueue.java b/src/main/java/repack/apache/commons/collections4/queue/UnmodifiableQueue.java deleted file mode 100644 index ac5a8ef715..0000000000 --- a/src/main/java/repack/apache/commons/collections4/queue/UnmodifiableQueue.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.function.Predicate; - -import repack.apache.commons.collections4.Unmodifiable; -import repack.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. - *

- * - * @param the type of elements held in this queue - * @since 4.0 - */ -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 NullPointerException 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 NullPointerException 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/queue/package-info.java b/src/main/java/repack/apache/commons/collections4/queue/package-info.java deleted file mode 100644 index 9a523dc624..0000000000 --- a/src/main/java/repack/apache/commons/collections4/queue/package-info.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 - *
- * - */ -package repack.apache.commons.collections4.queue; diff --git a/src/main/java/repack/apache/commons/collections4/sequence/CommandVisitor.java b/src/main/java/repack/apache/commons/collections4/sequence/CommandVisitor.java deleted file mode 100644 index ef86e896c2..0000000000 --- a/src/main/java/repack/apache/commons/collections4/sequence/CommandVisitor.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -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); - -} diff --git a/src/main/java/repack/apache/commons/collections4/sequence/DeleteCommand.java b/src/main/java/repack/apache/commons/collections4/sequence/DeleteCommand.java deleted file mode 100644 index a8e12e029b..0000000000 --- a/src/main/java/repack/apache/commons/collections4/sequence/DeleteCommand.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -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 {@code 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()); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/sequence/EditCommand.java b/src/main/java/repack/apache/commons/collections4/sequence/EditCommand.java deleted file mode 100644 index e6ba30797e..0000000000 --- a/src/main/java/repack/apache/commons/collections4/sequence/EditCommand.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 {@code equals} an object in the second sequence. It is - * guaranteed that comparison is always performed this way (i.e. the - * {@code 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 {@code equals} method is specialized. - *

- * - * @see SequencesComparator - * @see EditScript - * - * @since 4.0 - */ -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 command 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); - -} diff --git a/src/main/java/repack/apache/commons/collections4/sequence/EditScript.java b/src/main/java/repack/apache/commons/collections4/sequence/EditScript.java deleted file mode 100644 index b9694f41fa..0000000000 --- a/src/main/java/repack/apache/commons/collections4/sequence/EditScript.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 {@code equals} - * method is specialized. - *

- * - * @see SequencesComparator - * @see EditCommand - * @see CommandVisitor - * @see ReplacementsHandler - * - * @since 4.0 - */ -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; - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/sequence/InsertCommand.java b/src/main/java/repack/apache/commons/collections4/sequence/InsertCommand.java deleted file mode 100644 index 028f871aec..0000000000 --- a/src/main/java/repack/apache/commons/collections4/sequence/InsertCommand.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -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 {@code 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()); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/sequence/KeepCommand.java b/src/main/java/repack/apache/commons/collections4/sequence/KeepCommand.java deleted file mode 100644 index 22709a4abe..0000000000 --- a/src/main/java/repack/apache/commons/collections4/sequence/KeepCommand.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.sequence; - -/** - * Command representing the keeping of one object present in both sequences. - *

- * When one object of the first sequence {@code 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 - */ -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 {@code 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()); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/sequence/ReplacementsFinder.java b/src/main/java/repack/apache/commons/collections4/sequence/ReplacementsFinder.java deleted file mode 100644 index 14987c8860..0000000000 --- a/src/main/java/repack/apache/commons/collections4/sequence/ReplacementsFinder.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 - */ -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 - */ - @Override - 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 - */ - @Override - 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 - */ - @Override - public void visitDeleteCommand(final T object) { - pendingDeletions.add(object); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/sequence/ReplacementsHandler.java b/src/main/java/repack/apache/commons/collections4/sequence/ReplacementsHandler.java deleted file mode 100644 index 2c8471dc05..0000000000 --- a/src/main/java/repack/apache/commons/collections4/sequence/ReplacementsHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.sequence; - -import java.util.List; - -/** - * This interface is devoted to handle synchronized replacement sequences. - * - * @see ReplacementsFinder - * @since 4.0 - */ -@FunctionalInterface -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 {@code from} - * sub-sequence into the {@code 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); - -} diff --git a/src/main/java/repack/apache/commons/collections4/sequence/SequencesComparator.java b/src/main/java/repack/apache/commons/collections4/sequence/SequencesComparator.java deleted file mode 100644 index 38b3a15de4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/sequence/SequencesComparator.java +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.sequence; - -import java.util.List; - -import repack.apache.commons.collections4.Equator; -import repack.apache.commons.collections4.functors.DefaultEquator; - -/** - * This class allows to compare two objects sequences. - *

- * The two sequences can hold any object type, as only the {@code equals} - * method is used to compare the elements of the sequences. It is guaranteed - * that the comparisons will always be done as {@code o1.equals(o2)} where - * {@code o1} belongs to the first sequence and {@code o2} belongs to - * the second sequence. This can be important if subclassing is used for some - * elements in the first sequence and the {@code 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 {@code 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 - */ -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 - * {@code o1.equals(o2)} where {@code o1} belongs to the first - * sequence and {@code o2} belongs to the second sequence. This can be - * important if subclassing is used for some elements in the first sequence - * and the {@code 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 - * {@code Equator.equate(o1, o2)} where {@code o1} belongs to the first - * sequence and {@code 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 {@code 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 algorithm 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 && vUp[i-delta] <= vDown[i]) { // NOPMD - 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 && vUp[i] <= vDown[i + delta]) { // NOPMD - 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 - */ - 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; - } - } -} diff --git a/src/main/java/repack/apache/commons/collections4/sequence/package-info.java b/src/main/java/repack/apache/commons/collections4/sequence/package-info.java deleted file mode 100644 index e229982c7c..0000000000 --- a/src/main/java/repack/apache/commons/collections4/sequence/package-info.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 - * {@code equals} method is used to compare the elements of the - * sequences. It is guaranteed that the comparisons will always be done - * as {@code o1.equals(o2)} where {@code o1} belongs to the - * first sequence and {@code o2} belongs to the second - * sequence. This can be important if subclassing is used for some - * elements in the first sequence and the {@code 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 {@code 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 {@code (A, B)} is - * compared to {@code (B, A)}, the result will be either the - * sequence of three commands {@code delete A}, {@code keep B}, - * {@code insert A} or the sequence {@code insert B}, - * {@code keep A}, {@code 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 repack.apache.commons.collections4.sequence.EditScript edit script} containing - * all the {@link repack.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 repack.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 repack.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 - * {@code replacement} operations acting on complete subsequences of - * the original sequences, he will provide an object implementing the - * simple {@link repack.apache.commons.collections4.sequence.ReplacementsHandler} interface, - * using an instance of the {@link repack.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 repack.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. - * - */ -package repack.apache.commons.collections4.sequence; diff --git a/src/main/java/repack/apache/commons/collections4/set/AbstractNavigableSetDecorator.java b/src/main/java/repack/apache/commons/collections4/set/AbstractNavigableSetDecorator.java deleted file mode 100644 index 18e7d8a859..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/AbstractNavigableSetDecorator.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.Iterator; -import java.util.NavigableSet; - -/** - * Decorates another {@code NavigableSet} to provide additional behavior. - *

- * Methods are forwarded directly to the decorated set. - *

- * - * @param the type of the elements in the navigable set - * @since 4.1 - */ -public abstract class AbstractNavigableSetDecorator - extends AbstractSortedSetDecorator - implements NavigableSet { - - /** Serialization version */ - private static final long serialVersionUID = 20150528L; - - /** - * Constructor only used in deserialization, do not use otherwise. - */ - protected AbstractNavigableSetDecorator() { - } - - /** - * Constructor that wraps (not copies). - * - * @param set the set to decorate, must not be null - * @throws NullPointerException if set is null - */ - protected AbstractNavigableSetDecorator(final NavigableSet set) { - super(set); - } - - /** - * Gets the set being decorated. - * - * @return the decorated set - */ - @Override - protected NavigableSet decorated() { - return (NavigableSet) super.decorated(); - } - - - @Override - public E lower(final E e) { - return decorated().lower(e); - } - - @Override - public E floor(final E e) { - return decorated().floor(e); - } - - @Override - public E ceiling(final E e) { - return decorated().ceiling(e); - } - - @Override - public E higher(final E e) { - return decorated().higher(e); - } - - @Override - public E pollFirst() { - return decorated().pollFirst(); - } - - @Override - public E pollLast() { - return decorated().pollLast(); - } - - @Override - public NavigableSet descendingSet() { - return decorated().descendingSet(); - } - - @Override - public Iterator descendingIterator() { - return decorated().descendingIterator(); - } - - @Override - public NavigableSet subSet(final E fromElement, final boolean fromInclusive, final E toElement, - final boolean toInclusive) { - return decorated().subSet(fromElement, fromInclusive, toElement, toInclusive); - } - - @Override - public NavigableSet headSet(final E toElement, final boolean inclusive) { - return decorated().headSet(toElement, inclusive); - } - - @Override - public NavigableSet tailSet(final E fromElement, final boolean inclusive) { - return decorated().tailSet(fromElement, inclusive); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/AbstractSerializableSetDecorator.java b/src/main/java/repack/apache/commons/collections4/set/AbstractSerializableSetDecorator.java deleted file mode 100644 index ac159896ca..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/AbstractSerializableSetDecorator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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. - * - * @param the type of the elements in this set - * @since 3.1 - */ -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 NullPointerException 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 if an error occurs while writing to the stream - */ - 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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - */ - @SuppressWarnings("unchecked") - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - setCollection((Collection) in.readObject()); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/AbstractSetDecorator.java b/src/main/java/repack/apache/commons/collections4/set/AbstractSetDecorator.java deleted file mode 100644 index f22fe2a7bb..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/AbstractSetDecorator.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.Set; - -import repack.apache.commons.collections4.collection.AbstractCollectionDecorator; - -/** - * Decorates another {@code Set} to provide additional behavior. - *

- * Methods are forwarded directly to the decorated set. - *

- * - * @param the type of the elements in this set - * @since 3.0 - */ -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() { - } - - /** - * Constructor that wraps (not copies). - * - * @param set the set to decorate, must not be null - * @throws NullPointerException 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(); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/AbstractSortedSetDecorator.java b/src/main/java/repack/apache/commons/collections4/set/AbstractSortedSetDecorator.java deleted file mode 100644 index 18c5ea30ce..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/AbstractSortedSetDecorator.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.Comparator; -import java.util.Set; -import java.util.SortedSet; - -/** - * Decorates another {@code SortedSet} to provide additional behavior. - *

- * Methods are forwarded directly to the decorated set. - *

- * - * @param the type of the elements in the sorted set - * @since 3.0 - */ -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() { - } - - /** - * Constructor that wraps (not copies). - * - * @param set the set to decorate, must not be null - * @throws NullPointerException 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(); - } - - @Override - public SortedSet subSet(final E fromElement, final E toElement) { - return decorated().subSet(fromElement, toElement); - } - - @Override - public SortedSet headSet(final E toElement) { - return decorated().headSet(toElement); - } - - @Override - public SortedSet tailSet(final E fromElement) { - return decorated().tailSet(fromElement); - } - - @Override - public E first() { - return decorated().first(); - } - - @Override - public E last() { - return decorated().last(); - } - - @Override - public Comparator comparator() { - return decorated().comparator(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/CompositeSet.java b/src/main/java/repack/apache/commons/collections4/set/CompositeSet.java deleted file mode 100644 index 53a6570fa3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/CompositeSet.java +++ /dev/null @@ -1,529 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.Objects; -import java.util.Set; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.iterators.EmptyIterator; -import repack.apache.commons.collections4.iterators.IteratorChain; -import repack.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 repack.apache.commons.collections4.collection.CompositeCollection CompositeCollection} - * anymore due to its input restrictions (only accepts Sets). - * See COLLECTIONS-424 - * for more details. - *

- * - * @param the type of the elements in this set - * @since 3.0 - */ -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<>(); - - /** - * Creates an empty CompositeSet. - */ - public CompositeSet() { - } - - /** - * Creates a CompositeSet with just {@code set} composited. - * - * @param set the initial set in the composite - */ - public CompositeSet(final Set set) { - addComposited(set); - } - - /** - * Creates 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) { - addComposited(sets); - } - - /** - * Gets the size of this composite set. - *

- * This implementation calls {@code size()} on each set. - * - * @return total number of elements in all contained containers - */ - @Override - 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 {@code isEmpty()} on each set. - * - * @return true if all of the contained sets are empty - */ - @Override - public boolean isEmpty() { - for (final Set item : all) { - if (!item.isEmpty()) { - return false; - } - } - return true; - } - - /** - * Checks whether this composite set contains the object. - *

- * This implementation calls {@code contains()} on each set. - * - * @param obj the object to search for - * @return true if obj is contained in any of the contained sets - */ - @Override - 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 {@code IteratorChain}. - * - * @return an {@code IteratorChain} instance which supports - * {@code remove()}. Iteration occurs over contained collections in - * the order they were added, but this behavior should not be relied upon. - * @see IteratorChain - */ - @Override - public Iterator iterator() { - if (all.isEmpty()) { - return EmptyIterator.emptyIterator(); - } - final IteratorChain chain = new IteratorChain<>(); - all.forEach(item -> 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 - */ - @Override - 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 {@code 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 - */ - @Override - @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 - */ - @Override - 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 {@code 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 - */ - @Override - 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 {@code contains()} for each element in the - * specified collection. - * - * @param coll the collection to check for - * @return true if all elements contained - */ - @Override - public boolean containsAll(final Collection coll) { - if (coll == null) { - return false; - } - for (final Object item : coll) { - if (!contains(item)) { - 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 - */ - @Override - 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); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - if (Objects.isNull(filter)) { - return false; - } - boolean changed = false; - for (final Collection item : all) { - changed |= item.removeIf(filter); - } - return changed; - } - - /** - * Removes the elements in the specified collection from this composite set. - *

- * This implementation calls {@code removeAll} on each collection. - * - * @param coll the collection to remove - * @return true if the composite was modified - * @throws UnsupportedOperationException if removeAll is unsupported - */ - @Override - public boolean removeAll(final Collection coll) { - if (CollectionUtils.isEmpty(coll)) { - 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 {@code retainAll()} on each collection. - * - * @param coll the collection to remove - * @return true if the composite was modified - * @throws UnsupportedOperationException if retainAll is unsupported - */ - @Override - 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 {@code clear()} on each set. - * - * @throws UnsupportedOperationException if clear is unsupported - */ - @Override - 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; - } - - /** - * Adds 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) { - if (set != null) { - for (final Set existingSet : getSets()) { - final Collection intersects = CollectionUtils.intersection(existingSet, set); - if (!intersects.isEmpty()) { - 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).isEmpty()) { - throw new IllegalArgumentException( - "Attempt to add illegal entry unresolved by SetMutator.resolveCollision()"); - } - } - } - all.add(set); - } - } - - /** - * Adds 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); - } - - /** - * Adds 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) { - if (sets != null) { - for (final 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); - } - - /** - * Gets 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; - } - - /** - * Defines callbacks for mutation operations. - */ - public 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 {@code added} and {@code 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); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/set/ListOrderedSet.java b/src/main/java/repack/apache/commons/collections4/set/ListOrderedSet.java deleted file mode 100644 index f34e8044b0..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/ListOrderedSet.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Objects; -import java.util.Set; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.CollectionUtils; -import repack.apache.commons.collections4.OrderedIterator; -import repack.apache.commons.collections4.functors.UniquePredicate; -import repack.apache.commons.collections4.iterators.AbstractIteratorDecorator; -import repack.apache.commons.collections4.list.UnmodifiableList; - -/** - * Decorates another {@code 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 {@code List}, such as {@code get(int)}, - * {@code remove(int)} and {@code indexOf(int)}. An unmodifiable - * {@code List} view of the set can be obtained via {@code asList()}. - *

- *

- * This class cannot implement the {@code List} interface directly as - * various interface methods (notably equals/hashCode) are incompatible with a - * set. - *

- *

- * This class is Serializable from Commons Collections 3.1. - *

- * - * @param the type of the elements in this set - * @since 3.0 - */ -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 NullPointerException 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) { - Objects.requireNonNull(set, "set"); - Objects.requireNonNull(list, "list"); - if (!set.isEmpty() || !list.isEmpty()) { - throw new IllegalArgumentException("Set and List must be empty"); - } - return new ListOrderedSet<>(set, list); - } - - /** - * Factory method to create an ordered set. - *

- * An {@code 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 NullPointerException 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 {@code HashSet} is used for the set behavior. - *

- * 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 NullPointerException if list is null - * @since 4.0 - */ - public static ListOrderedSet listOrderedSet(final List list) { - Objects.requireNonNull(list, "list"); - CollectionUtils.filter(list, UniquePredicate.uniquePredicate()); - final Set set = new HashSet<>(list); - - return new ListOrderedSet<>(set, list); - } - - /** - * Constructs a new empty {@code ListOrderedSet} using a - * {@code HashSet} and an {@code 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 NullPointerException 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 initialized 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 NullPointerException if set or list is null - */ - protected ListOrderedSet(final Set set, final List list) { - super(set); - setOrder = Objects.requireNonNull(list, "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; - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - if (Objects.isNull(filter)) { - return false; - } - final boolean result = decorated().removeIf(filter); - if (result) { - setOrder.removeIf(filter); - } - return result; - } - - @Override - public boolean removeAll(final Collection coll) { - boolean result = false; - for (final Object name : coll) { - result |= remove(name); - } - return result; - } - - /** - * {@inheritDoc} - *

- * This implementation iterates over the elements of this set, checking - * each element in turn to see if it's contained in {@code coll}. - * If it's not contained, it's removed from this set. As a consequence, - * it is advised to use a collection type for {@code coll} that provides - * a fast (e.g. O(1)) implementation of {@link Collection#contains(Object)}. - */ - @Override - public boolean retainAll(final Collection coll) { - final boolean result = decorated().retainAll(coll); - if (!result) { - return false; - } - if (decorated().isEmpty()) { - setOrder.clear(); - } else { - setOrder.removeIf(e -> !decorated().contains(e)); - } - return result; - } - - @Override - public Object[] toArray() { - return setOrder.toArray(); - } - - @Override - public T[] toArray(final T a[]) { - return setOrder.toArray(a); - } - - /** - * 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 E remove(final int index) { - final E obj = setOrder.remove(index); - remove(obj); - return obj; - } - - /** - * Uses the underlying List's toString so that order is achieved. This means - * that the decorated Set's toString is not used, so any custom toStrings - * will be ignored. - * - * @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; - } - - @Override - public boolean hasPrevious() { - return ((ListIterator) getIterator()).hasPrevious(); - } - - @Override - public E previous() { - last = ((ListIterator) getIterator()).previous(); - return last; - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/MapBackedSet.java b/src/main/java/repack/apache/commons/collections4/set/MapBackedSet.java deleted file mode 100644 index 96b5d4a52d..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/MapBackedSet.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.io.Serializable; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.function.Predicate; - -/** - * Decorates a {@code Map} to obtain {@code Set} behavior. - *

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

- *

- * Most map implementation can be used to create a set by passing in dummy values. - * Exceptions include {@code BidiMap} implementations, as they require unique values. - *

- * - * @param the type of the elements in this set - * @param the dummy value type in this map - * @since 3.1 - */ -public final class MapBackedSet implements Set, Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 6723912213766056587L; - - /** The map being used as the backing store */ - 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 NullPointerException if map 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 NullPointerException if map is null - * @since 4.0 - */ - public static MapBackedSet mapBackedSet(final Map map, final V dummyValue) { - 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 NullPointerException if map is null - */ - private MapBackedSet(final Map map, final V dummyValue) { - this.map = Objects.requireNonNull(map, "map"); - this.dummyValue = dummyValue; - } - - @Override - public int size() { - return map.size(); - } - - @Override - public boolean isEmpty() { - return map.isEmpty(); - } - - @Override - public Iterator iterator() { - return map.keySet().iterator(); - } - - @Override - public boolean contains(final Object obj) { - return map.containsKey(obj); - } - - @Override - public boolean containsAll(final Collection coll) { - return map.keySet().containsAll(coll); - } - - @Override - public boolean add(final E obj) { - final int size = map.size(); - map.put(obj, dummyValue); - return map.size() != size; - } - - @Override - public boolean addAll(final Collection coll) { - final int size = map.size(); - for (final E e : coll) { - map.put(e, dummyValue); - } - return map.size() != size; - } - - @Override - public boolean remove(final Object obj) { - final int size = map.size(); - map.remove(obj); - return map.size() != size; - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - return map.keySet().removeIf(filter); - } - - @Override - public boolean removeAll(final Collection coll) { - return map.keySet().removeAll(coll); - } - - @Override - public boolean retainAll(final Collection coll) { - return map.keySet().retainAll(coll); - } - - @Override - public void clear() { - map.clear(); - } - - @Override - public Object[] toArray() { - return map.keySet().toArray(); - } - - @Override - 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/PredicatedNavigableSet.java b/src/main/java/repack/apache/commons/collections4/set/PredicatedNavigableSet.java deleted file mode 100644 index 8d05f62122..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/PredicatedNavigableSet.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.Iterator; -import java.util.NavigableSet; - -import repack.apache.commons.collections4.Predicate; - -/** - * Decorates another {@code NavigableSet} 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. - *

- *
- * NavigableSet set =
- *   PredicatedSortedSet.predicatedNavigableSet(new TreeSet(),
- *                                              NotNullPredicate.notNullPredicate());
- * 
- * - * @param the type of the elements in this set - * @since 4.1 - */ -public class PredicatedNavigableSet extends PredicatedSortedSet implements NavigableSet { - - /** Serialization version */ - private static final long serialVersionUID = 20150528L; - - /** - * Factory method to create a predicated (validating) navigable 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 navigable set. - * @throws NullPointerException if set or predicate is null - * @throws IllegalArgumentException if the set contains invalid elements - * @since 4.0 - */ - public static PredicatedNavigableSet predicatedNavigableSet(final NavigableSet set, - final Predicate predicate) { - return new PredicatedNavigableSet<>(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 NullPointerException if set or predicate is null - * @throws IllegalArgumentException if the set contains invalid elements - */ - protected PredicatedNavigableSet(final NavigableSet set, final Predicate predicate) { - super(set, predicate); - } - - /** - * Gets the navigable set being decorated. - * - * @return the decorated navigable set - */ - @Override - protected NavigableSet decorated() { - return (NavigableSet) super.decorated(); - } - - - @Override - public E lower(final E e) { - return decorated().lower(e); - } - - @Override - public E floor(final E e) { - return decorated().floor(e); - } - - @Override - public E ceiling(final E e) { - return decorated().ceiling(e); - } - - @Override - public E higher(final E e) { - return decorated().higher(e); - } - - @Override - public E pollFirst() { - return decorated().pollFirst(); - } - - @Override - public E pollLast() { - return decorated().pollLast(); - } - - @Override - public NavigableSet descendingSet() { - return predicatedNavigableSet(decorated().descendingSet(), predicate); - } - - @Override - public Iterator descendingIterator() { - return decorated().descendingIterator(); - } - - @Override - public NavigableSet subSet(final E fromElement, final boolean fromInclusive, final E toElement, - final boolean toInclusive) { - final NavigableSet sub = decorated().subSet(fromElement, fromInclusive, toElement, toInclusive); - return predicatedNavigableSet(sub, predicate); - } - - @Override - public NavigableSet headSet(final E toElement, final boolean inclusive) { - final NavigableSet head = decorated().headSet(toElement, inclusive); - return predicatedNavigableSet(head, predicate); - } - - @Override - public NavigableSet tailSet(final E fromElement, final boolean inclusive) { - final NavigableSet tail = decorated().tailSet(fromElement, inclusive); - return predicatedNavigableSet(tail, predicate); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/PredicatedSet.java b/src/main/java/repack/apache/commons/collections4/set/PredicatedSet.java deleted file mode 100644 index f8e14b19c3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/PredicatedSet.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.Set; - -import repack.apache.commons.collections4.Predicate; -import repack.apache.commons.collections4.collection.PredicatedCollection; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the elements in this set - * @since 3.0 - */ -public class PredicatedSet extends PredicatedCollection implements Set { - - /** Serialization version */ - private static final long serialVersionUID = -684521469108685117L; - - /** - * Factory method to create a predicated (validating) set. - *

- * If there are any elements already in the set being decorated, they - * are validated. - * - * @param 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 NullPointerException 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 NullPointerException 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(); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/PredicatedSortedSet.java b/src/main/java/repack/apache/commons/collections4/set/PredicatedSortedSet.java deleted file mode 100644 index 8cdb0192db..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/PredicatedSortedSet.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.Comparator; -import java.util.SortedSet; - -import repack.apache.commons.collections4.Predicate; - -/** - * Decorates another {@code 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.predicatedSortedSet(new TreeSet(),
- *                                           NotNullPredicate.notNullPredicate());
- * 
- *

- * This class is Serializable from Commons Collections 3.1. - *

- * - * @param the type of the elements in this set - * @since 3.0 - */ -public class PredicatedSortedSet extends PredicatedSet implements SortedSet { - - /** Serialization version */ - private static final long serialVersionUID = -9110948148132275052L; - - /** - * Factory method to create a predicated (validating) sorted set. - *

- * If there are any elements already in the set being decorated, they - * are validated. - * - * @param 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 NullPointerException 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 NullPointerException 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(); - } - - @Override - public Comparator comparator() { - return decorated().comparator(); - } - - @Override - public E first() { - return decorated().first(); - } - - @Override - public E last() { - return decorated().last(); - } - - @Override - public SortedSet subSet(final E fromElement, final E toElement) { - final SortedSet sub = decorated().subSet(fromElement, toElement); - return new PredicatedSortedSet<>(sub, predicate); - } - - @Override - public SortedSet headSet(final E toElement) { - final SortedSet head = decorated().headSet(toElement); - return new PredicatedSortedSet<>(head, predicate); - } - - @Override - public SortedSet tailSet(final E fromElement) { - final SortedSet tail = decorated().tailSet(fromElement); - return new PredicatedSortedSet<>(tail, predicate); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/TransformedNavigableSet.java b/src/main/java/repack/apache/commons/collections4/set/TransformedNavigableSet.java deleted file mode 100644 index 970af91327..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/TransformedNavigableSet.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.Iterator; -import java.util.NavigableSet; - -import repack.apache.commons.collections4.Transformer; - -/** - * Decorates another {@code NavigableSet} 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. - *

- * - * @param the type of the elements in this set - * @since 4.1 - */ -public class TransformedNavigableSet extends TransformedSortedSet implements NavigableSet { - - /** Serialization version */ - private static final long serialVersionUID = 20150528L; - - /** - * Factory method to create a transforming navigable set. - *

- * If there are any elements already in the set being decorated, they - * are NOT transformed. - * Contrast this with {@link #transformedNavigableSet(NavigableSet, 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 NavigableSet} - * @throws NullPointerException if set or transformer is null - */ - public static TransformedNavigableSet transformingNavigableSet(final NavigableSet set, - final Transformer transformer) { - return new TransformedNavigableSet<>(set, transformer); - } - - /** - * Factory method to create a transforming navigable set that will transform - * existing contents of the specified navigable set. - *

- * If there are any elements already in the set being decorated, they - * will be transformed by this method. - * Contrast this with {@link #transformingNavigableSet(NavigableSet, 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 NavigableSet} - * @throws NullPointerException if set or transformer is null - */ - public static TransformedNavigableSet transformedNavigableSet(final NavigableSet set, - final Transformer transformer) { - - final TransformedNavigableSet decorated = new TransformedNavigableSet<>(set, transformer); - if (!set.isEmpty()) { - @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 NullPointerException if set or transformer is null - */ - protected TransformedNavigableSet(final NavigableSet set, - final Transformer transformer) { - super(set, transformer); - } - - /** - * Gets the decorated navigable set. - * - * @return the decorated navigable set - */ - @Override - protected NavigableSet decorated() { - return (NavigableSet) super.decorated(); - } - - - @Override - public E lower(final E e) { - return decorated().lower(e); - } - - @Override - public E floor(final E e) { - return decorated().floor(e); - } - - @Override - public E ceiling(final E e) { - return decorated().ceiling(e); - } - - @Override - public E higher(final E e) { - return decorated().higher(e); - } - - @Override - public E pollFirst() { - return decorated().pollFirst(); - } - - @Override - public E pollLast() { - return decorated().pollLast(); - } - - @Override - public NavigableSet descendingSet() { - return transformingNavigableSet(decorated().descendingSet(), transformer); - } - - @Override - public Iterator descendingIterator() { - return decorated().descendingIterator(); - } - - @Override - public NavigableSet subSet(final E fromElement, final boolean fromInclusive, final E toElement, - final boolean toInclusive) { - final NavigableSet sub = decorated().subSet(fromElement, fromInclusive, toElement, toInclusive); - return transformingNavigableSet(sub, transformer); - } - - @Override - public NavigableSet headSet(final E toElement, final boolean inclusive) { - final NavigableSet head = decorated().headSet(toElement, inclusive); - return transformingNavigableSet(head, transformer); - } - - @Override - public NavigableSet tailSet(final E fromElement, final boolean inclusive) { - final NavigableSet tail = decorated().tailSet(fromElement, inclusive); - return transformingNavigableSet(tail, transformer); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/TransformedSet.java b/src/main/java/repack/apache/commons/collections4/set/TransformedSet.java deleted file mode 100644 index 8c4b9e5192..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/TransformedSet.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.Set; - -import repack.apache.commons.collections4.Transformer; -import repack.apache.commons.collections4.collection.TransformedCollection; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the elements in this set - * @since 3.0 - */ -public class TransformedSet extends TransformedCollection implements Set { - - /** Serialization version */ - private static final long serialVersionUID = 306127383500410386L; - - /** - * Factory method to create a transforming set. - *

- * If there are any elements already in the set being decorated, they - * are NOT transformed. - * 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 NullPointerException 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 NullPointerException 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 (!set.isEmpty()) { - @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 NullPointerException if set or transformer is null - */ - protected TransformedSet(final Set set, final Transformer transformer) { - super(set, transformer); - } - - @Override - public boolean equals(final Object object) { - return object == this || decorated().equals(object); - } - - @Override - public int hashCode() { - return decorated().hashCode(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/TransformedSortedSet.java b/src/main/java/repack/apache/commons/collections4/set/TransformedSortedSet.java deleted file mode 100644 index 9da3eedca4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/TransformedSortedSet.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.Comparator; -import java.util.SortedSet; - -import repack.apache.commons.collections4.Transformer; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the elements in this set - * @since 3.0 - */ -public class TransformedSortedSet extends TransformedSet implements SortedSet { - - /** Serialization version */ - private static final long serialVersionUID = -1675486811351124386L; - - /** - * Factory method to create a transforming sorted set. - *

- * If there are any elements already in the set being decorated, they - * are NOT transformed. - * 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 NullPointerException 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 NullPointerException 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 (!set.isEmpty()) { - @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 NullPointerException 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(); - } - - @Override - public E first() { - return getSortedSet().first(); - } - - @Override - public E last() { - return getSortedSet().last(); - } - - @Override - public Comparator comparator() { - return getSortedSet().comparator(); - } - - @Override - public SortedSet subSet(final E fromElement, final E toElement) { - final SortedSet set = getSortedSet().subSet(fromElement, toElement); - return new TransformedSortedSet<>(set, transformer); - } - - @Override - public SortedSet headSet(final E toElement) { - final SortedSet set = getSortedSet().headSet(toElement); - return new TransformedSortedSet<>(set, transformer); - } - - @Override - public SortedSet tailSet(final E fromElement) { - final SortedSet set = getSortedSet().tailSet(fromElement); - return new TransformedSortedSet<>(set, transformer); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/UnmodifiableNavigableSet.java b/src/main/java/repack/apache/commons/collections4/set/UnmodifiableNavigableSet.java deleted file mode 100644 index f59085aab6..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/UnmodifiableNavigableSet.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.NavigableSet; -import java.util.SortedSet; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableIterator; - -/** - * Decorates another {@code NavigableSet} to ensure it can't be altered. - *

- * Attempts to modify it will result in an UnsupportedOperationException. - *

- * - * @param the type of the elements in this set - * @since 4.1 - */ -public final class UnmodifiableNavigableSet - extends AbstractNavigableSetDecorator - implements Unmodifiable { - - /** Serialization version */ - private static final long serialVersionUID = 20150528L; - - /** - * 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 NavigableSet} - * @throws NullPointerException if set is null - */ - public static NavigableSet unmodifiableNavigableSet(final NavigableSet set) { - if (set instanceof Unmodifiable) { - return set; - } - return new UnmodifiableNavigableSet<>(set); - } - - /** - * Constructor that wraps (not copies). - * - * @param set the set to decorate, must not be null - * @throws NullPointerException if set is null - */ - private UnmodifiableNavigableSet(final NavigableSet 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeAll(final Collection coll) { - throw new UnsupportedOperationException(); - } - - /** - * @since 4.5 - */ - @Override - public E pollFirst() { - throw new UnsupportedOperationException(); - } - - /** - * @since 4.5 - */ - @Override - public E pollLast() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean retainAll(final Collection coll) { - throw new UnsupportedOperationException(); - } - - // SortedSet - @Override - public SortedSet subSet(final E fromElement, final E toElement) { - final SortedSet sub = decorated().subSet(fromElement, toElement); - return UnmodifiableSortedSet.unmodifiableSortedSet(sub); - } - - @Override - public SortedSet headSet(final E toElement) { - final SortedSet head = decorated().headSet(toElement); - return UnmodifiableSortedSet.unmodifiableSortedSet(head); - } - - @Override - public SortedSet tailSet(final E fromElement) { - final SortedSet tail = decorated().tailSet(fromElement); - return UnmodifiableSortedSet.unmodifiableSortedSet(tail); - } - - // NavigableSet - @Override - public NavigableSet descendingSet() { - return unmodifiableNavigableSet(decorated().descendingSet()); - } - - @Override - public Iterator descendingIterator() { - return UnmodifiableIterator.unmodifiableIterator(decorated().descendingIterator()); - } - - @Override - public NavigableSet subSet(final E fromElement, final boolean fromInclusive, final E toElement, - final boolean toInclusive) { - final NavigableSet sub = decorated().subSet(fromElement, fromInclusive, toElement, toInclusive); - return unmodifiableNavigableSet(sub); - } - - @Override - public NavigableSet headSet(final E toElement, final boolean inclusive) { - final NavigableSet head = decorated().headSet(toElement, inclusive); - return unmodifiableNavigableSet(head); - } - - @Override - public NavigableSet tailSet(final E fromElement, final boolean inclusive) { - final NavigableSet tail = decorated().tailSet(fromElement, inclusive); - return unmodifiableNavigableSet(tail); - } - - /** - * Write the collection out using a custom routine. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the 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 error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - */ - @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) - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/UnmodifiableSet.java b/src/main/java/repack/apache/commons/collections4/set/UnmodifiableSet.java deleted file mode 100644 index 14ea1c5e40..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/UnmodifiableSet.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.set; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Set; -import java.util.function.Predicate; - -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableIterator; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the elements in this set - * @since 3.0 - */ -public final class UnmodifiableSet - extends AbstractSerializableSetDecorator - implements Unmodifiable { - - /** Serialization version */ - private static final long serialVersionUID = 6499119872185240161L; - - /** - * Factory method to create an unmodifiable set. - * - * @param the element type - * @param set the set to decorate, must not be null - * @return a new unmodifiable set - * @throws NullPointerException 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 NullPointerException 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeAll(final Collection coll) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean retainAll(final Collection coll) { - throw new UnsupportedOperationException(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/UnmodifiableSortedSet.java b/src/main/java/repack/apache/commons/collections4/set/UnmodifiableSortedSet.java deleted file mode 100644 index eace29c694..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/UnmodifiableSortedSet.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.function.Predicate; - -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableIterator; - -/** - * Decorates another {@code 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. - *

- * - * @param the type of the elements in this set - * @since 3.0 - */ -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 NullPointerException if set is null - * @since 4.0 - */ - public static SortedSet unmodifiableSortedSet(final SortedSet set) { - if (set instanceof Unmodifiable) { - return set; - } - return new UnmodifiableSortedSet<>(set); - } - - /** - * Constructor that wraps (not copies). - * - * @param set the set to decorate, must not be null - * @throws NullPointerException 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(); - } - - /** - * @since 4.4 - */ - @Override - public boolean removeIf(final Predicate filter) { - 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 unmodifiableSortedSet(sub); - } - - @Override - public SortedSet headSet(final E toElement) { - final SortedSet head = decorated().headSet(toElement); - return unmodifiableSortedSet(head); - } - - @Override - public SortedSet tailSet(final E fromElement) { - final SortedSet tail = decorated().tailSet(fromElement); - return unmodifiableSortedSet(tail); - } - - /** - * Write the collection out using a custom routine. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the 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 error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - */ - @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) - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/set/package-info.java b/src/main/java/repack/apache/commons/collections4/set/package-info.java deleted file mode 100644 index 807187f1f1..0000000000 --- a/src/main/java/repack/apache/commons/collections4/set/package-info.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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}, - * {@link java.util.SortedSet SortedSet} and - * {@link java.util.NavigableSet NavigableSet} 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 - *
- * - */ -package repack.apache.commons.collections4.set; diff --git a/src/main/java/repack/apache/commons/collections4/splitmap/AbstractIterableGetMapDecorator.java b/src/main/java/repack/apache/commons/collections4/splitmap/AbstractIterableGetMapDecorator.java deleted file mode 100644 index 6329fd9546..0000000000 --- a/src/main/java/repack/apache/commons/collections4/splitmap/AbstractIterableGetMapDecorator.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.splitmap; - -import java.util.Collection; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - -import repack.apache.commons.collections4.IterableGet; -import repack.apache.commons.collections4.MapIterator; -import repack.apache.commons.collections4.map.EntrySetToMapIteratorAdapter; - -/** - * {@link IterableGet} that uses a {@link Map}<K, V> for the - * {@link repack.apache.commons.collections4.Get Get}<K, V> implementation. - * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.0 - */ -public class AbstractIterableGetMapDecorator implements IterableGet { - - /** The map to decorate */ - transient Map map; - - /** - * Create a new AbstractSplitMapDecorator. - * @param map the map to decorate, must not be null - * @throws NullPointerException if map is null - */ - public AbstractIterableGetMapDecorator(final Map map) { - this.map = Objects.requireNonNull(map, "map"); - } - - /** - * Constructor only used in deserialization, do not use otherwise. - */ - protected AbstractIterableGetMapDecorator() { - } - - /** - * Gets the map being decorated. - * - * @return the decorated map - */ - protected Map decorated() { - return map; - } - - @Override - public boolean containsKey(final Object key) { - return decorated().containsKey(key); - } - - @Override - public boolean containsValue(final Object value) { - return decorated().containsValue(value); - } - - @Override - public Set> entrySet() { - return decorated().entrySet(); - } - - @Override - public V get(final Object key) { - return decorated().get(key); - } - - @Override - public V remove(final Object key) { - return decorated().remove(key); - } - - @Override - public boolean isEmpty() { - return decorated().isEmpty(); - } - - @Override - public Set keySet() { - return decorated().keySet(); - } - - @Override - public int size() { - return decorated().size(); - } - - @Override - public Collection values() { - return decorated().values(); - } - - /** - * Get a MapIterator over this Get. - * @return MapIterator<K, V> - */ - @Override - 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/splitmap/TransformedSplitMap.java b/src/main/java/repack/apache/commons/collections4/splitmap/TransformedSplitMap.java deleted file mode 100644 index dbbe2d7d01..0000000000 --- a/src/main/java/repack/apache/commons/collections4/splitmap/TransformedSplitMap.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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 java.util.Objects; - -import repack.apache.commons.collections4.Put; -import repack.apache.commons.collections4.Transformer; -import repack.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 repack.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 {@code >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 repack.apache.commons.collections4.Get Get} generalizations. - *

- * - * @param the type of the keys to put in this map - * @param the type of the keys to get in this map - * @param the type of the values to put in this map - * @param the type of the values to get in this map - * @since 4.0 - * - * @see repack.apache.commons.collections4.SplitMapUtils#readableMap(repack.apache.commons.collections4.Get) - * @see repack.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, must not be null - * @param valueTransformer the transformer to use for value conversion, must not be null - * @return a new transformed map - * @throws NullPointerException if map or either of the transformers 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, must not be null - * @param valueTransformer the transformer to use for value conversion, must not be null - * @throws NullPointerException if map or either of the transformers is null - */ - protected TransformedSplitMap(final Map map, final Transformer keyTransformer, - final Transformer valueTransformer) { - super(map); - this.keyTransformer = Objects.requireNonNull(keyTransformer, "keyTransformer"); - this.valueTransformer = Objects.requireNonNull(valueTransformer, "valueTransformer"); - } - - /** - * Write the map out using a custom routine. - * - * @param out the output stream - * @throws IOException if an error occurs while writing to the stream - */ - 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 if an error occurs while reading from the stream - * @throws ClassNotFoundException if an object read from the stream can not be loaded - * @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 {@code setValue}. - * - * @param value the value to transform - * @return the transformed value - */ - protected V checkSetValue(final U value) { - return valueTransformer.transform(value); - } - - @Override - public V put(final J key, final U value) { - return decorated().put(transformKey(key), transformValue(value)); - } - - @Override - public void putAll(final Map mapToCopy) { - decorated().putAll(transformMap(mapToCopy)); - } - - @Override - public void clear() { - decorated().clear(); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/splitmap/package-info.java b/src/main/java/repack/apache/commons/collections4/splitmap/package-info.java deleted file mode 100644 index 0405cdbaba..0000000000 --- a/src/main/java/repack/apache/commons/collections4/splitmap/package-info.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 repack.apache.commons.collections4.Put Put} and - * {@link repack.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 from 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 repack.apache.commons.collections4.Put Put} and - * {@link repack.apache.commons.collections4.Get Get} with matching - * generic parameters). - *

- * The following decorators are provided: - *

    - *
  • Transformed - transforms each element added - *
- * - */ -package repack.apache.commons.collections4.splitmap; diff --git a/src/main/java/repack/apache/commons/collections4/trie/AbstractBitwiseTrie.java b/src/main/java/repack/apache/commons/collections4/trie/AbstractBitwiseTrie.java deleted file mode 100644 index e5382f5020..0000000000 --- a/src/main/java/repack/apache/commons/collections4/trie/AbstractBitwiseTrie.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.trie; - -import java.io.Serializable; -import java.util.AbstractMap; -import java.util.Map; -import java.util.Objects; - -import repack.apache.commons.collections4.Trie; - -/** - * This class provides some basic {@link Trie} functionality and - * utility methods for actual bitwise {@link Trie} implementations. - * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.0 - */ -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) { - this.keyAnalyzer = Objects.requireNonNull(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)); - } - - /** - * A utility method for calling {@link KeyAnalyzer#compare(Object, Object)} - */ - final boolean compareKeys(final K key, final K other) { - if (key == null) { - return other == null; - } - if (other == null) { - return false; - } - - return keyAnalyzer.compare(key, other) == 0; - } - - /** - * Delegates to {@link Objects#equals(Object, Object)}. - */ - static boolean compare(final Object a, final Object b) { - return Objects.equals(a, 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; - - BasicEntry(final K key) { - this.key = key; - } - - 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); - } - - @Override - public K getKey() { - return key; - } - - @Override - public V getValue() { - return value; - } - - @Override - 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; - } - 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; - } - } -} diff --git a/src/main/java/repack/apache/commons/collections4/trie/AbstractPatriciaTrie.java b/src/main/java/repack/apache/commons/collections4/trie/AbstractPatriciaTrie.java deleted file mode 100644 index 976cbccd43..0000000000 --- a/src/main/java/repack/apache/commons/collections4/trie/AbstractPatriciaTrie.java +++ /dev/null @@ -1,2441 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.Objects; -import java.util.Set; -import java.util.SortedMap; - -import repack.apache.commons.collections4.OrderedMapIterator; - -/** - * This class implements the base PATRICIA algorithm and everything that - * is related to the {@link Map} interface. - * - * @since 4.0 - */ -abstract class AbstractPatriciaTrie extends AbstractBitwiseTrie { - - private static final long serialVersionUID = 5155253417231339498L; - - /** The root node of the {@link repack.apache.commons.collections4.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 repack.apache.commons.collections4.Trie}. */ - private transient int size; - - /** - * The number of times this {@link repack.apache.commons.collections4.Trie} has been modified. - * It's used to detect concurrent modifications and fail-fast the {@link Iterator}s. - */ - protected transient int modCount; - - protected AbstractPatriciaTrie(final KeyAnalyzer keyAnalyzer) { - super(keyAnalyzer); - } - - /** - * Constructs a new {@link repack.apache.commons.collections4.Trie} - * using the given {@link KeyAnalyzer} and initializes the {@link repack.apache.commons.collections4.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 repack.apache.commons.collections4.Trie} size and the modification counter. - */ - void incrementSize() { - size++; - incrementModCount(); - } - - /** - * A helper method to decrement the {@link repack.apache.commons.collections4.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) { - Objects.requireNonNull(key, "key"); - - 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; - } - 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); - - } - if (KeyAnalyzer.isEqualBitKey(bitIndex) && found != root) { // NOPMD - incrementModCount(); - return found.setKeyValue(key, value); - } - } - - throw new IllegalArgumentException("Failed to put: " + key + " -> " + value + ", " + bitIndex); - } - - /** - * Adds the given {@link TrieEntry} to the {@link repack.apache.commons.collections4.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 java.util.Map.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 repack.apache.commons.collections4.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 java.util.Map.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 repack.apache.commons.collections4.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 repack.apache.commons.collections4.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(); - } - - 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); - } - 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 repack.apache.commons.collections4.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 repack.apache.commons.collections4.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!"); - } - 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 repack.apache.commons.collections4.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!"); - } - 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 its parent - // (if we aren't removing its 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(); - } - 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 repack.apache.commons.collections4.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; - } - } - - - @Override - public Comparator comparator() { - return getKeyAnalyzer(); - } - - @Override - public K firstKey() { - if (isEmpty()) { - throw new NoSuchElementException(); - } - return firstEntry().getKey(); - } - - @Override - public K lastKey() { - final TrieEntry entry = lastEntry(); - if (entry != null) { - return entry.getKey(); - } - throw new NoSuchElementException(); - } - - @Override - public K nextKey(final K key) { - Objects.requireNonNull(key, "key"); - final TrieEntry entry = getEntry(key); - if (entry != null) { - final TrieEntry nextEntry = nextEntry(entry); - return nextEntry != null ? nextEntry.getKey() : null; - } - return null; - } - - @Override - public K previousKey(final K key) { - Objects.requireNonNull(key, "key"); - final TrieEntry entry = getEntry(key); - if (entry != null) { - final TrieEntry prevEntry = previousEntry(entry); - return prevEntry != null ? prevEntry.getKey() : null; - } - return null; - } - - @Override - public OrderedMapIterator mapIterator() { - return new TrieMapIterator(); - } - - @Override - public SortedMap prefixMap(final K key) { - return getPrefixMapByBits(key, 0, lengthInBits(key)); - } - - /** - * Returns a view of this {@link repack.apache.commons.collections4.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 repack.apache.commons.collections4.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 repack.apache.commons.collections4.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); - } - - @Override - public SortedMap headMap(final K toKey) { - return new RangeEntryMap(null, toKey); - } - - @Override - public SortedMap subMap(final K fromKey, final K toKey) { - return new RangeEntryMap(fromKey, toKey); - } - - @Override - 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); - } - // If no more after, no higher entry. - return null; - } - // 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; - } - if (KeyAnalyzer.isNullBitKey(bitIndex)) { - if (!root.isEmpty()) { - return firstEntry(); - } - if (size() > 1) { - return nextEntry(firstEntry()); - } - return null; - } - 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; - } - 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; - } - if (KeyAnalyzer.isNullBitKey(bitIndex)) { - if (!root.isEmpty()) { - return root; - } - return firstEntry(); - } - 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; - } - if (KeyAnalyzer.isNullBitKey(bitIndex)) { - return null; - } - 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; - } - 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; - } - if (KeyAnalyzer.isNullBitKey(bitIndex)) { - if (!root.isEmpty()) { - return root; - } - return null; - } - 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 - 1, endIndexInBits) - != isBitSet(entry.key, lengthInBits - 1, 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 repack.apache.commons.collections4.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; - } - return followRight(start.predecessor.left); - } - 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; - } - return root; - - } - return node.parent.left; - } - 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(); - } - 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 repack.apache.commons.collections4.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 an entry set view of the {@link repack.apache.commons.collections4.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)) { - return false; - } - if (!contains(obj)) { - 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> { - @Override - public Map.Entry next() { - return nextEntry(); - } - } - } - - /** - * This is a key set view of the {@link repack.apache.commons.collections4.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 { - @Override - public K next() { - return nextEntry().getKey(); - } - } - } - - /** - * This is a value view of the {@link repack.apache.commons.collections4.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 { - @Override - 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); - } - - @Override - public boolean hasNext() { - return next != null; - } - - @Override - 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 repack.apache.commons.collections4.Trie}. - */ - private class TrieMapIterator extends TrieIterator implements OrderedMapIterator { - - protected TrieEntry previous; // the previous node to return - - @Override - public K next() { - return nextEntry().getKey(); - } - - @Override - public K getKey() { - if (current == null) { - throw new IllegalStateException(); - } - return current.getKey(); - } - - @Override - public V getValue() { - if (current == null) { - throw new IllegalStateException(); - } - return current.getValue(); - } - - @Override - public V setValue(final V value) { - if (current == null) { - throw new IllegalStateException(); - } - return current.setValue(value); - } - - @Override - public boolean hasPrevious() { - return previous != null; - } - - @Override - 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 repack.apache.commons.collections4.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(); - - @Override - 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; - } - - @Override - 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()); - } - - @Override - public SortedMap headMap(final K toKey) { - if (!inRange2(toKey)) { - throw new IllegalArgumentException("ToKey is out of range: " + toKey); - } - return createRangeMap(getFromKey(), isFromInclusive(), toKey, isToInclusive()); - } - - @Override - 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; - } - 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; - } - 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; - } - - @Override - 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; - } - - @Override - public K lastKey() { - final 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}. - */ - RangeEntrySet(final RangeMap delegate) { - this.delegate = Objects.requireNonNull(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); - } - - @Override - 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 repack.apache.commons.collections4.Trie}. - */ - private class PrefixRangeMap extends RangeMap { - - private final K prefix; - - private final int offsetInBits; - - private final int lengthInBits; - - private K fromKey; - - private K toKey; - - private transient int expectedModCount; - - 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 repack.apache.commons.collections4.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; - } - - @Override - 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; - } - - @Override - 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); - } - - @Override - public void clear() { - final Iterator> it = AbstractPatriciaTrie.this.entrySet().iterator(); - final Set currentKeys = keySet(); - while (it.hasNext()) { - if (currentKeys.contains(it.next().getKey())) { - it.remove(); - } - } - } - } - - /** - * A prefix {@link RangeEntrySet} view of the {@link repack.apache.commons.collections4.Trie}. - */ - private final class PrefixRangeEntrySet extends RangeEntrySet { - - private final PrefixRangeMap delegate; - - private TrieEntry prefixStart; - - private int expectedModCount; - - /** - * Creates a {@link PrefixRangeEntrySet}. - */ - 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(); - } - if (delegate.lengthInBits > prefixStart.bitIndex) { - return new SingletonIterator(prefixStart); - } - 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; - - SingletonIterator(final TrieEntry entry) { - this.entry = entry; - } - - @Override - public boolean hasNext() { - return hit == 0; - } - - @Override - public Map.Entry next() { - if (hit != 0) { - throw new NoSuchElementException(); - } - - ++hit; - return entry; - } - - @Override - 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; - } - - @Override - 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); - final int size = stream.readInt(); - for (int i = 0; i < size; i++){ - final K k = (K) stream.readObject(); - final 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()); - } - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/trie/KeyAnalyzer.java b/src/main/java/repack/apache/commons/collections4/trie/KeyAnalyzer.java deleted file mode 100644 index 0eeb414ee3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/trie/KeyAnalyzer.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.trie; - -import java.io.Serializable; -import java.util.Comparator; - -/** - * Defines the interface to analyze {@link repack.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}). - *

- * - * @param the type of objects that may be compared by this analyzer - * @since 4.0 - */ -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); - - @Override - @SuppressWarnings("unchecked") - public int compare(final K o1, final K o2) { - if (o1 == null) { - return o2 == null ? 0 : -1; - } - if (o2 == null) { - return 1; - } - - return ((Comparable) o1).compareTo(o2); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/trie/PatriciaTrie.java b/src/main/java/repack/apache/commons/collections4/trie/PatriciaTrie.java deleted file mode 100644 index 8403b857b3..0000000000 --- a/src/main/java/repack/apache/commons/collections4/trie/PatriciaTrie.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.trie; - -import java.util.Map; - -import repack.apache.commons.collections4.trie.analyzer.StringKeyAnalyzer; - -/** - * Implementation of a PATRICIA Trie (Practical Algorithm to Retrieve Information - * Coded in Alphanumeric). - *

- * A PATRICIA {@link repack.apache.commons.collections4.Trie} is a compressed - * {@link repack.apache.commons.collections4.Trie}. Instead of storing - * all data at the edges of the {@link repack.apache.commons.collections4.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 repack.apache.commons.collections4.Trie} can return operations in - * lexicographical order using the 'prefixMap', 'submap', or 'iterator' methods. - * The {@link repack.apache.commons.collections4.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 repack.apache.commons.collections4.Trie} supports both variable - * length & fixed length keys. Some methods, such as {@link repack.apache.commons.collections4.Trie#prefixMap(Object)} - * are suited only to variable length keys. - *

- * - * @param the type of the values in this map - * - * @see Radix Tree - * @see PATRICIA - * @see Crit-Bit Tree - * @since 4.0 - */ -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); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/trie/UnmodifiableTrie.java b/src/main/java/repack/apache/commons/collections4/trie/UnmodifiableTrie.java deleted file mode 100644 index 9edc290bd4..0000000000 --- a/src/main/java/repack/apache/commons/collections4/trie/UnmodifiableTrie.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.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.Objects; -import java.util.Set; -import java.util.SortedMap; - -import repack.apache.commons.collections4.OrderedMapIterator; -import repack.apache.commons.collections4.Trie; -import repack.apache.commons.collections4.Unmodifiable; -import repack.apache.commons.collections4.iterators.UnmodifiableOrderedMapIterator; - -/** - * An unmodifiable {@link Trie}. - * - * @param the type of the keys in this map - * @param the type of the values in this map - * @since 4.0 - */ -public class UnmodifiableTrie implements Trie, Serializable, Unmodifiable { - - /** Serialization version */ - private static final long serialVersionUID = -7156426030315945159L; - - private final Trie delegate; - - /** - * Factory method to create an 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 NullPointerException 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 NullPointerException if trie is null - */ - public UnmodifiableTrie(final Trie trie) { - @SuppressWarnings("unchecked") // safe to upcast - final Trie tmpTrie = (Trie) Objects.requireNonNull(trie, "trie"); - this.delegate = tmpTrie; - } - - - @Override - public Set> entrySet() { - return Collections.unmodifiableSet(delegate.entrySet()); - } - - @Override - public Set keySet() { - return Collections.unmodifiableSet(delegate.keySet()); - } - - @Override - public Collection values() { - return Collections.unmodifiableCollection(delegate.values()); - } - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean containsKey(final Object key) { - return delegate.containsKey(key); - } - - @Override - public boolean containsValue(final Object value) { - return delegate.containsValue(value); - } - - @Override - public V get(final Object key) { - return delegate.get(key); - } - - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - @Override - public V put(final K key, final V value) { - throw new UnsupportedOperationException(); - } - - @Override - public void putAll(final Map m) { - throw new UnsupportedOperationException(); - } - - @Override - public V remove(final Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public int size() { - return delegate.size(); - } - - @Override - public K firstKey() { - return delegate.firstKey(); - } - - @Override - public SortedMap headMap(final K toKey) { - return Collections.unmodifiableSortedMap(delegate.headMap(toKey)); - } - - @Override - public K lastKey() { - return delegate.lastKey(); - } - - @Override - public SortedMap subMap(final K fromKey, final K toKey) { - return Collections.unmodifiableSortedMap(delegate.subMap(fromKey, toKey)); - } - - @Override - public SortedMap tailMap(final K fromKey) { - return Collections.unmodifiableSortedMap(delegate.tailMap(fromKey)); - } - - @Override - public SortedMap prefixMap(final K key) { - return Collections.unmodifiableSortedMap(delegate.prefixMap(key)); - } - - @Override - public Comparator comparator() { - return delegate.comparator(); - } - - @Override - public OrderedMapIterator mapIterator() { - final OrderedMapIterator it = delegate.mapIterator(); - return UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(it); - } - - @Override - public K nextKey(final K key) { - return delegate.nextKey(key); - } - - @Override - public K previousKey(final 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(); - } - -} diff --git a/src/main/java/repack/apache/commons/collections4/trie/analyzer/StringKeyAnalyzer.java b/src/main/java/repack/apache/commons/collections4/trie/analyzer/StringKeyAnalyzer.java deleted file mode 100644 index ddcec35f20..0000000000 --- a/src/main/java/repack/apache/commons/collections4/trie/analyzer/StringKeyAnalyzer.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package repack.apache.commons.collections4.trie.analyzer; - -import repack.apache.commons.collections4.trie.KeyAnalyzer; - -/** - * An {@link KeyAnalyzer} for {@link String}s. - * - * @since 4.0 - */ -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); - } -} diff --git a/src/main/java/repack/apache/commons/collections4/trie/analyzer/package-info.java b/src/main/java/repack/apache/commons/collections4/trie/analyzer/package-info.java deleted file mode 100644 index e3090b917a..0000000000 --- a/src/main/java/repack/apache/commons/collections4/trie/analyzer/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 repack.apache.commons.collections4.trie.KeyAnalyzer} implementations. - * - */ -package repack.apache.commons.collections4.trie.analyzer; diff --git a/src/main/java/repack/apache/commons/collections4/trie/package-info.java b/src/main/java/repack/apache/commons/collections4/trie/package-info.java deleted file mode 100644 index ff90f1d105..0000000000 --- a/src/main/java/repack/apache/commons/collections4/trie/package-info.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES 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 repack.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 - *
- * - */ -package repack.apache.commons.collections4.trie;