You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@openjpa.apache.org by rm...@apache.org on 2020/09/16 10:17:19 UTC
[openjpa] branch master updated: [OPENJPA-2831] import
[collections4] used classes and drop the dependency
This is an automated email from the ASF dual-hosted git repository.
rmannibucau pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/openjpa.git
The following commit(s) were added to refs/heads/master by this push:
new 33fc72a [OPENJPA-2831] import [collections4] used classes and drop the dependency
33fc72a is described below
commit 33fc72ac857dff85f9ff1ef3173638ca504a5d22
Author: Romain Manni-Bucau <rm...@gmail.com>
AuthorDate: Wed Sep 16 12:16:57 2020 +0200
[OPENJPA-2831] import [collections4] used classes and drop the dependency
---
openjpa-features/src/main/feature/feature.xml | 1 -
.../openjpa/jdbc/sql/InformixDictionary.java | 4 +-
.../org/apache/openjpa/jdbc/sql/SelectImpl.java | 5 +-
.../openjpa/datacache/AbstractQueryCache.java | 2 +-
.../openjpa/datacache/QueryCacheStoreQuery.java | 2 +-
.../org/apache/openjpa/enhance/PCRegistry.java | 9 +-
.../org/apache/openjpa/enhance/Reflection.java | 2 +-
.../event/SingleJVMRemoteCommitProvider.java | 2 +-
.../openjpa/kernel/AbstractBrokerFactory.java | 4 +-
.../apache/openjpa/kernel/AbstractStoreQuery.java | 2 +-
.../java/org/apache/openjpa/kernel/BrokerImpl.java | 17 +-
.../org/apache/openjpa/kernel/DelegatingQuery.java | 2 +-
.../java/org/apache/openjpa/kernel/ExtentImpl.java | 14 +-
.../org/apache/openjpa/kernel/ManagedCache.java | 4 +-
.../org/apache/openjpa/kernel/QueryContext.java | 5 +-
.../java/org/apache/openjpa/kernel/QueryImpl.java | 7 +-
.../org/apache/openjpa/kernel/QueryStatistics.java | 2 +-
.../java/org/apache/openjpa/kernel/StoreQuery.java | 2 +-
.../org/apache/openjpa/meta/FieldMetaData.java | 2 +-
.../org/apache/openjpa/meta/ValueStrategies.java | 2 +-
.../apache/openjpa/util/AbstractChangeTracker.java | 4 +-
.../openjpa/util/AbstractLRSProxyCollection.java | 8 +-
.../apache/openjpa/util/AbstractLRSProxyMap.java | 10 +-
.../java/org/apache/openjpa/util/CacheMap.java | 14 +-
.../java/org/apache/openjpa/util/ImplHelper.java | 2 +-
.../java/org/apache/openjpa/util/OpenJPAId.java | 2 +-
openjpa-lib/pom.xml | 4 -
.../apache/openjpa/lib/conf/Configurations.java | 2 +-
.../org/apache/openjpa/lib/conf/ObjectValue.java | 2 +-
.../lib/rop/SoftRandomAccessResultList.java | 4 +-
.../java/org/apache/openjpa/lib/util/LRUMap.java | 2 +-
.../apache/openjpa/lib/util/ReferenceHashMap.java | 9 +-
.../apache/openjpa/lib/util/ReferenceHashSet.java | 12 +-
.../collections/AbstractCollectionDecorator.java | 189 ++
.../lib/util/collections/AbstractDualBidiMap.java | 824 +++++++
.../util/collections/AbstractEmptyIterator.java | 75 +
.../util/collections/AbstractEmptyMapIterator.java | 47 +
.../lib/util/collections/AbstractHashedMap.java | 1395 ++++++++++++
.../lib/util/collections/AbstractIterableMap.java | 35 +
.../collections/AbstractIteratorDecorator.java | 47 +
.../lib/util/collections/AbstractKeyValue.java | 92 +
.../lib/util/collections/AbstractLinkedMap.java | 620 ++++++
.../util/collections/AbstractListDecorator.java | 128 ++
.../lib/util/collections/AbstractMapDecorator.java | 156 ++
.../lib/util/collections/AbstractMapEntry.java | 92 +
.../collections/AbstractMapEntryDecorator.java | 91 +
.../collections/AbstractOrderedMapDecorator.java | 94 +
.../lib/util/collections/AbstractReferenceMap.java | 1107 ++++++++++
.../AbstractSerializableListDecorator.java | 71 +
.../AbstractSerializableSetDecorator.java | 72 +
.../lib/util/collections/AbstractSetDecorator.java | 74 +
.../collections/AbstractSortedMapDecorator.java | 169 ++
.../AbstractUntypedIteratorDecorator.java | 67 +
.../openjpa/lib/util/collections/BidiMap.java | 155 ++
.../openjpa/lib/util/collections/BoundedMap.java | 47 +
.../lib/util/collections/ComparableComparator.java | 131 ++
.../lib/util/collections/ComparatorChain.java | 352 +++
.../lib/util/collections/DefaultMapEntry.java | 61 +
.../lib/util/collections/DualHashBidiMap.java | 109 +
.../lib/util/collections/DualTreeBidiMap.java | 411 ++++
.../lib/util/collections/EmptyIterator.java | 71 +
.../lib/util/collections/EmptyMapIterator.java | 53 +
.../lib/util/collections/EmptyOrderedIterator.java | 51 +
.../util/collections/EmptyOrderedMapIterator.java | 53 +
.../collections/EntrySetToMapIteratorAdapter.java | 119 ++
.../lib/util/collections/FilterIterator.java | 184 ++
.../openjpa/lib/util/collections/IterableMap.java | 87 +
.../lib/util/collections/IterableSortedMap.java | 30 +
.../lib/util/collections/IteratorChain.java | 280 +++
.../openjpa/lib/util/collections/KeyValue.java | 47 +
.../openjpa/lib/util/collections/LRUMap.java | 530 +++++
.../openjpa/lib/util/collections/LinkedMap.java | 321 +++
.../lib/util/collections/ListIteratorWrapper.java | 269 +++
.../openjpa/lib/util/collections/MapBackedSet.java | 177 ++
.../openjpa/lib/util/collections/MapIterator.java | 114 +
.../lib/util/collections/OrderedBidiMap.java | 52 +
.../lib/util/collections/OrderedIterator.java | 47 +
.../openjpa/lib/util/collections/OrderedMap.java | 73 +
.../lib/util/collections/OrderedMapIterator.java | 48 +
.../lib/util/collections/ReferenceIdentityMap.java | 255 +++
.../openjpa/lib/util/collections/ReferenceMap.java | 200 ++
.../lib/util/collections/ResettableIterator.java | 38 +
.../util/collections/ResettableListIterator.java | 32 +
.../lib/util/collections/SortedBidiMap.java | 59 +
.../openjpa/lib/util/collections/TreeBidiMap.java | 2255 ++++++++++++++++++++
.../openjpa/lib/util/collections/Unmodifiable.java | 38 +
.../util/collections/UnmodifiableCollection.java | 118 +
.../lib/util/collections/UnmodifiableEntrySet.java | 190 ++
.../lib/util/collections/UnmodifiableIterator.java | 84 +
.../lib/util/collections/UnmodifiableList.java | 154 ++
.../util/collections/UnmodifiableListIterator.java | 112 +
.../lib/util/collections/UnmodifiableMapEntry.java | 73 +
.../util/collections/UnmodifiableOrderedMap.java | 149 ++
.../UnmodifiableOrderedMapIterator.java | 111 +
.../lib/util/collections/UnmodifiableSet.java | 117 +
.../collections/package-info.java} | 23 +-
.../concurrent/ConcurrentReferenceHashMap.java | 45 +-
.../concurrent/ConcurrentReferenceHashSet.java | 10 +-
.../apache/openjpa/lib/util/TestReferenceSet.java | 2 +-
openjpa-persistence-jdbc/pom.xml | 5 -
.../jdbc/common/apps/HorizRelation.java | 4 +-
.../openjpa/persistence/kernel/TestProxies2.java | 2 +-
.../persistence/kernel/common/apps/ProxiesPC.java | 2 +-
openjpa-project/assembly.xml | 1 -
openjpa-project/bin-assembly.xml | 1 -
pom.xml | 5 -
106 files changed, 13422 insertions(+), 145 deletions(-)
diff --git a/openjpa-features/src/main/feature/feature.xml b/openjpa-features/src/main/feature/feature.xml
index c3fc1c3..907f22f 100644
--- a/openjpa-features/src/main/feature/feature.xml
+++ b/openjpa-features/src/main/feature/feature.xml
@@ -26,7 +26,6 @@
<bundle dependency="true">mvn:org.apache.geronimo.specs/geronimo-el_1.0_spec/1.0.1</bundle>
<bundle dependency="true">mvn:org.apache.commons/commons-pool2/2.6.0</bundle>
<bundle dependency="true">mvn:org.apache.commons/commons-dbcp2/2.7.0</bundle>
- <bundle dependency="true">mvn:org.apache.commons/commons-collections4/4.4</bundle>
<bundle dependency="true">mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.serp/1.14.1_1</bundle>
<bundle dependency="true">mvn:org.apache.xbean/xbean-asm8-shaded/${xbean.version}</bundle>
<bundle>mvn:org.apache.openjpa/openjpa/${project.version}</bundle>
diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/InformixDictionary.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/InformixDictionary.java
index f750f1f..05c2016 100644
--- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/InformixDictionary.java
+++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/InformixDictionary.java
@@ -31,7 +31,6 @@ import java.util.Collections;
import java.util.Map;
import java.util.Set;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.jdbc.identifier.DBIdentifier;
import org.apache.openjpa.jdbc.identifier.DBIdentifier.DBIdentifierType;
import org.apache.openjpa.jdbc.kernel.exps.FilterValue;
@@ -42,6 +41,7 @@ import org.apache.openjpa.jdbc.schema.PrimaryKey;
import org.apache.openjpa.jdbc.schema.Table;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.ReferenceHashSet;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap;
import org.apache.openjpa.util.StoreException;
import org.apache.openjpa.util.UnsupportedException;
@@ -85,7 +85,7 @@ public class InformixDictionary
protected boolean useJCC = false;
// weak set of connections we've already executed lock mode sql on
private final Collection _seenConnections = Collections.synchronizedSet(
- new ReferenceHashSet(ReferenceStrength.WEAK));
+ new ReferenceHashSet(AbstractReferenceMap.ReferenceStrength.WEAK));
public boolean disableRetainUpdateLocksSQL=false;
diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SelectImpl.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SelectImpl.java
index 1c10959..5157273 100644
--- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SelectImpl.java
+++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SelectImpl.java
@@ -38,7 +38,6 @@ import java.util.SortedMap;
import java.util.Stack;
import java.util.TreeMap;
-import org.apache.commons.collections4.iterators.EmptyIterator;
import org.apache.openjpa.jdbc.conf.JDBCConfiguration;
import org.apache.openjpa.jdbc.kernel.EagerFetchModes;
import org.apache.openjpa.jdbc.kernel.JDBCFetchConfiguration;
@@ -64,6 +63,8 @@ import org.apache.openjpa.util.ApplicationIds;
import org.apache.openjpa.util.Id;
import org.apache.openjpa.util.InternalException;
+import static java.util.Collections.emptyIterator;
+
/**
* Standard {@link Select} implementation. Usage note: though this class
* implements {@link Joins}, it should not be used for joining directly.
@@ -750,7 +751,7 @@ public class SelectImpl
@Override
public Iterator getJoinIterator() {
if (_joins == null || _joins.isEmpty())
- return EmptyIterator.INSTANCE;
+ return emptyIterator();
return _joins.joins().joinIterator();
}
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/AbstractQueryCache.java b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/AbstractQueryCache.java
index 3eac6db..9c7ea75 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/AbstractQueryCache.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/AbstractQueryCache.java
@@ -31,7 +31,6 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.event.RemoteCommitEvent;
import org.apache.openjpa.event.RemoteCommitListener;
@@ -41,6 +40,7 @@ import org.apache.openjpa.lib.conf.Configuration;
import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.concurrent.AbstractConcurrentEventManager;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashSet;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/QueryCacheStoreQuery.java b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/QueryCacheStoreQuery.java
index 17224f1..9e55326 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/QueryCacheStoreQuery.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/datacache/QueryCacheStoreQuery.java
@@ -30,7 +30,6 @@ import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
-import org.apache.commons.collections4.map.LinkedMap;
import org.apache.openjpa.datacache.AbstractQueryCache.EvictPolicy;
import org.apache.openjpa.kernel.FetchConfiguration;
import org.apache.openjpa.kernel.LockLevels;
@@ -45,6 +44,7 @@ import org.apache.openjpa.kernel.exps.QueryExpressions;
import org.apache.openjpa.lib.rop.ListResultObjectProvider;
import org.apache.openjpa.lib.rop.ResultObjectProvider;
import org.apache.openjpa.lib.util.OrderedMap;
+import org.apache.openjpa.lib.util.collections.LinkedMap;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.JavaTypes;
import org.apache.openjpa.meta.MetaDataRepository;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCRegistry.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCRegistry.java
index e361203..0a79ec1 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCRegistry.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/PCRegistry.java
@@ -22,8 +22,8 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Map;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashSet;
import org.apache.openjpa.util.UserException;
@@ -40,14 +40,15 @@ public class PCRegistry {
private static final Localizer _loc = Localizer.forPackage(PCRegistry.class);
// map of persistent classes to meta structures; weak so the VM can GC classes
- private static final Map<Class<?>,Meta> _metas = new ConcurrentReferenceHashMap(ReferenceStrength.WEAK,
- ReferenceStrength.HARD);
+ private static final Map<Class<?>,Meta> _metas = new ConcurrentReferenceHashMap(
+ AbstractReferenceMap.ReferenceStrength.WEAK,
+ AbstractReferenceMap.ReferenceStrength.HARD);
// register class listeners
// Weak reference prevents OutOfMemeoryError as described in OPENJPA-2042
private static final Collection<RegisterClassListener> _listeners =
new ConcurrentReferenceHashSet<>(
- ReferenceStrength.WEAK);
+ AbstractReferenceMap.ReferenceStrength.WEAK);
/**
* Register a {@link RegisterClassListener}.
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/Reflection.java b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/Reflection.java
index 7492d86..4aad923 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/Reflection.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/enhance/Reflection.java
@@ -29,12 +29,12 @@ import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.Localizer.Message;
import org.apache.openjpa.lib.util.Reflectable;
import org.apache.openjpa.lib.util.StringUtil;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap;
import org.apache.openjpa.util.GeneralException;
import org.apache.openjpa.util.UserException;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/event/SingleJVMRemoteCommitProvider.java b/openjpa-kernel/src/main/java/org/apache/openjpa/event/SingleJVMRemoteCommitProvider.java
index 0fb290d..3e98de3 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/event/SingleJVMRemoteCommitProvider.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/event/SingleJVMRemoteCommitProvider.java
@@ -21,7 +21,7 @@ package org.apache.openjpa.event;
import java.util.Iterator;
import java.util.Set;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashSet;
/**
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java
index 225b129..f3d8266 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java
@@ -39,8 +39,7 @@ import javax.transaction.Synchronization;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
-import org.apache.commons.collections4.set.MapBackedSet;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.audit.Auditor;
import org.apache.openjpa.conf.BrokerValue;
import org.apache.openjpa.conf.OpenJPAConfiguration;
@@ -61,6 +60,7 @@ import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.StringUtil;
+import org.apache.openjpa.lib.util.collections.MapBackedSet;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashSet;
import org.apache.openjpa.meta.MetaDataModes;
import org.apache.openjpa.meta.MetaDataRepository;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractStoreQuery.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractStoreQuery.java
index 6873daf..56994a0 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractStoreQuery.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractStoreQuery.java
@@ -20,13 +20,13 @@ package org.apache.openjpa.kernel;
import java.util.Map;
-import org.apache.commons.collections4.map.LinkedMap;
import org.apache.openjpa.datacache.DataCache;
import org.apache.openjpa.kernel.exps.AggregateListener;
import org.apache.openjpa.kernel.exps.FilterListener;
import org.apache.openjpa.kernel.exps.QueryExpressions;
import org.apache.openjpa.kernel.exps.Value;
import org.apache.openjpa.lib.util.OrderedMap;
+import org.apache.openjpa.lib.util.collections.LinkedMap;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.FieldMetaData;
import org.apache.openjpa.util.InternalException;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java
index a1a7680..81ecf25 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/BrokerImpl.java
@@ -44,10 +44,6 @@ import java.util.concurrent.locks.ReentrantLock;
import javax.transaction.Status;
import javax.transaction.Synchronization;
-import org.apache.commons.collections4.iterators.IteratorChain;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
-import org.apache.commons.collections4.map.LinkedMap;
-import org.apache.commons.collections4.set.MapBackedSet;
import org.apache.openjpa.conf.Compatibility;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.datacache.DataCache;
@@ -73,6 +69,10 @@ import org.apache.openjpa.lib.util.ReferenceHashMap;
import org.apache.openjpa.lib.util.ReferenceHashSet;
import org.apache.openjpa.lib.util.ReferenceMap;
import org.apache.openjpa.lib.util.StringUtil;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap;
+import org.apache.openjpa.lib.util.collections.IteratorChain;
+import org.apache.openjpa.lib.util.collections.LinkedMap;
+import org.apache.openjpa.lib.util.collections.MapBackedSet;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.FieldMetaData;
import org.apache.openjpa.meta.MetaDataRepository;
@@ -432,7 +432,8 @@ public class BrokerImpl implements Broker, FindCallbacks, Cloneable, Serializabl
* {@link ReferenceMap} with soft values.
*/
protected Map<?,?> newManagedObjectCache() {
- return new ReferenceHashMap(ReferenceStrength.HARD, ReferenceStrength.SOFT);
+ return new ReferenceHashMap(
+ AbstractReferenceMap.ReferenceStrength.HARD, AbstractReferenceMap.ReferenceStrength.SOFT);
}
//////////////////////////////////
@@ -3872,7 +3873,7 @@ public class BrokerImpl implements Broker, FindCallbacks, Cloneable, Serializabl
try {
ExtentImpl extent = new ExtentImpl(this, type, subclasses, fetch);
if (_extents == null)
- _extents = new ReferenceHashSet(ReferenceStrength.WEAK);
+ _extents = new ReferenceHashSet(AbstractReferenceMap.ReferenceStrength.WEAK);
_extents.add(extent);
return extent;
@@ -3926,7 +3927,7 @@ public class BrokerImpl implements Broker, FindCallbacks, Cloneable, Serializabl
// track queries
if (_queries == null)
- _queries = new ReferenceHashSet(ReferenceStrength.WEAK);
+ _queries = new ReferenceHashSet(AbstractReferenceMap.ReferenceStrength.WEAK);
_queries.add(q);
return q;
} catch (OpenJPAException ke) {
@@ -5075,7 +5076,7 @@ public class BrokerImpl implements Broker, FindCallbacks, Cloneable, Serializabl
private boolean addCleanInternal(StateManagerImpl sm) {
if (_clean == null)
- _clean = new ReferenceHashSet(ReferenceStrength.SOFT);
+ _clean = new ReferenceHashSet(AbstractReferenceMap.ReferenceStrength.SOFT);
return _clean.add(sm);
}
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingQuery.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingQuery.java
index 2b7af53..6da9bf3 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingQuery.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/DelegatingQuery.java
@@ -21,10 +21,10 @@ package org.apache.openjpa.kernel;
import java.util.Collection;
import java.util.Map;
-import org.apache.commons.collections4.map.LinkedMap;
import org.apache.openjpa.kernel.exps.AggregateListener;
import org.apache.openjpa.kernel.exps.FilterListener;
import org.apache.openjpa.lib.util.OrderedMap;
+import org.apache.openjpa.lib.util.collections.LinkedMap;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.util.RuntimeExceptionTranslator;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExtentImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExtentImpl.java
index f104196..421a1c1 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExtentImpl.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ExtentImpl.java
@@ -23,15 +23,15 @@ import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.locks.ReentrantLock;
+import java.util.function.Predicate;
-import org.apache.commons.collections4.Predicate;
-import org.apache.commons.collections4.iterators.FilterIterator;
-import org.apache.commons.collections4.iterators.IteratorChain;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.rop.ResultObjectProvider;
import org.apache.openjpa.lib.rop.ResultObjectProviderIterator;
import org.apache.openjpa.lib.util.Closeable;
import org.apache.openjpa.lib.util.ReferenceHashSet;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap;
+import org.apache.openjpa.lib.util.collections.FilterIterator;
+import org.apache.openjpa.lib.util.collections.IteratorChain;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.MetaDataRepository;
import org.apache.openjpa.util.GeneralException;
@@ -162,7 +162,7 @@ public class ExtentImpl<T>
lock();
try {
if (_openItrs == null)
- _openItrs = new ReferenceHashSet(ReferenceStrength.WEAK);
+ _openItrs = new ReferenceHashSet(AbstractReferenceMap.ReferenceStrength.WEAK);
_openItrs.add(citr);
} finally {
unlock();
@@ -339,7 +339,7 @@ public class ExtentImpl<T>
}
@Override
- public boolean evaluate(Object o) {
+ public boolean test(Object o) {
return !_extent._broker.isDeleted(o);
}
}
@@ -362,7 +362,7 @@ public class ExtentImpl<T>
}
@Override
- public boolean evaluate(Object o) {
+ public boolean test(Object o) {
if (!_broker.isNew(o))
return false;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ManagedCache.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ManagedCache.java
index d5a806e..212a7ef 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ManagedCache.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/ManagedCache.java
@@ -27,9 +27,9 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.ReferenceHashSet;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap;
import org.apache.openjpa.util.Exceptions;
import org.apache.openjpa.util.UserException;
@@ -109,7 +109,7 @@ class ManagedCache implements Serializable {
if (!sm.isPersistent() || sm.isEmbedded()) {
if (_embeds == null)
- _embeds = new ReferenceHashSet(ReferenceStrength.WEAK);
+ _embeds = new ReferenceHashSet(AbstractReferenceMap.ReferenceStrength.WEAK);
_embeds.add(sm);
return;
}
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryContext.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryContext.java
index 48f15e3..25f5eca 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryContext.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryContext.java
@@ -21,12 +21,12 @@ package org.apache.openjpa.kernel;
import java.util.Collection;
import java.util.Map;
-import org.apache.commons.collections4.map.LinkedMap;
import org.apache.openjpa.kernel.exps.AggregateListener;
import org.apache.openjpa.kernel.exps.Constant;
import org.apache.openjpa.kernel.exps.FilterListener;
import org.apache.openjpa.kernel.exps.Value;
import org.apache.openjpa.lib.util.OrderedMap;
+import org.apache.openjpa.lib.util.collections.LinkedMap;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.FieldMetaData;
@@ -199,7 +199,8 @@ public interface QueryContext {
* map will iterate in the order that the parameters were declared or,
* if they're implicit, used.
*/
- @Deprecated LinkedMap getParameterTypes();
+ @Deprecated
+ LinkedMap getParameterTypes();
/**
* If this query is a bulk update, return a map of the
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryImpl.java
index cb50be1..a316b89 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryImpl.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryImpl.java
@@ -33,8 +33,6 @@ import java.util.Map.Entry;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
-import org.apache.commons.collections4.map.LinkedMap;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.enhance.PersistenceCapable;
import org.apache.openjpa.kernel.exps.AggregateListener;
@@ -47,7 +45,6 @@ import org.apache.openjpa.kernel.exps.Val;
import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.rop.BatchedResultObjectProvider;
import org.apache.openjpa.lib.rop.EagerResultList;
-import org.apache.openjpa.lib.rop.ListResultList;
import org.apache.openjpa.lib.rop.MergedResultObjectProvider;
import org.apache.openjpa.lib.rop.RangeResultObjectProvider;
import org.apache.openjpa.lib.rop.ResultList;
@@ -58,6 +55,8 @@ import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.OrderedMap;
import org.apache.openjpa.lib.util.ReferenceHashSet;
import org.apache.openjpa.lib.util.StringUtil;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap;
+import org.apache.openjpa.lib.util.collections.LinkedMap;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.FieldMetaData;
import org.apache.openjpa.meta.JavaTypes;
@@ -128,7 +127,7 @@ public class QueryImpl implements Query {
// remember the list of all the results we have returned so we
// can free their resources when close or closeAll is called
private transient final Collection<RemoveOnCloseResultList> _resultLists =
- new ReferenceHashSet(ReferenceStrength.WEAK);
+ new ReferenceHashSet(AbstractReferenceMap.ReferenceStrength.WEAK);
private boolean _printParameters = false;
/**
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryStatistics.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryStatistics.java
index 981fcb5..499851a 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryStatistics.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/QueryStatistics.java
@@ -25,7 +25,7 @@ import java.util.Date;
import java.util.Map;
import java.util.Set;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap;
/**
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreQuery.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreQuery.java
index 26b850d..ef357cd 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreQuery.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/StoreQuery.java
@@ -22,7 +22,6 @@ import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
-import org.apache.commons.collections4.map.LinkedMap;
import org.apache.openjpa.kernel.exps.AggregateListener;
import org.apache.openjpa.kernel.exps.Constant;
import org.apache.openjpa.kernel.exps.FilterListener;
@@ -30,6 +29,7 @@ import org.apache.openjpa.kernel.exps.QueryExpressions;
import org.apache.openjpa.kernel.exps.Value;
import org.apache.openjpa.lib.rop.ResultObjectProvider;
import org.apache.openjpa.lib.util.OrderedMap;
+import org.apache.openjpa.lib.util.collections.LinkedMap;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.FieldMetaData;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/FieldMetaData.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/FieldMetaData.java
index c1fda39..4d5fa26 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/FieldMetaData.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/FieldMetaData.java
@@ -45,7 +45,6 @@ import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
-import org.apache.commons.collections4.comparators.ComparatorChain;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.kernel.OpenJPAStateManager;
import org.apache.openjpa.kernel.StoreContext;
@@ -57,6 +56,7 @@ import org.apache.openjpa.lib.util.JavaVersions;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.Options;
import org.apache.openjpa.lib.util.StringUtil;
+import org.apache.openjpa.lib.util.collections.ComparatorChain;
import org.apache.openjpa.lib.xml.Commentable;
import org.apache.openjpa.util.Exceptions;
import org.apache.openjpa.util.ImplHelper;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ValueStrategies.java b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ValueStrategies.java
index 1dd167f..3aad2e8 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ValueStrategies.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/meta/ValueStrategies.java
@@ -18,10 +18,10 @@
*/
package org.apache.openjpa.meta;
-import org.apache.commons.collections4.bidimap.TreeBidiMap;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.StringDistance;
+import org.apache.openjpa.lib.util.collections.TreeBidiMap;
import org.apache.openjpa.util.MetaDataException;
/**
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractChangeTracker.java b/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractChangeTracker.java
index cdddbb3..a891503 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractChangeTracker.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractChangeTracker.java
@@ -18,14 +18,14 @@
*/
package org.apache.openjpa.util;
+import org.apache.openjpa.lib.util.collections.MapBackedSet;
+
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Set;
-import org.apache.commons.collections4.set.MapBackedSet;
-
/**
* Base class that provides utilities to change trackers.
*
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractLRSProxyCollection.java b/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractLRSProxyCollection.java
index b9c1757..52c342d 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractLRSProxyCollection.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractLRSProxyCollection.java
@@ -25,13 +25,13 @@ import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
+import java.util.function.Predicate;
-import org.apache.commons.collections4.Predicate;
-import org.apache.commons.collections4.iterators.FilterIterator;
-import org.apache.commons.collections4.iterators.IteratorChain;
import org.apache.openjpa.kernel.OpenJPAStateManager;
import org.apache.openjpa.lib.util.Closeable;
import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.lib.util.collections.FilterIterator;
+import org.apache.openjpa.lib.util.collections.IteratorChain;
/**
* A collection proxy designed for collections backed by extremely large
@@ -318,7 +318,7 @@ public abstract class AbstractLRSProxyCollection
////////////////////////////
@Override
- public boolean evaluate(Object o) {
+ public boolean test(Object o) {
return !_ct.getRemoved().contains(o);
}
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractLRSProxyMap.java b/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractLRSProxyMap.java
index 3386273..82118f7 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractLRSProxyMap.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/util/AbstractLRSProxyMap.java
@@ -28,13 +28,13 @@ import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
+import java.util.function.Predicate;
-import org.apache.commons.collections4.Predicate;
-import org.apache.commons.collections4.iterators.FilterIterator;
-import org.apache.commons.collections4.iterators.IteratorChain;
import org.apache.openjpa.kernel.OpenJPAStateManager;
import org.apache.openjpa.lib.util.Closeable;
import org.apache.openjpa.lib.util.Localizer;
+import org.apache.openjpa.lib.util.collections.FilterIterator;
+import org.apache.openjpa.lib.util.collections.IteratorChain;
/**
* A map proxy designed for maps backed by extremely large result sets in
@@ -367,7 +367,7 @@ public abstract class AbstractLRSProxyMap<K,V>
_iterated = true;
// have to copy the entry set of _map to prevent concurrent mod errors
- IteratorChain chain = new IteratorChain();
+ IteratorChain chain = new IteratorChain<>();
if (_map != null)
chain.addIterator(new ArrayList(_map.entrySet()).iterator());
chain.addIterator(new FilterIterator(itr(), this));
@@ -379,7 +379,7 @@ public abstract class AbstractLRSProxyMap<K,V>
////////////////////////////
@Override
- public boolean evaluate(Object obj) {
+ public boolean test(Object obj) {
Map.Entry entry = (Map.Entry) obj;
return (_ct.getTrackKeys()
&& !_ct.getRemoved().contains(entry.getKey())
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/util/CacheMap.java b/openjpa-kernel/src/main/java/org/apache/openjpa/util/CacheMap.java
index 31c04b7..2560cb7 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/util/CacheMap.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/util/CacheMap.java
@@ -27,13 +27,13 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.Predicate;
-import org.apache.commons.collections4.Predicate;
-import org.apache.commons.collections4.iterators.FilterIterator;
-import org.apache.commons.collections4.iterators.IteratorChain;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.LRUMap;
import org.apache.openjpa.lib.util.SizedMap;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap;
+import org.apache.openjpa.lib.util.collections.FilterIterator;
+import org.apache.openjpa.lib.util.collections.IteratorChain;
import org.apache.openjpa.lib.util.concurrent.ConcurrentHashMap;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap;
@@ -112,8 +112,8 @@ public class CacheMap
if (size < 0)
size = 500;
- softMap = new ConcurrentReferenceHashMap(ReferenceStrength.HARD,
- ReferenceStrength.SOFT, size, load) {
+ softMap = new ConcurrentReferenceHashMap(AbstractReferenceMap.ReferenceStrength.HARD,
+ AbstractReferenceMap.ReferenceStrength.SOFT, size, load) {
@Override
public void overflowRemoved(Object key, Object value) {
softMapOverflowRemoved(key, value);
@@ -672,7 +672,7 @@ public class CacheMap
}
@Override
- public boolean evaluate(Object obj) {
+ public boolean test(Object obj) {
switch (_type) {
case ENTRY:
return ((Map.Entry) obj).getValue() != null;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/util/ImplHelper.java b/openjpa-kernel/src/main/java/org/apache/openjpa/util/ImplHelper.java
index 154e5e0..023abf8 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/util/ImplHelper.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/util/ImplHelper.java
@@ -25,7 +25,6 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.conf.OpenJPAConfiguration;
import org.apache.openjpa.enhance.ManagedInstanceProvider;
import org.apache.openjpa.enhance.PCRegistry;
@@ -41,6 +40,7 @@ import org.apache.openjpa.kernel.StoreContext;
import org.apache.openjpa.kernel.StoreManager;
import org.apache.openjpa.lib.util.Closeable;
import org.apache.openjpa.lib.util.UUIDGenerator;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap;
import org.apache.openjpa.meta.ClassMetaData;
import org.apache.openjpa.meta.FieldMetaData;
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/util/OpenJPAId.java b/openjpa-kernel/src/main/java/org/apache/openjpa/util/OpenJPAId.java
index 09113a4..48298d4 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/util/OpenJPAId.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/util/OpenJPAId.java
@@ -20,7 +20,7 @@ package org.apache.openjpa.util;
import java.io.Serializable;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap;
/**
diff --git a/openjpa-lib/pom.xml b/openjpa-lib/pom.xml
index 2eacec5..4b95357 100644
--- a/openjpa-lib/pom.xml
+++ b/openjpa-lib/pom.xml
@@ -68,10 +68,6 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-collections4</artifactId>
- </dependency>
- <dependency>
<groupId>net.sourceforge.serp</groupId>
<artifactId>serp</artifactId>
</dependency>
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java
index 5e8ad9a..624f3cc 100644
--- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/Configurations.java
@@ -35,7 +35,7 @@ import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.util.ClassUtil;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ObjectValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ObjectValue.java
index 37b55f0..268da42 100644
--- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ObjectValue.java
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/conf/ObjectValue.java
@@ -21,7 +21,7 @@ package org.apache.openjpa.lib.conf;
import java.security.AccessController;
import java.util.Objects;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap.ReferenceStrength;
import org.apache.openjpa.lib.util.J2DoPrivHelper;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashMap;
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/rop/SoftRandomAccessResultList.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/rop/SoftRandomAccessResultList.java
index fac8d4f..bee41c6 100644
--- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/rop/SoftRandomAccessResultList.java
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/rop/SoftRandomAccessResultList.java
@@ -18,9 +18,9 @@
*/
package org.apache.openjpa.lib.rop;
-import java.util.Map;
+import org.apache.openjpa.lib.util.collections.ReferenceMap;
-import org.apache.commons.collections4.map.ReferenceMap;
+import java.util.Map;
/**
* Specialization of the {@link RandomAccessResultList} that only maintains
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/LRUMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/LRUMap.java
index 4065a8a..6371ec3 100644
--- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/LRUMap.java
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/LRUMap.java
@@ -29,7 +29,7 @@ import java.util.Map;
*
* @author Abe White
*/
-public class LRUMap extends org.apache.commons.collections4.map.LRUMap
+public class LRUMap extends org.apache.openjpa.lib.util.collections.LRUMap
implements SizedMap {
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/ReferenceHashMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/ReferenceHashMap.java
index 77d604d..cd49362 100644
--- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/ReferenceHashMap.java
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/ReferenceHashMap.java
@@ -18,6 +18,8 @@
*/
package org.apache.openjpa.lib.util;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap;
+
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
@@ -29,7 +31,7 @@ import java.io.ObjectOutputStream;
* @since 0.4.0
*/
public class ReferenceHashMap
- extends org.apache.commons.collections4.map.ReferenceMap
+ extends org.apache.openjpa.lib.util.collections.ReferenceMap
implements ReferenceMap, SizedMap {
@@ -124,9 +126,8 @@ public class ReferenceHashMap
private static class AccessibleEntry extends ReferenceEntry {
private final ReferenceHashMap parent;
- public AccessibleEntry(org.apache.commons.collections4.map.
- AbstractReferenceMap map, HashEntry next,
- int hashCode, Object key, Object value) {
+ public AccessibleEntry(AbstractReferenceMap map, HashEntry next,
+ int hashCode, Object key, Object value) {
super(map, next, hashCode, key, value);
parent = (ReferenceHashMap)map;
}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/ReferenceHashSet.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/ReferenceHashSet.java
index f35cb5d..42d8b45 100644
--- a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/ReferenceHashSet.java
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/ReferenceHashSet.java
@@ -24,8 +24,9 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
-import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
-import org.apache.commons.collections4.set.MapBackedSet;
+import org.apache.openjpa.lib.util.collections.AbstractReferenceMap;
+import org.apache.openjpa.lib.util.collections.MapBackedSet;
+import org.apache.openjpa.lib.util.collections.ReferenceMap;
/**
* A set whose values may be stored as weak or soft references.
@@ -51,12 +52,11 @@ public class ReferenceHashSet implements Set, Serializable {
/**
* Construct a set with the given reference type.
*/
- public ReferenceHashSet(ReferenceStrength refType) {
- if (refType == ReferenceStrength.HARD)
+ public ReferenceHashSet(AbstractReferenceMap.ReferenceStrength refType) {
+ if (refType == AbstractReferenceMap.ReferenceStrength.HARD)
_set = new HashSet();
else {
- _set = MapBackedSet.mapBackedSet(new org.apache.commons.
- collections4.map.ReferenceMap(refType, ReferenceStrength.HARD), DUMMY_VAL);
+ _set = MapBackedSet.mapBackedSet(new ReferenceMap(refType, AbstractReferenceMap.ReferenceStrength.HARD), DUMMY_VAL);
}
}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractCollectionDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractCollectionDecorator.java
new file mode 100644
index 0000000..2550586
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractCollectionDecorator.java
@@ -0,0 +1,189 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.function.Predicate;
+
+/**
+ * Decorates another <code>Collection</code> to provide additional behaviour.
+ * <p>
+ * Each method call made on this <code>Collection</code> is forwarded to the
+ * decorated <code>Collection</code>. This class is used as a framework on which
+ * to build to extensions such as synchronized and unmodifiable behaviour. The
+ * main advantage of decoration is that one decorator can wrap any implementation
+ * of <code>Collection</code>, whereas sub-classing requires a new class to be
+ * written for each implementation.
+ * </p>
+ * <p>
+ * 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.
+ * </p>
+ * <p>
+ * 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.
+ * </p>
+ *
+ * @param <E> the type of the elements in the collection
+ * @since 3.0
+ */
+public abstract class AbstractCollectionDecorator<E>
+ implements Collection<E>, Serializable {
+
+ /** Serialization version */
+ private static final long serialVersionUID = 6249888059822088500L;
+
+ /** The collection being decorated */
+ private Collection<E> collection;
+
+ /**
+ * Constructor only used in deserialization, do not use otherwise.
+ * @since 3.1
+ */
+ protected AbstractCollectionDecorator() {
+ super();
+ }
+
+ /**
+ * Constructor that wraps (not copies).
+ *
+ * @param coll the collection to decorate, must not be null
+ * @throws NullPointerException if the collection is null
+ */
+ protected AbstractCollectionDecorator(final Collection<E> coll) {
+ if (coll == null) {
+ throw new NullPointerException("Collection must not be null.");
+ }
+ this.collection = coll;
+ }
+
+ /**
+ * Gets the collection being decorated.
+ * All access to the decorated collection goes via this method.
+ *
+ * @return the decorated collection
+ */
+ protected Collection<E> decorated() {
+ return collection;
+ }
+
+ /**
+ * Sets the collection being decorated.
+ * <p>
+ * <b>NOTE:</b> this method should only be used during deserialization
+ *
+ * @param coll the decorated collection
+ */
+ protected void setCollection(final Collection<E> coll) {
+ this.collection = coll;
+ }
+
+ //-----------------------------------------------------------------------
+
+ @Override
+ public boolean add(final E object) {
+ return decorated().add(object);
+ }
+
+ @Override
+ public boolean addAll(final Collection<? extends E> 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<E> 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> 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<? super E> 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractDualBidiMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractDualBidiMap.java
new file mode 100644
index 0000000..89fba49
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractDualBidiMap.java
@@ -0,0 +1,824 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+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;
+
+/**
+ * Abstract {@link BidiMap} implemented using two maps.
+ * <p>
+ * An implementation can be written simply by implementing the
+ * {@link #createBidiMap(Map, Map, BidiMap)} method.
+ * </p>
+ *
+ * @param <K> the type of the keys in the map
+ * @param <V> the type of the values in the map
+ *
+ * @see DualHashBidiMap
+ * @see DualTreeBidiMap
+ * @since 3.0
+ */
+public abstract class AbstractDualBidiMap<K, V> implements BidiMap<K, V> {
+
+ /**
+ * Normal delegate map.
+ */
+ transient Map<K, V> normalMap;
+
+ /**
+ * Reverse delegate map.
+ */
+ transient Map<V, K> reverseMap;
+
+ /**
+ * Inverse view of this map.
+ */
+ transient BidiMap<V, K> inverseBidiMap = null;
+
+ /**
+ * View of the keys.
+ */
+ transient Set<K> keySet = null;
+
+ /**
+ * View of the values.
+ */
+ transient Set<V> values = null;
+
+ /**
+ * View of the entries.
+ */
+ transient Set<Entry<K, V>> entrySet = null;
+
+ /**
+ * Creates an empty map, initialised by <code>createMap</code>.
+ * <p>
+ * This constructor remains in place for deserialization.
+ * All other usage is deprecated in favour of
+ * {@link #AbstractDualBidiMap(Map, Map)}.
+ */
+ protected AbstractDualBidiMap() {
+ super();
+ }
+
+ /**
+ * Creates an empty map using the two maps specified as storage.
+ * <p>
+ * The two maps must be a matching pair, normal and reverse.
+ * They will typically both be empty.
+ * <p>
+ * 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[]</code> instance variable itself.
+ *
+ * @param normalMap the normal direction map
+ * @param reverseMap the reverse direction map
+ * @since 3.1
+ */
+ protected AbstractDualBidiMap(final Map<K, V> normalMap, final Map<V, K> reverseMap) {
+ super();
+ this.normalMap = normalMap;
+ this.reverseMap = reverseMap;
+ }
+
+ /**
+ * Constructs a map that decorates the specified maps,
+ * used by the subclass <code>createBidiMap</code> implementation.
+ *
+ * @param normalMap the normal direction map
+ * @param reverseMap the reverse direction map
+ * @param inverseBidiMap the inverse BidiMap
+ */
+ protected AbstractDualBidiMap(final Map<K, V> normalMap, final Map<V, K> reverseMap,
+ final BidiMap<V, K> inverseBidiMap) {
+ super();
+ this.normalMap = normalMap;
+ this.reverseMap = reverseMap;
+ this.inverseBidiMap = inverseBidiMap;
+ }
+
+ /**
+ * Creates a new instance of the subclass.
+ *
+ * @param normalMap the normal direction map
+ * @param reverseMap the reverse direction map
+ * @param inverseMap this map, which is the inverse in the new map
+ * @return the inverse map
+ */
+ protected abstract BidiMap<V, K> createBidiMap(Map<V, K> normalMap, Map<K, V> reverseMap, BidiMap<K, V> 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<? extends K, ? extends V> map) {
+ for (final Entry<? extends K, ? extends V> 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</code> over the map.
+ * The iterator implements <code>ResetableMapIterator</code>.
+ * This implementation relies on the entrySet iterator.
+ * <p>
+ * The setValue() methods only allow a new value to be set.
+ * If the value being set is already in the map, an IllegalArgumentException
+ * is thrown (as setValue cannot change the size of the map).
+ *
+ * @return a map iterator
+ */
+ @Override
+ public MapIterator<K, V> 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<V, K> 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<K> 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<K> createKeySetIterator(final Iterator<K> 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<V> 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<V> createValuesIterator(final Iterator<V> 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.
+ * <p>
+ * 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<Entry<K, V>> 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<Entry<K, V>> createEntrySetIterator(final Iterator<Entry<K, V>> iterator) {
+ return new EntrySetIterator<>(iterator, this);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Inner class View.
+ */
+ protected static abstract class View<K, V, E> extends AbstractCollectionDecorator<E> {
+
+ /** Generated serial version ID. */
+ private static final long serialVersionUID = 4621510560119690639L;
+
+ /** The parent map */
+ protected final AbstractDualBidiMap<K, V> parent;
+
+ /**
+ * Constructs a new view of the BidiMap.
+ *
+ * @param coll the collection view being decorated
+ * @param parent the parent BidiMap
+ */
+ protected View(final Collection<E> coll, final AbstractDualBidiMap<K, V> 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(Predicate<? super E> 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;
+ final Iterator<?> it = coll.iterator();
+ while (it.hasNext()) {
+ modified |= remove(it.next());
+ }
+ return modified;
+ }
+
+ /**
+ * {@inheritDoc}
+ * <p>
+ * This implementation iterates over the elements of this bidi map, checking each element in
+ * turn to see if it's contained in <code>coll</code>. 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</code> 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<E> it = iterator();
+ while (it.hasNext()) {
+ if (coll.contains(it.next()) == false) {
+ it.remove();
+ modified = true;
+ }
+ }
+ return modified;
+ }
+
+ @Override
+ public void clear() {
+ parent.clear();
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Inner class KeySet.
+ */
+ protected static class KeySet<K> extends View<K, Object, K> implements Set<K> {
+
+ /** Serialization version */
+ private static final long serialVersionUID = -7107935777385040694L;
+
+ /**
+ * Constructs a new view of the BidiMap.
+ *
+ * @param parent the parent BidiMap
+ */
+ @SuppressWarnings("unchecked")
+ protected KeySet(final AbstractDualBidiMap<K, ?> parent) {
+ super(parent.normalMap.keySet(), (AbstractDualBidiMap<K, Object>) parent);
+ }
+
+ @Override
+ public Iterator<K> 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<K> extends AbstractIteratorDecorator<K> {
+
+ /** The parent map */
+ protected final AbstractDualBidiMap<K, ?> parent;
+
+ /** The last returned key */
+ protected K lastKey = null;
+
+ /** Whether remove is allowed at present */
+ protected boolean canRemove = false;
+
+ /**
+ * Constructor.
+ * @param iterator the iterator to decorate
+ * @param parent the parent map
+ */
+ protected KeySetIterator(final Iterator<K> iterator, final AbstractDualBidiMap<K, ?> parent) {
+ super(iterator);
+ this.parent = parent;
+ }
+
+ @Override
+ public K next() {
+ lastKey = super.next();
+ canRemove = true;
+ return lastKey;
+ }
+
+ @Override
+ public void remove() {
+ if (canRemove == false) {
+ throw new IllegalStateException("Iterator remove() can only be called once after next()");
+ }
+ final Object value = parent.normalMap.get(lastKey);
+ super.remove();
+ parent.reverseMap.remove(value);
+ lastKey = null;
+ canRemove = false;
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Inner class Values.
+ */
+ protected static class Values<V> extends View<Object, V, V> implements Set<V> {
+
+ /** Serialization version */
+ private static final long serialVersionUID = 4023777119829639864L;
+
+ /**
+ * Constructs a new view of the BidiMap.
+ *
+ * @param parent the parent BidiMap
+ */
+ @SuppressWarnings("unchecked")
+ protected Values(final AbstractDualBidiMap<?, V> parent) {
+ super(parent.normalMap.values(), (AbstractDualBidiMap<Object, V>) parent);
+ }
+
+ @Override
+ public Iterator<V> 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<V> extends AbstractIteratorDecorator<V> {
+
+ /** The parent map */
+ protected final AbstractDualBidiMap<Object, V> parent;
+
+ /** The last returned value */
+ protected V lastValue = null;
+
+ /** Whether remove is allowed at present */
+ protected boolean canRemove = false;
+
+ /**
+ * Constructor.
+ * @param iterator the iterator to decorate
+ * @param parent the parent map
+ */
+ @SuppressWarnings("unchecked")
+ protected ValuesIterator(final Iterator<V> iterator, final AbstractDualBidiMap<?, V> parent) {
+ super(iterator);
+ this.parent = (AbstractDualBidiMap<Object, V>) parent;
+ }
+
+ @Override
+ public V next() {
+ lastValue = super.next();
+ canRemove = true;
+ return lastValue;
+ }
+
+ @Override
+ public void remove() {
+ if (canRemove == false) {
+ throw new IllegalStateException("Iterator remove() can only be called once after next()");
+ }
+ super.remove(); // removes from maps[0]
+ parent.reverseMap.remove(lastValue);
+ lastValue = null;
+ canRemove = false;
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Inner class EntrySet.
+ */
+ protected static class EntrySet<K, V> extends View<K, V, Entry<K, V>> implements Set<Entry<K, V>> {
+
+ /** Serialization version */
+ private static final long serialVersionUID = 4040410962603292348L;
+
+ /**
+ * Constructs a new view of the BidiMap.
+ *
+ * @param parent the parent BidiMap
+ */
+ protected EntrySet(final AbstractDualBidiMap<K, V> parent) {
+ super(parent.normalMap.entrySet(), parent);
+ }
+
+ @Override
+ public Iterator<Entry<K, V>> iterator() {
+ return parent.createEntrySetIterator(super.iterator());
+ }
+
+ @Override
+ public boolean remove(final Object obj) {
+ if (obj instanceof Map.Entry == false) {
+ return false;
+ }
+ final Entry<?, ?> entry = (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<K, V> extends AbstractIteratorDecorator<Entry<K, V>> {
+
+ /** The parent map */
+ protected final AbstractDualBidiMap<K, V> parent;
+
+ /** The last returned entry */
+ protected Entry<K, V> last = null;
+
+ /** Whether remove is allowed at present */
+ protected boolean canRemove = false;
+
+ /**
+ * Constructor.
+ * @param iterator the iterator to decorate
+ * @param parent the parent map
+ */
+ protected EntrySetIterator(final Iterator<Entry<K, V>> iterator, final AbstractDualBidiMap<K, V> parent) {
+ super(iterator);
+ this.parent = parent;
+ }
+
+ @Override
+ public Entry<K, V> next() {
+ last = new MapEntry<>(super.next(), parent);
+ canRemove = true;
+ return last;
+ }
+
+ @Override
+ public void remove() {
+ if (canRemove == false) {
+ throw new IllegalStateException("Iterator remove() can only be called once after next()");
+ }
+ // store value as remove may change the entry in the decorator (eg.TreeMap)
+ final Object value = last.getValue();
+ super.remove();
+ parent.reverseMap.remove(value);
+ last = null;
+ canRemove = false;
+ }
+ }
+
+ /**
+ * Inner class MapEntry.
+ */
+ protected static class MapEntry<K, V> extends AbstractMapEntryDecorator<K, V> {
+
+ /** The parent map */
+ protected final AbstractDualBidiMap<K, V> parent;
+
+ /**
+ * Constructor.
+ * @param entry the entry to decorate
+ * @param parent the parent map
+ */
+ protected MapEntry(final Entry<K, V> entry, final AbstractDualBidiMap<K, V> parent) {
+ super(entry);
+ this.parent = parent;
+ }
+
+ @Override
+ public V setValue(final V value) {
+ final K key = MapEntry.this.getKey();
+ if (parent.reverseMap.containsKey(value) &&
+ parent.reverseMap.get(value) != key) {
+ throw new IllegalArgumentException(
+ "Cannot use setValue() when the object being set is already in the map");
+ }
+ parent.put(key, value);
+ return super.setValue(value);
+ }
+ }
+
+ /**
+ * Inner class MapIterator.
+ */
+ protected static class BidiMapIterator<K, V> implements MapIterator<K, V>, ResettableIterator<K> {
+
+ /** The parent map */
+ protected final AbstractDualBidiMap<K, V> parent;
+
+ /** The iterator being wrapped */
+ protected Iterator<Entry<K, V>> iterator;
+
+ /** The last returned entry */
+ protected Entry<K, V> last = null;
+
+ /** Whether remove is allowed at present */
+ protected boolean canRemove = false;
+
+ /**
+ * Constructor.
+ * @param parent the parent map
+ */
+ protected BidiMapIterator(final AbstractDualBidiMap<K, V> parent) {
+ super();
+ 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 == false) {
+ throw new IllegalStateException("Iterator remove() can only be called once after next()");
+ }
+ // store value as remove may change the entry in the decorator (eg.TreeMap)
+ final V value = last.getValue();
+ iterator.remove();
+ parent.reverseMap.remove(value);
+ last = null;
+ canRemove = false;
+ }
+
+ @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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractEmptyIterator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractEmptyIterator.java
new file mode 100644
index 0000000..d7c5910
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractEmptyIterator.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.NoSuchElementException;
+
+/**
+ * Provides an implementation of an empty iterator.
+ *
+ * @since 3.1
+ */
+abstract class AbstractEmptyIterator<E> {
+
+ /**
+ * Constructor.
+ */
+ protected AbstractEmptyIterator() {
+ super();
+ }
+
+ public boolean hasNext() {
+ return false;
+ }
+
+ public E next() {
+ throw new NoSuchElementException("Iterator contains no elements");
+ }
+
+ public boolean hasPrevious() {
+ return false;
+ }
+
+ public E previous() {
+ throw new NoSuchElementException("Iterator contains no elements");
+ }
+
+ public int nextIndex() {
+ return 0;
+ }
+
+ public int previousIndex() {
+ return -1;
+ }
+
+ public void add(final E obj) {
+ throw new UnsupportedOperationException("add() not supported for empty Iterator");
+ }
+
+ public void set(final E obj) {
+ throw new IllegalStateException("Iterator contains no elements");
+ }
+
+ public void remove() {
+ throw new IllegalStateException("Iterator contains no elements");
+ }
+
+ public void reset() {
+ // do nothing
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractEmptyMapIterator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractEmptyMapIterator.java
new file mode 100644
index 0000000..cf7684b
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractEmptyMapIterator.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+/**
+ * Provides an implementation of an empty map iterator.
+ *
+ * @param <K> the type of keys
+ * @param <V> the type of mapped values
+ * @since 4.0
+ */
+public abstract class AbstractEmptyMapIterator<K, V> extends AbstractEmptyIterator<K> {
+
+ /**
+ * Create a new AbstractEmptyMapIterator.
+ */
+ public AbstractEmptyMapIterator() {
+ super();
+ }
+
+ public K getKey() {
+ throw new IllegalStateException("Iterator contains no elements");
+ }
+
+ public V getValue() {
+ throw new IllegalStateException("Iterator contains no elements");
+ }
+
+ public V setValue(final V value) {
+ throw new IllegalStateException("Iterator contains no elements");
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractHashedMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractHashedMap.java
new file mode 100644
index 0000000..b00dcc0
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractHashedMap.java
@@ -0,0 +1,1395 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.AbstractCollection;
+import java.util.AbstractMap;
+import java.util.AbstractSet;
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+
+/**
+ * An abstract implementation of a hash-based map which provides numerous points for
+ * subclasses to override.
+ * <p>
+ * This class implements all the features necessary for a subclass hash-based map.
+ * Key-value entries are stored in instances of the <code>HashEntry</code> 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.
+ * <p>
+ * Overridable methods are provided to change the default hashing behaviour, and
+ * to change how entries are added to and removed from the map. Hopefully, all you
+ * need for unusual subclasses is here.
+ * <p>
+ * 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 <K> the type of the keys in this map
+ * @param <V> the type of the values in this map
+ * @since 3.0
+ */
+public class AbstractHashedMap<K, V> extends AbstractMap<K, V> implements IterableMap<K, V> {
+
+ 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<K, V>[] data;
+ /** Size at which to rehash */
+ transient int threshold;
+ /** Modification count for iterators */
+ transient int modCount;
+ /** Entry set */
+ transient EntrySet<K, V> entrySet;
+ /** Key set */
+ transient KeySet<K> keySet;
+ /** Values */
+ transient Values<V> values;
+
+ /**
+ * Constructor only used in deserialization, do not use otherwise.
+ */
+ protected AbstractHashedMap() {
+ super();
+ }
+
+ /**
+ * Constructor which performs no validation on the passed in parameters.
+ *
+ * @param initialCapacity the initial capacity, must be a power of two
+ * @param loadFactor the load factor, must be > 0.0f and generally < 1.0f
+ * @param threshold the threshold, must be sensible
+ */
+ @SuppressWarnings("unchecked")
+ protected AbstractHashedMap(final int initialCapacity, final float loadFactor, final int threshold) {
+ super();
+ this.loadFactor = loadFactor;
+ this.data = new HashEntry[initialCapacity];
+ this.threshold = threshold;
+ init();
+ }
+
+ /**
+ * Constructs a new, empty map with the specified initial capacity and
+ * default load factor.
+ *
+ * @param initialCapacity the initial capacity
+ * @throws IllegalArgumentException if the initial capacity is negative
+ */
+ protected AbstractHashedMap(final int initialCapacity) {
+ this(initialCapacity, DEFAULT_LOAD_FACTOR);
+ }
+
+ /**
+ * Constructs a new, empty map with the specified initial capacity and
+ * load factor.
+ *
+ * @param initialCapacity the initial capacity
+ * @param loadFactor the load factor
+ * @throws IllegalArgumentException if the initial capacity is negative
+ * @throws IllegalArgumentException if the load factor is less than or equal to zero
+ */
+ @SuppressWarnings("unchecked")
+ protected AbstractHashedMap(int initialCapacity, final float loadFactor) {
+ super();
+ if (initialCapacity < 0) {
+ throw new IllegalArgumentException("Initial capacity must be a non negative number");
+ }
+ if (loadFactor <= 0.0f || Float.isNaN(loadFactor)) {
+ throw new IllegalArgumentException("Load factor must be greater than 0");
+ }
+ this.loadFactor = loadFactor;
+ initialCapacity = calculateNewCapacity(initialCapacity);
+ this.threshold = calculateThreshold(initialCapacity, loadFactor);
+ this.data = new HashEntry[initialCapacity];
+ init();
+ }
+
+ /**
+ * Constructor copying elements from another map.
+ *
+ * @param map the map to copy
+ * @throws NullPointerException if the map is null
+ */
+ protected AbstractHashedMap(final Map<? extends K, ? extends V> map) {
+ this(Math.max(2 * map.size(), DEFAULT_CAPACITY), DEFAULT_LOAD_FACTOR);
+ _putAll(map);
+ }
+
+ /**
+ * Initialise subclasses during construction, cloning or deserialization.
+ */
+ protected void init() {
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the value mapped to the key specified.
+ *
+ * @param key the key
+ * @return the mapped value, null if no match
+ */
+ @Override
+ public V get(Object key) {
+ key = convertKey(key);
+ final int hashCode = hash(key);
+ HashEntry<K, V> 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<K, V> 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<K, V> element : data) {
+ HashEntry<K, V> entry = element;
+ while (entry != null) {
+ if (entry.getValue() == null) {
+ return true;
+ }
+ entry = entry.next;
+ }
+ }
+ } else {
+ for (final HashEntry<K, V> element : data) {
+ HashEntry<K, V> 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<K, V> 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.
+ * <p>
+ * 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<? extends K, ? extends V> map) {
+ _putAll(map);
+ }
+
+ /**
+ * Puts all the values from the specified map into this map.
+ * <p>
+ * This implementation iterates around the specified map and
+ * uses {@link #put(Object, Object)}.
+ * <p>
+ * It is private to allow the constructor to still call it
+ * even when putAll is overriden.
+ *
+ * @param map the map to add
+ * @throws NullPointerException if the map is null
+ */
+ private void _putAll(final Map<? extends K, ? extends V> map) {
+ final int mapSize = map.size();
+ if (mapSize == 0) {
+ return;
+ }
+ final int newSize = (int) ((size + mapSize) / loadFactor + 1);
+ ensureCapacity(calculateNewCapacity(newSize));
+ for (final Entry<? extends K, ? extends V> 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<K, V> entry = data[index];
+ HashEntry<K, V> 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<K, V>[] data = this.data;
+ for (int i = data.length - 1; i >= 0; i--) {
+ data[i] = null;
+ }
+ size = 0;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Converts input keys to another object for storage in the map.
+ * This implementation masks nulls.
+ * Subclasses can override this to perform alternate key conversions.
+ * <p>
+ * 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</code>
+ * @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()</code>
+ * @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.
+ * <p>
+ * 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<K, V> getEntry(Object key) {
+ key = convertKey(key);
+ final int hashCode = hash(key);
+ HashEntry<K, V> 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.
+ * <p>
+ * This implementation calls <code>setValue()</code> 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<K, V> entry, final V newValue) {
+ entry.setValue(newValue);
+ }
+
+ /**
+ * Reuses an existing key-value mapping, storing completely new data.
+ * <p>
+ * 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<K, V> 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.
+ * <p>
+ * This implementation calls <code>createEntry()</code>, <code>addEntry()</code>
+ * and <code>checkCapacity()</code>.
+ * It also handles changes to <code>modCount</code> and <code>size</code>.
+ * 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<K, V> entry = createEntry(data[hashIndex], hashCode, key, value);
+ addEntry(entry, hashIndex);
+ size++;
+ checkCapacity();
+ }
+
+ /**
+ * Creates an entry to store the key-value data.
+ * <p>
+ * 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<K, V> createEntry(final HashEntry<K, V> next, final int hashCode, final K key, final V value) {
+ return new HashEntry<>(next, hashCode, convertKey(key), value);
+ }
+
+ /**
+ * Adds an entry into this map.
+ * <p>
+ * 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<K, V> entry, final int hashIndex) {
+ data[hashIndex] = entry;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Removes a mapping from the map.
+ * <p>
+ * This implementation calls <code>removeEntry()</code> and <code>destroyEntry()</code>.
+ * It also handles changes to <code>modCount</code> and <code>size</code>.
+ * 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<K, V> entry, final int hashIndex, final HashEntry<K, V> previous) {
+ modCount++;
+ removeEntry(entry, hashIndex, previous);
+ size--;
+ destroyEntry(entry);
+ }
+
+ /**
+ * Removes an entry from the chain stored in a particular index.
+ * <p>
+ * 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<K, V> entry, final int hashIndex, final HashEntry<K, V> previous) {
+ if (previous == null) {
+ data[hashIndex] = entry.next;
+ } else {
+ previous.next = entry.next;
+ }
+ }
+
+ /**
+ * Kills an entry ready for the garbage collector.
+ * <p>
+ * 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<K, V> entry) {
+ entry.next = null;
+ entry.key = null;
+ entry.value = null;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Checks the capacity of the map and enlarges it if necessary.
+ * <p>
+ * 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<K, V> oldEntries[] = data;
+ final HashEntry<K, V> newEntries[] = new HashEntry[newCapacity];
+
+ modCount++;
+ for (int i = oldCapacity - 1; i >= 0; i--) {
+ HashEntry<K, V> entry = oldEntries[i];
+ if (entry != null) {
+ oldEntries[i] = null; // gc
+ do {
+ final HashEntry<K, V> 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</code> field from a <code>HashEntry</code>.
+ * Used in subclasses that have no visibility of the field.
+ *
+ * @param entry the entry to query, must not be null
+ * @return the <code>next</code> field of the entry
+ * @throws NullPointerException if the entry is null
+ * @since 3.1
+ */
+ protected HashEntry<K, V> entryNext(final HashEntry<K, V> entry) {
+ return entry.next;
+ }
+
+ /**
+ * Gets the <code>hashCode</code> field from a <code>HashEntry</code>.
+ * Used in subclasses that have no visibility of the field.
+ *
+ * @param entry the entry to query, must not be null
+ * @return the <code>hashCode</code> field of the entry
+ * @throws NullPointerException if the entry is null
+ * @since 3.1
+ */
+ protected int entryHashCode(final HashEntry<K, V> entry) {
+ return entry.hashCode;
+ }
+
+ /**
+ * Gets the <code>key</code> field from a <code>HashEntry</code>.
+ * Used in subclasses that have no visibility of the field.
+ *
+ * @param entry the entry to query, must not be null
+ * @return the <code>key</code> field of the entry
+ * @throws NullPointerException if the entry is null
+ * @since 3.1
+ */
+ protected K entryKey(final HashEntry<K, V> entry) {
+ return entry.getKey();
+ }
+
+ /**
+ * Gets the <code>value</code> field from a <code>HashEntry</code>.
+ * Used in subclasses that have no visibility of the field.
+ *
+ * @param entry the entry to query, must not be null
+ * @return the <code>value</code> field of the entry
+ * @throws NullPointerException if the entry is null
+ * @since 3.1
+ */
+ protected V entryValue(final HashEntry<K, V> entry) {
+ return entry.getValue();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets an iterator over the map.
+ * Changes made to the iterator affect this map.
+ * <p>
+ * 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<K, V> mapIterator() {
+ if (size == 0) {
+ return EmptyMapIterator.<K, V>emptyMapIterator();
+ }
+ return new HashMapIterator<>(this);
+ }
+
+ /**
+ * MapIterator implementation.
+ */
+ protected static class HashMapIterator<K, V> extends HashIterator<K, V> implements MapIterator<K, V> {
+
+ protected HashMapIterator(final AbstractHashedMap<K, V> parent) {
+ super(parent);
+ }
+
+ @Override
+ public K next() {
+ return super.nextEntry().getKey();
+ }
+
+ @Override
+ public K getKey() {
+ final HashEntry<K, V> current = currentEntry();
+ if (current == null) {
+ throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID);
+ }
+ return current.getKey();
+ }
+
+ @Override
+ public V getValue() {
+ final HashEntry<K, V> current = currentEntry();
+ if (current == null) {
+ throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID);
+ }
+ return current.getValue();
+ }
+
+ @Override
+ public V setValue(final V value) {
+ final HashEntry<K, V> 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<Entry<K, V>> 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<Entry<K, V>> createEntrySetIterator() {
+ if (size() == 0) {
+ return EmptyIterator.<Entry<K, V>>emptyIterator();
+ }
+ return new EntrySetIterator<>(this);
+ }
+
+ /**
+ * EntrySet implementation.
+ */
+ protected static class EntrySet<K, V> extends AbstractSet<Entry<K, V>> {
+ /** The parent map */
+ private final AbstractHashedMap<K, V> parent;
+
+ protected EntrySet(final AbstractHashedMap<K, V> parent) {
+ super();
+ this.parent = parent;
+ }
+
+ @Override
+ public int size() {
+ return parent.size();
+ }
+
+ @Override
+ public void clear() {
+ parent.clear();
+ }
+
+ @Override
+ public boolean contains(final Object entry) {
+ if (entry instanceof Map.Entry) {
+ final Entry<?, ?> e = (Entry<?, ?>) entry;
+ final Entry<K, V> match = parent.getEntry(e.getKey());
+ return match != null && match.equals(e);
+ }
+ return false;
+ }
+
+ @Override
+ public boolean remove(final Object obj) {
+ if (obj instanceof Map.Entry == false) {
+ return false;
+ }
+ if (contains(obj) == false) {
+ return false;
+ }
+ final Entry<?, ?> entry = (Entry<?, ?>) obj;
+ parent.remove(entry.getKey());
+ return true;
+ }
+
+ @Override
+ public Iterator<Entry<K, V>> iterator() {
+ return parent.createEntrySetIterator();
+ }
+ }
+
+ /**
+ * EntrySet iterator.
+ */
+ protected static class EntrySetIterator<K, V> extends HashIterator<K, V> implements Iterator<Entry<K, V>> {
+
+ protected EntrySetIterator(final AbstractHashedMap<K, V> parent) {
+ super(parent);
+ }
+
+ @Override
+ public Entry<K, V> 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<K> 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<K> createKeySetIterator() {
+ if (size() == 0) {
+ return EmptyIterator.<K>emptyIterator();
+ }
+ return new KeySetIterator<>(this);
+ }
+
+ /**
+ * KeySet implementation.
+ */
+ protected static class KeySet<K> extends AbstractSet<K> {
+ /** The parent map */
+ private final AbstractHashedMap<K, ?> parent;
+
+ protected KeySet(final AbstractHashedMap<K, ?> parent) {
+ super();
+ this.parent = parent;
+ }
+
+ @Override
+ public int size() {
+ return parent.size();
+ }
+
+ @Override
+ public void clear() {
+ parent.clear();
+ }
+
+ @Override
+ public boolean contains(final Object key) {
+ return parent.containsKey(key);
+ }
+
+ @Override
+ public boolean remove(final Object key) {
+ final boolean result = parent.containsKey(key);
+ parent.remove(key);
+ return result;
+ }
+
+ @Override
+ public Iterator<K> iterator() {
+ return parent.createKeySetIterator();
+ }
+ }
+
+ /**
+ * KeySet iterator.
+ */
+ protected static class KeySetIterator<K> extends HashIterator<K, Object> implements Iterator<K> {
+
+ @SuppressWarnings("unchecked")
+ protected KeySetIterator(final AbstractHashedMap<K, ?> parent) {
+ super((AbstractHashedMap<K, Object>) 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<V> 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<V> createValuesIterator() {
+ if (size() == 0) {
+ return EmptyIterator.<V>emptyIterator();
+ }
+ return new ValuesIterator<>(this);
+ }
+
+ /**
+ * Values implementation.
+ */
+ protected static class Values<V> extends AbstractCollection<V> {
+ /** The parent map */
+ private final AbstractHashedMap<?, V> parent;
+
+ protected Values(final AbstractHashedMap<?, V> parent) {
+ super();
+ this.parent = parent;
+ }
+
+ @Override
+ public int size() {
+ return parent.size();
+ }
+
+ @Override
+ public void clear() {
+ parent.clear();
+ }
+
+ @Override
+ public boolean contains(final Object value) {
+ return parent.containsValue(value);
+ }
+
+ @Override
+ public Iterator<V> iterator() {
+ return parent.createValuesIterator();
+ }
+ }
+
+ /**
+ * Values iterator.
+ */
+ protected static class ValuesIterator<V> extends HashIterator<Object, V> implements Iterator<V> {
+
+ @SuppressWarnings("unchecked")
+ protected ValuesIterator(final AbstractHashedMap<?, V> parent) {
+ super((AbstractHashedMap<Object, V>) parent);
+ }
+
+ @Override
+ public V next() {
+ return super.nextEntry().getValue();
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * HashEntry used to store the data.
+ * <p>
+ * If you subclass <code>AbstractHashedMap</code> but not <code>HashEntry</code>
+ * then you will not be able to access the protected fields.
+ * The <code>entryXxx()</code> methods on <code>AbstractHashedMap</code> exist
+ * to provide the necessary access.
+ */
+ protected static class HashEntry<K, V> implements Entry<K, V>, KeyValue<K, V> {
+ /** The next entry in the hash chain */
+ protected HashEntry<K, V> next;
+ /** The hash code of the key */
+ protected int hashCode;
+ /** The key */
+ protected Object key;
+ /** The value */
+ protected Object value;
+
+ protected HashEntry(final HashEntry<K, V> next, final int hashCode, final Object key, final V value) {
+ super();
+ 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 == false) {
+ return false;
+ }
+ final Entry<?, ?> other = (Entry<?, ?>) obj;
+ return
+ (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) &&
+ (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue()));
+ }
+
+ @Override
+ public int hashCode() {
+ return (getKey() == null ? 0 : getKey().hashCode()) ^
+ (getValue() == null ? 0 : getValue().hashCode());
+ }
+
+ @Override
+ public String toString() {
+ return new StringBuilder().append(getKey()).append('=').append(getValue()).toString();
+ }
+ }
+
+ /**
+ * Base Iterator
+ */
+ protected static abstract class HashIterator<K, V> {
+
+ /** The parent map */
+ private final AbstractHashedMap<K, V> parent;
+ /** The current index into the array of buckets */
+ private int hashIndex;
+ /** The last returned entry */
+ private HashEntry<K, V> last;
+ /** The next entry */
+ private HashEntry<K, V> next;
+ /** The modification count expected */
+ private int expectedModCount;
+
+ protected HashIterator(final AbstractHashedMap<K, V> parent) {
+ super();
+ this.parent = parent;
+ final HashEntry<K, V>[] data = parent.data;
+ int i = data.length;
+ HashEntry<K, V> 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<K, V> nextEntry() {
+ if (parent.modCount != expectedModCount) {
+ throw new ConcurrentModificationException();
+ }
+ final HashEntry<K, V> newCurrent = next;
+ if (newCurrent == null) {
+ throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY);
+ }
+ final HashEntry<K, V>[] data = parent.data;
+ int i = hashIndex;
+ HashEntry<K, V> n = newCurrent.next;
+ while (n == null && i > 0) {
+ n = data[--i];
+ }
+ next = n;
+ hashIndex = i;
+ last = newCurrent;
+ return newCurrent;
+ }
+
+ protected HashEntry<K, V> 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()</code> is used.
+ * <p>
+ * Serialization is not one of the JDK's nicest topics. Normal serialization will
+ * initialise the superclass before the subclass. Sometimes however, this isn't
+ * what you want, as in this case the <code>put()</code> method on read can be
+ * affected by subclass state.
+ * <p>
+ * 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()</code> of the first serializable subclass.
+ * <p>
+ * Subclasses may override if they have a specific field that must be present
+ * on read before this implementation will work. Generally, the read determines
+ * what must be serialized here, if anything.
+ *
+ * @param out the output stream
+ * @throws IOException if an error occurs while writing tothe stream
+ */
+ protected void doWriteObject(final ObjectOutputStream out) throws IOException {
+ out.writeFloat(loadFactor);
+ out.writeInt(data.length);
+ out.writeInt(size);
+ for (final MapIterator<K, V> 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()</code> is used.
+ * <p>
+ * Serialization is not one of the JDK's nicest topics. Normal serialization will
+ * initialise the superclass before the subclass. Sometimes however, this isn't
+ * what you want, as in this case the <code>put()</code> method on read can be
+ * affected by subclass state.
+ * <p>
+ * 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()</code> of the first serializable subclass.
+ * <p>
+ * Subclasses may override if the subclass has a specific field that must be present
+ * before <code>put()</code> or <code>calculateThreshold()</code> 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.
+ * <p>
+ * To implement <code>clone()</code>, a subclass must implement the
+ * <code>Cloneable</code> interface and make this method public.
+ *
+ * @return a shallow clone
+ * @throws InternalError if {@link AbstractMap#clone()} failed
+ */
+ @Override
+ @SuppressWarnings("unchecked")
+ protected AbstractHashedMap<K, V> clone() {
+ try {
+ final AbstractHashedMap<K, V> cloned = (AbstractHashedMap<K, V>) super.clone();
+ cloned.data = new HashEntry[data.length];
+ cloned.entrySet = null;
+ cloned.keySet = null;
+ cloned.values = null;
+ cloned.modCount = 0;
+ cloned.size = 0;
+ cloned.init();
+ cloned.putAll(this);
+ return cloned;
+ } catch (final CloneNotSupportedException ex) {
+ throw new InternalError();
+ }
+ }
+
+ /**
+ * Compares this map with another.
+ *
+ * @param obj the object to compare to
+ * @return true if equal
+ */
+ @Override
+ public boolean equals(final Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (obj instanceof Map == false) {
+ return false;
+ }
+ final Map<?,?> map = (Map<?,?>) obj;
+ if (map.size() != size()) {
+ return false;
+ }
+ final MapIterator<?,?> it = mapIterator();
+ try {
+ while (it.hasNext()) {
+ final Object key = it.next();
+ final Object value = it.getValue();
+ if (value == null) {
+ if (map.get(key) != null || map.containsKey(key) == false) {
+ return false;
+ }
+ } else {
+ if (value.equals(map.get(key)) == false) {
+ return false;
+ }
+ }
+ }
+ } catch (final ClassCastException ignored) {
+ return false;
+ } catch (final NullPointerException ignored) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Gets the standard Map hashCode.
+ *
+ * @return the hash code defined in the Map interface
+ */
+ @Override
+ public int hashCode() {
+ int total = 0;
+ final Iterator<Entry<K, V>> it = createEntrySetIterator();
+ while (it.hasNext()) {
+ total += it.next().hashCode();
+ }
+ return total;
+ }
+
+ /**
+ * Gets the map as a String.
+ *
+ * @return a string version of the map
+ */
+ @Override
+ public String toString() {
+ if (size() == 0) {
+ return "{}";
+ }
+ final StringBuilder buf = new StringBuilder(32 * size());
+ buf.append('{');
+
+ final MapIterator<K, V> it = mapIterator();
+ boolean hasNext = it.hasNext();
+ while (hasNext) {
+ final K key = it.next();
+ final V value = it.getValue();
+ buf.append(key == this ? "(this Map)" : key)
+ .append('=')
+ .append(value == this ? "(this Map)" : value);
+
+ hasNext = it.hasNext();
+ if (hasNext) {
+ buf.append(',').append(' ');
+ }
+ }
+
+ buf.append('}');
+ return buf.toString();
+ }
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractIterableMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractIterableMap.java
new file mode 100644
index 0000000..ff3d1ca
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractIterableMap.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+/**
+ * Provide a basic {@link IterableMap} implementation.
+ *
+ * @param <K> the type of the keys in this map
+ * @param <V> the type of the values in this map
+ * @since 4.0
+ */
+public abstract class AbstractIterableMap<K, V> implements IterableMap<K, V> {
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public MapIterator<K, V> mapIterator() {
+ return new EntrySetToMapIteratorAdapter<>(entrySet());
+ }
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractIteratorDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractIteratorDecorator.java
new file mode 100644
index 0000000..06309e1
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractIteratorDecorator.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Iterator;
+
+/**
+ * Provides basic behaviour for decorating an iterator with extra functionality.
+ * <p>
+ * All methods are forwarded to the decorated iterator.
+ *
+ * @since 3.0
+ */
+public abstract class AbstractIteratorDecorator<E> extends AbstractUntypedIteratorDecorator<E, E> {
+
+ //-----------------------------------------------------------------------
+ /**
+ * 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<E> iterator) {
+ super(iterator);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public E next() {
+ return getIterator().next();
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractKeyValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractKeyValue.java
new file mode 100644
index 0000000..0ce8020
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractKeyValue.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+/**
+ * Abstract pair class to assist with creating <code>KeyValue</code>
+ * and {@link java.util.Map.Entry Map.Entry} implementations.
+ *
+ * @param <K> the type of keys
+ * @param <V> the type of values
+ * @since 3.0
+ */
+public abstract class AbstractKeyValue<K, V> implements KeyValue<K, V> {
+
+ /** The key */
+ private K key;
+ /** The value */
+ private V value;
+
+ /**
+ * Constructs a new pair with the specified key and given value.
+ *
+ * @param key the key for the entry, may be null
+ * @param value the value for the entry, may be null
+ */
+ protected AbstractKeyValue(final K key, final V value) {
+ super();
+ this.key = key;
+ this.value = value;
+ }
+
+ /**
+ * Gets the key from the pair.
+ *
+ * @return the key
+ */
+ @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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractLinkedMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractLinkedMap.java
new file mode 100644
index 0000000..adf161b
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractLinkedMap.java
@@ -0,0 +1,620 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+/**
+ * An abstract implementation of a hash-based map that links entries to create an
+ * ordered map and which provides numerous points for subclasses to override.
+ * <p>
+ * 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</code> 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.
+ * </p>
+ * <p>
+ * Overridable methods are provided to change the default hashing behaviour, and
+ * to change how entries are added to and removed from the map. Hopefully, all you
+ * need for unusual subclasses is here.
+ * </p>
+ * <p>
+ * This implementation maintains order by original insertion, but subclasses
+ * may work differently. The <code>OrderedMap</code> interface is implemented
+ * to provide access to bidirectional iteration and extra convenience methods.
+ * </p>
+ * <p>
+ * The <code>orderedMapIterator()</code> method provides direct access to a
+ * bidirectional iterator. The iterators from the other views can also be cast
+ * to <code>OrderedIterator</code> if required.
+ * </p>
+ * <p>
+ * All the available iterators can be reset back to the start by casting to
+ * <code>ResettableIterator</code> and calling <code>reset()</code>.
+ * </p>
+ * <p>
+ * The implementation is also designed to be subclassed, with lots of useful
+ * methods exposed.
+ * </p>
+ *
+ * @param <K> the type of the keys in this map
+ * @param <V> the type of the values in this map
+ * @since 3.0
+ */
+public abstract class AbstractLinkedMap<K, V> extends AbstractHashedMap<K, V> implements OrderedMap<K, V> {
+
+ /** Header in the linked list */
+ transient LinkEntry<K, V> header;
+
+ /**
+ * Constructor only used in deserialization, do not use otherwise.
+ */
+ protected AbstractLinkedMap() {
+ super();
+ }
+
+ /**
+ * Constructor which performs no validation on the passed in parameters.
+ *
+ * @param initialCapacity the initial capacity, must be a power of two
+ * @param loadFactor the load factor, must be > 0.0f and generally < 1.0f
+ * @param threshold the threshold, must be sensible
+ */
+ protected AbstractLinkedMap(final int initialCapacity, final float loadFactor, final int threshold) {
+ super(initialCapacity, loadFactor, threshold);
+ }
+
+ /**
+ * Constructs a new, empty map with the specified initial capacity.
+ *
+ * @param initialCapacity the initial capacity
+ * @throws IllegalArgumentException if the initial capacity is negative
+ */
+ protected AbstractLinkedMap(final int initialCapacity) {
+ super(initialCapacity);
+ }
+
+ /**
+ * Constructs a new, empty map with the specified initial capacity and
+ * load factor.
+ *
+ * @param initialCapacity the initial capacity
+ * @param loadFactor the load factor
+ * @throws IllegalArgumentException if the initial capacity is negative
+ * @throws IllegalArgumentException if the load factor is less than zero
+ */
+ protected AbstractLinkedMap(final int initialCapacity, final float loadFactor) {
+ super(initialCapacity, loadFactor);
+ }
+
+ /**
+ * Constructor copying elements from another map.
+ *
+ * @param map the map to copy
+ * @throws NullPointerException if the map is null
+ */
+ protected AbstractLinkedMap(final Map<? extends K, ? extends V> map) {
+ super(map);
+ }
+
+ /**
+ * Initialise this subclass during construction.
+ * <p>
+ * 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<K, V> entry = header.after; entry != header; entry = entry.after) {
+ if (entry.getValue() == null) {
+ return true;
+ }
+ }
+ } else {
+ for (LinkEntry<K, V> 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<K, V> entry = getEntry(key);
+ return entry == null || entry.after == header ? null : entry.after.getKey();
+ }
+
+ @Override
+ protected LinkEntry<K, V> getEntry(final Object key) {
+ return (LinkEntry<K, V>) 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<K, V> 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<K, V> 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<K, V> 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.
+ * <p>
+ * 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<K, V> entry, final int hashIndex) {
+ final LinkEntry<K, V> link = (LinkEntry<K, V>) 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.
+ * <p>
+ * 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<K, V> createEntry(final HashEntry<K, V> 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.
+ * <p>
+ * 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<K, V> entry, final int hashIndex, final HashEntry<K, V> previous) {
+ final LinkEntry<K, V> link = (LinkEntry<K, V>) 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</code> field from a <code>LinkEntry</code>.
+ * Used in subclasses that have no visibility of the field.
+ *
+ * @param entry the entry to query, must not be null
+ * @return the <code>before</code> field of the entry
+ * @throws NullPointerException if the entry is null
+ * @since 3.1
+ */
+ protected LinkEntry<K, V> entryBefore(final LinkEntry<K, V> entry) {
+ return entry.before;
+ }
+
+ /**
+ * Gets the <code>after</code> field from a <code>LinkEntry</code>.
+ * Used in subclasses that have no visibility of the field.
+ *
+ * @param entry the entry to query, must not be null
+ * @return the <code>after</code> field of the entry
+ * @throws NullPointerException if the entry is null
+ * @since 3.1
+ */
+ protected LinkEntry<K, V> entryAfter(final LinkEntry<K, V> entry) {
+ return entry.after;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public OrderedMapIterator<K, V> mapIterator() {
+ if (size == 0) {
+ return EmptyOrderedMapIterator.<K, V>emptyOrderedMapIterator();
+ }
+ return new LinkMapIterator<>(this);
+ }
+
+ /**
+ * MapIterator implementation.
+ */
+ protected static class LinkMapIterator<K, V> extends LinkIterator<K, V> implements
+ OrderedMapIterator<K, V>, ResettableIterator<K> {
+
+ protected LinkMapIterator(final AbstractLinkedMap<K, V> 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<K, V> current = currentEntry();
+ if (current == null) {
+ throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID);
+ }
+ return current.getKey();
+ }
+
+ @Override
+ public V getValue() {
+ final LinkEntry<K, V> current = currentEntry();
+ if (current == null) {
+ throw new IllegalStateException(GETVALUE_INVALID);
+ }
+ return current.getValue();
+ }
+
+ @Override
+ public V setValue(final V value) {
+ final LinkEntry<K, V> current = currentEntry();
+ if (current == null) {
+ throw new IllegalStateException(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<Entry<K, V>> createEntrySetIterator() {
+ if (size() == 0) {
+ return EmptyOrderedIterator.<Entry<K, V>>emptyOrderedIterator();
+ }
+ return new EntrySetIterator<>(this);
+ }
+
+ /**
+ * EntrySet iterator.
+ */
+ protected static class EntrySetIterator<K, V> extends LinkIterator<K, V> implements
+ OrderedIterator<Entry<K, V>>, ResettableIterator<Entry<K, V>> {
+
+ protected EntrySetIterator(final AbstractLinkedMap<K, V> parent) {
+ super(parent);
+ }
+
+ @Override
+ public Entry<K, V> next() {
+ return super.nextEntry();
+ }
+
+ @Override
+ public Entry<K, V> 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<K> createKeySetIterator() {
+ if (size() == 0) {
+ return EmptyOrderedIterator.<K>emptyOrderedIterator();
+ }
+ return new KeySetIterator<>(this);
+ }
+
+ /**
+ * KeySet iterator.
+ */
+ protected static class KeySetIterator<K> extends LinkIterator<K, Object> implements
+ OrderedIterator<K>, ResettableIterator<K> {
+
+ @SuppressWarnings("unchecked")
+ protected KeySetIterator(final AbstractLinkedMap<K, ?> parent) {
+ super((AbstractLinkedMap<K, Object>) 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<V> createValuesIterator() {
+ if (size() == 0) {
+ return EmptyOrderedIterator.<V>emptyOrderedIterator();
+ }
+ return new ValuesIterator<>(this);
+ }
+
+ /**
+ * Values iterator.
+ */
+ protected static class ValuesIterator<V> extends LinkIterator<Object, V> implements
+ OrderedIterator<V>, ResettableIterator<V> {
+
+ @SuppressWarnings("unchecked")
+ protected ValuesIterator(final AbstractLinkedMap<?, V> parent) {
+ super((AbstractLinkedMap<Object, V>) parent);
+ }
+
+ @Override
+ public V next() {
+ return super.nextEntry().getValue();
+ }
+
+ @Override
+ public V previous() {
+ return super.previousEntry().getValue();
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * LinkEntry that stores the data.
+ * <p>
+ * If you subclass <code>AbstractLinkedMap</code> but not <code>LinkEntry</code>
+ * then you will not be able to access the protected fields.
+ * The <code>entryXxx()</code> methods on <code>AbstractLinkedMap</code> exist
+ * to provide the necessary access.
+ */
+ protected static class LinkEntry<K, V> extends HashEntry<K, V> {
+ /** The entry before this one in the order */
+ protected LinkEntry<K, V> before;
+ /** The entry after this one in the order */
+ protected LinkEntry<K, V> 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<K, V> next, final int hashCode, final Object key, final V value) {
+ super(next, hashCode, key, value);
+ }
+ }
+
+ /**
+ * Base Iterator that iterates in link order.
+ */
+ protected static abstract class LinkIterator<K, V> {
+
+ /** The parent map */
+ protected final AbstractLinkedMap<K, V> parent;
+ /** The current (last returned) entry */
+ protected LinkEntry<K, V> last;
+ /** The next entry */
+ protected LinkEntry<K, V> next;
+ /** The modification count expected */
+ protected int expectedModCount;
+
+ protected LinkIterator(final AbstractLinkedMap<K, V> parent) {
+ super();
+ this.parent = parent;
+ this.next = parent.header.after;
+ this.expectedModCount = parent.modCount;
+ }
+
+ public boolean hasNext() {
+ return next != parent.header;
+ }
+
+ public boolean hasPrevious() {
+ return next.before != parent.header;
+ }
+
+ protected LinkEntry<K, V> nextEntry() {
+ if (parent.modCount != expectedModCount) {
+ throw new ConcurrentModificationException();
+ }
+ if (next == parent.header) {
+ throw new NoSuchElementException(NO_NEXT_ENTRY);
+ }
+ last = next;
+ next = next.after;
+ return last;
+ }
+
+ protected LinkEntry<K, V> previousEntry() {
+ if (parent.modCount != expectedModCount) {
+ throw new ConcurrentModificationException();
+ }
+ final LinkEntry<K, V> previous = next.before;
+ if (previous == parent.header) {
+ throw new NoSuchElementException(AbstractHashedMap.NO_PREVIOUS_ENTRY);
+ }
+ next = previous;
+ last = previous;
+ return last;
+ }
+
+ protected LinkEntry<K, V> 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractListDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractListDecorator.java
new file mode 100644
index 0000000..c80676b
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractListDecorator.java
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.ListIterator;
+
+/**
+ * Decorates another {@link List} to provide additional behaviour.
+ * <p>
+ * Methods are forwarded directly to the decorated list.
+ * </p>
+ *
+ * @param <E> the type of the elements in the list
+ * @since 3.0
+ */
+public abstract class AbstractListDecorator<E> extends AbstractCollectionDecorator<E>
+ implements List<E> {
+
+ /** Serialization version--necessary in an abstract class? */
+ private static final long serialVersionUID = 4500739654952315623L;
+
+ /**
+ * Constructor only used in deserialization, do not use otherwise.
+ * @since 3.1
+ */
+ protected AbstractListDecorator() {
+ super();
+ }
+
+ /**
+ * Constructor that wraps (not copies).
+ *
+ * @param list the list to decorate, must not be null
+ * @throws NullPointerException if list is null
+ */
+ protected AbstractListDecorator(final List<E> list) {
+ super(list);
+ }
+
+ /**
+ * Gets the list being decorated.
+ *
+ * @return the decorated list
+ */
+ @Override
+ protected List<E> decorated() {
+ return (List<E>) 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<? extends E> 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<E> listIterator() {
+ return decorated().listIterator();
+ }
+
+ @Override
+ public ListIterator<E> 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<E> subList(final int fromIndex, final int toIndex) {
+ return decorated().subList(fromIndex, toIndex);
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractMapDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractMapDecorator.java
new file mode 100644
index 0000000..93eb0e5
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractMapDecorator.java
@@ -0,0 +1,156 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Provides a base decorator that enables additional functionality to be added
+ * to a Map via decoration.
+ * <p>
+ * Methods are forwarded directly to the decorated map.
+ * </p>
+ * <p>
+ * 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.
+ * </p>
+ *
+ * @param <K> the type of the keys in the map
+ * @param <V> the type of the values in the map
+ * @since 3.0
+ */
+public abstract class AbstractMapDecorator<K, V> extends AbstractIterableMap<K, V> {
+
+ /** The map to decorate */
+ transient Map<K, V> map;
+
+ /**
+ * Constructor only used in deserialization, do not use otherwise.
+ * @since 3.1
+ */
+ protected AbstractMapDecorator() {
+ super();
+ }
+
+ /**
+ * Constructor that wraps (not copies).
+ *
+ * @param map the map to decorate, must not be null
+ * @throws NullPointerException if the map is null
+ */
+ protected AbstractMapDecorator(final Map<K, V> map) {
+ if (map == null) {
+ throw new NullPointerException("Map must not be null.");
+ }
+ this.map = map;
+ }
+
+ /**
+ * Gets the map being decorated.
+ *
+ * @return the decorated map
+ */
+ protected Map<K, V> 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<Entry<K, V>> 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<K> 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<? extends K, ? extends V> 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<V> 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractMapEntry.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractMapEntry.java
new file mode 100644
index 0000000..6d4597c
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractMapEntry.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Map;
+
+/**
+ * Abstract Pair class to assist with creating correct
+ * {@link Map.Entry Map.Entry} implementations.
+ *
+ * @param <K> the type of keys
+ * @param <V> the type of mapped values
+ * @since 3.0
+ */
+public abstract class AbstractMapEntry<K, V> extends AbstractKeyValue<K, V> implements Map.Entry<K, V> {
+
+ /**
+ * Constructs a new entry with the given key and given value.
+ *
+ * @param key the key for the entry, may be null
+ * @param value the value for the entry, may be null
+ */
+ protected AbstractMapEntry(final K key, final V value) {
+ super(key, value);
+ }
+
+ // Map.Entry interface
+ //-------------------------------------------------------------------------
+ /**
+ * Sets the value stored in this <code>Map.Entry</code>.
+ * <p>
+ * This <code>Map.Entry</code> 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</code> with another <code>Map.Entry</code>.
+ * <p>
+ * Implemented per API documentation of {@link Map.Entry#equals(Object)}
+ *
+ * @param obj the object to compare to
+ * @return true if equal key and value
+ */
+ @Override
+ public boolean equals(final Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (obj instanceof Map.Entry == false) {
+ return false;
+ }
+ final Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
+ return
+ (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) &&
+ (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue()));
+ }
+
+ /**
+ * Gets a hashCode compatible with the equals method.
+ * <p>
+ * Implemented per API documentation of {@link 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractMapEntryDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractMapEntryDecorator.java
new file mode 100644
index 0000000..1fbb1ea
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractMapEntryDecorator.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Map;
+
+/**
+ * Provides a base decorator that allows additional functionality to be
+ * added to a {@link Map.Entry Map.Entry}.
+ *
+ * @param <K> the type of keys
+ * @param <V> the type of mapped values
+ * @since 3.0
+ */
+public abstract class AbstractMapEntryDecorator<K, V> implements Map.Entry<K, V>, KeyValue<K, V> {
+
+ /** The <code>Map.Entry</code> to decorate */
+ private final Map.Entry<K, V> entry;
+
+ /**
+ * Constructor that wraps (not copies).
+ *
+ * @param entry the <code>Map.Entry</code> to decorate, must not be null
+ * @throws NullPointerException if the collection is null
+ */
+ public AbstractMapEntryDecorator(final Map.Entry<K, V> entry) {
+ if (entry == null) {
+ throw new NullPointerException("Map Entry must not be null.");
+ }
+ this.entry = entry;
+ }
+
+ /**
+ * Gets the map being decorated.
+ *
+ * @return the decorated map
+ */
+ protected Map.Entry<K, V> 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractOrderedMapDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractOrderedMapDecorator.java
new file mode 100644
index 0000000..61cd5cc
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractOrderedMapDecorator.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+/**
+ * Provides a base decorator that enables additional functionality to be added
+ * to an OrderedMap via decoration.
+ * <p>
+ * Methods are forwarded directly to the decorated map.
+ * </p>
+ * <p>
+ * 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.
+ * </p>
+ *
+ * @param <K> the type of the keys in this map
+ * @param <V> the type of the values in this map
+ * @since 3.0
+ */
+public abstract class AbstractOrderedMapDecorator<K, V> extends AbstractMapDecorator<K, V>
+ implements OrderedMap<K, V> {
+
+ /**
+ * Constructor only used in deserialization, do not use otherwise.
+ * @since 3.1
+ */
+ protected AbstractOrderedMapDecorator() {
+ super();
+ }
+
+ /**
+ * Constructor that wraps (not copies).
+ *
+ * @param map the map to decorate, must not be null
+ * @throws NullPointerException if the map is null
+ */
+ public AbstractOrderedMapDecorator(final OrderedMap<K, V> map) {
+ super(map);
+ }
+
+ /**
+ * Gets the map being decorated.
+ *
+ * @return the decorated map
+ */
+ @Override
+ protected OrderedMap<K, V> decorated() {
+ return (OrderedMap<K, V>) 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<K, V> mapIterator() {
+ return decorated().mapIterator();
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractReferenceMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractReferenceMap.java
new file mode 100644
index 0000000..78fc97d
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractReferenceMap.java
@@ -0,0 +1,1107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+
+/**
+ * An abstract implementation of a hash-based map that allows the entries to
+ * be removed by the garbage collector.
+ * <p>
+ * 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</code> 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.
+ * </p>
+ * <p>
+ * Overridable methods are provided to change the default hashing behaviour, and
+ * to change how entries are added to and removed from the map. Hopefully, all you
+ * need for unusual subclasses is here.
+ * </p>
+ * <p>
+ * When you construct an <code>AbstractReferenceMap</code>, 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}.
+ * </p>
+ * <p>
+ * 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
+ * <a href="http://java.sun.com/j2se/1.4/docs/api/java/util/WeakHashMap.html">
+ * <code>WeakHashMap</code></a>. 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.
+ * </p>
+ * <p>
+ * This {@link Map} implementation does <i>not</i> allow null elements.
+ * Attempting to add a null key or value to the map will raise a
+ * <code>NullPointerException</code>.
+ * </p>
+ * <p>
+ * All the available iterators can be reset back to the start by casting to
+ * <code>ResettableIterator</code> and calling <code>reset()</code>.
+ * </p>
+ * <p>
+ * This implementation is not synchronized.
+ * You can use {@link java.util.Collections#synchronizedMap} to
+ * provide synchronized access to a <code>ReferenceMap</code>.
+ * </p>
+ *
+ * @param <K> the type of the keys in this map
+ * @param <V> the type of the values in this map
+ *
+ * @see Reference
+ * @since 3.1 (extracted from ReferenceMap in 3.0)
+ */
+public abstract class AbstractReferenceMap<K, V> extends AbstractHashedMap<K, V> {
+
+ /**
+ * 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<Object> queue;
+
+ //-----------------------------------------------------------------------
+ /**
+ * Constructor used during deserialization.
+ */
+ protected AbstractReferenceMap() {
+ super();
+ }
+
+ /**
+ * Constructs a new empty map with the specified reference types,
+ * load factor and initial capacity.
+ *
+ * @param keyType the type of reference to use for keys;
+ * must be {@link ReferenceStrength#HARD HARD},
+ * {@link ReferenceStrength#SOFT SOFT},
+ * {@link ReferenceStrength#WEAK WEAK}
+ * @param valueType the type of reference to use for values;
+ * must be {@link ReferenceStrength#HARD},
+ * {@link ReferenceStrength#SOFT SOFT},
+ * {@link ReferenceStrength#WEAK WEAK}
+ * @param capacity the initial capacity for the map
+ * @param loadFactor the load factor for the map
+ * @param purgeValues should the value be automatically purged when the
+ * key is garbage collected
+ */
+ protected AbstractReferenceMap(
+ final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity,
+ final float loadFactor, final boolean purgeValues) {
+ super(capacity, loadFactor);
+ this.keyType = keyType;
+ this.valueType = valueType;
+ this.purgeValues = purgeValues;
+ }
+
+ /**
+ * Initialise this subclass during construction, cloning or deserialization.
+ */
+ @Override
+ protected void init() {
+ queue = new ReferenceQueue<>();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the size of the map.
+ *
+ * @return the size
+ */
+ @Override
+ public int size() {
+ purgeBeforeRead();
+ return super.size();
+ }
+
+ /**
+ * Checks whether the map is currently empty.
+ *
+ * @return true if the map is currently size zero
+ */
+ @Override
+ public boolean isEmpty() {
+ purgeBeforeRead();
+ return super.isEmpty();
+ }
+
+ /**
+ * Checks whether the map contains the specified key.
+ *
+ * @param key the key to search for
+ * @return true if the map contains the key
+ */
+ @Override
+ public boolean containsKey(final Object key) {
+ purgeBeforeRead();
+ final Entry<K, V> 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<K, V> entry = getEntry(key);
+ if (entry == null) {
+ return null;
+ }
+ return entry.getValue();
+ }
+
+
+ /**
+ * Puts a key-value mapping into this map.
+ * Neither the key nor the value may be null.
+ *
+ * @param key the key to add, must not be null
+ * @param value the value to add, must not be null
+ * @return the value previously mapped to this key, null if none
+ * @throws NullPointerException if either the key or value is null
+ */
+ @Override
+ public V put(final K key, final V value) {
+ if (key == null) {
+ throw new NullPointerException("null keys not allowed");
+ }
+ if (value == null) {
+ throw new NullPointerException("null values not allowed");
+ }
+
+ purgeBeforeWrite();
+ return super.put(key, value);
+ }
+
+ /**
+ * Removes the specified mapping from this map.
+ *
+ * @param key the mapping to remove
+ * @return the value mapped to the removed key, null if key not in map
+ */
+ @Override
+ public V remove(final Object key) {
+ if (key == null) {
+ return null;
+ }
+ purgeBeforeWrite();
+ return super.remove(key);
+ }
+
+ /**
+ * Clears this map.
+ */
+ @Override
+ public void clear() {
+ super.clear();
+ // drain the queue
+ while (queue.poll() != null) {
+ // empty
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets a MapIterator over the reference map.
+ * The iterator only returns valid key/value pairs.
+ *
+ * @return a map iterator
+ */
+ @Override
+ public MapIterator<K, V> mapIterator() {
+ return new ReferenceMapIterator<>(this);
+ }
+
+ /**
+ * Returns a set view of this map's entries.
+ * An iterator returned entry is valid until <code>next()</code> is called again.
+ * The <code>setValue()</code> method on the <code>toArray</code> entries has no effect.
+ *
+ * @return a set view of this map's entries
+ */
+ @Override
+ public Set<Entry<K, V>> 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<K> 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<V> values() {
+ if (values == null) {
+ values = new ReferenceValues<>(this);
+ }
+ return values;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Purges stale mappings from this map before read operations.
+ * <p>
+ * This implementation calls {@link #purge()} to maintain a consistent state.
+ */
+ protected void purgeBeforeRead() {
+ purge();
+ }
+
+ /**
+ * Purges stale mappings from this map before write operations.
+ * <p>
+ * This implementation calls {@link #purge()} to maintain a consistent state.
+ */
+ protected void purgeBeforeWrite() {
+ purge();
+ }
+
+ /**
+ * Purges stale mappings from this map.
+ * <p>
+ * 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<K, V> previous = null;
+ HashEntry<K, V> entry = data[index];
+ while (entry != null) {
+ ReferenceEntry<K, V> refEntry = (ReferenceEntry<K, V>) 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<K, V> 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.
+ * <p>
+ * 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</code>
+ * @return true if equal
+ */
+ @Override
+ @SuppressWarnings("unchecked")
+ protected boolean isEqualKey(final Object key1, Object key2) {
+ key2 = keyType == ReferenceStrength.HARD ? key2 : ((Reference<K>) 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<K, V> createEntry(final HashEntry<K, V> 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<Entry<K, V>> createEntrySetIterator() {
+ return new ReferenceEntrySetIterator<>(this);
+ }
+
+ /**
+ * Creates an key set iterator.
+ *
+ * @return the keySet iterator
+ */
+ @Override
+ protected Iterator<K> createKeySetIterator() {
+ return new ReferenceKeySetIterator<>(this);
+ }
+
+ /**
+ * Creates an values iterator.
+ *
+ * @return the values iterator
+ */
+ @Override
+ protected Iterator<V> createValuesIterator() {
+ return new ReferenceValuesIterator<>(this);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * EntrySet implementation.
+ */
+ static class ReferenceEntrySet<K, V> extends EntrySet<K, V> {
+
+ protected ReferenceEntrySet(final AbstractHashedMap<K, V> parent) {
+ super(parent);
+ }
+
+ @Override
+ public Object[] toArray() {
+ return toArray(new Object[size()]);
+ }
+
+ @Override
+ public <T> T[] toArray(final T[] arr) {
+ // special implementation to handle disappearing entries
+ final ArrayList<Entry<K, V>> list = new ArrayList<>(size());
+ for (final Entry<K, V> entry : this) {
+ list.add(new DefaultMapEntry<>(entry));
+ }
+ return list.toArray(arr);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * KeySet implementation.
+ */
+ static class ReferenceKeySet<K> extends KeySet<K> {
+
+ protected ReferenceKeySet(final AbstractHashedMap<K, ?> parent) {
+ super(parent);
+ }
+
+ @Override
+ public Object[] toArray() {
+ return toArray(new Object[size()]);
+ }
+
+ @Override
+ public <T> T[] toArray(final T[] arr) {
+ // special implementation to handle disappearing keys
+ final List<K> list = new ArrayList<>(size());
+ for (final K key : this) {
+ list.add(key);
+ }
+ return list.toArray(arr);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Values implementation.
+ */
+ static class ReferenceValues<V> extends Values<V> {
+
+ protected ReferenceValues(final AbstractHashedMap<?, V> parent) {
+ super(parent);
+ }
+
+ @Override
+ public Object[] toArray() {
+ return toArray(new Object[size()]);
+ }
+
+ @Override
+ public <T> T[] toArray(final T[] arr) {
+ // special implementation to handle disappearing values
+ final List<V> list = new ArrayList<>(size());
+ for (final V value : this) {
+ list.add(value);
+ }
+ return list.toArray(arr);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * A MapEntry implementation for the map.
+ * <p>
+ * If getKey() or getValue() returns null, it means
+ * the mapping is stale and should be removed.
+ *
+ * @since 3.1
+ */
+ protected static class ReferenceEntry<K, V> extends HashEntry<K, V> {
+ /** The parent map */
+ private final AbstractReferenceMap<K, V> 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<K, V> parent, final HashEntry<K, V> 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<K>) 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<V>) 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<V>) value).clear();
+ }
+ value = toReference(parent.valueType, obj, hashCode);
+ return old;
+ }
+
+ /**
+ * Compares this map entry to another.
+ * <p>
+ * This implementation uses <code>isEqualKey</code> and
+ * <code>isEqualValue</code> on the main map for comparison.
+ *
+ * @param obj the other map entry to compare to
+ * @return true if equal, false if not
+ */
+ @Override
+ public boolean equals(final Object obj) {
+ if (obj == this) {
+ return true;
+ }
+ if (obj instanceof Map.Entry == false) {
+ return false;
+ }
+
+ final Entry<?, ?> entry = (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.
+ * <p>
+ * This implementation uses <code>hashEntry</code> 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 <T> 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 <i>key</i> 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 <T> 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<K, V> next() {
+ return (ReferenceEntry<K, V>) next;
+ }
+
+ /**
+ * This method can be overriden to provide custom logic to purge value
+ */
+ protected void nullValue() {
+ value = null;
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Base iterator class.
+ */
+ static class ReferenceBaseIterator<K, V> {
+ /** The parent map */
+ final AbstractReferenceMap<K, V> parent;
+
+ // These fields keep track of where we are in the table.
+ int index;
+ ReferenceEntry<K, V> entry;
+ ReferenceEntry<K, V> previous;
+
+ // These Object fields provide hard references to the
+ // current and next entry; this assures that if hasNext()
+ // returns true, next() will actually return a valid element.
+ K currentKey, nextKey;
+ V currentValue, nextValue;
+
+ int expectedModCount;
+
+ public ReferenceBaseIterator(final AbstractReferenceMap<K, V> parent) {
+ super();
+ this.parent = parent;
+ index = parent.size() != 0 ? parent.data.length : 0;
+ // have to do this here! size() invocation above
+ // may have altered the modCount.
+ expectedModCount = parent.modCount;
+ }
+
+ public boolean hasNext() {
+ checkMod();
+ while (nextNull()) {
+ ReferenceEntry<K, V> e = entry;
+ int i = index;
+ while (e == null && i > 0) {
+ i--;
+ e = (ReferenceEntry<K, V>) parent.data[i];
+ }
+ entry = e;
+ index = i;
+ if (e == null) {
+ currentKey = null;
+ currentValue = null;
+ return false;
+ }
+ nextKey = e.getKey();
+ nextValue = e.getValue();
+ if (nextNull()) {
+ entry = entry.next();
+ }
+ }
+ return true;
+ }
+
+ private void checkMod() {
+ if (parent.modCount != expectedModCount) {
+ throw new ConcurrentModificationException();
+ }
+ }
+
+ private boolean nextNull() {
+ return nextKey == null || nextValue == null;
+ }
+
+ protected ReferenceEntry<K, V> nextEntry() {
+ checkMod();
+ if (nextNull() && !hasNext()) {
+ throw new NoSuchElementException();
+ }
+ previous = entry;
+ entry = entry.next();
+ currentKey = nextKey;
+ currentValue = nextValue;
+ nextKey = null;
+ nextValue = null;
+ return previous;
+ }
+
+ protected ReferenceEntry<K, V> currentEntry() {
+ checkMod();
+ return previous;
+ }
+
+ public void remove() {
+ checkMod();
+ if (previous == null) {
+ throw new IllegalStateException();
+ }
+ parent.remove(currentKey);
+ previous = null;
+ currentKey = null;
+ currentValue = null;
+ expectedModCount = parent.modCount;
+ }
+ }
+
+ /**
+ * The EntrySet iterator.
+ */
+ static class ReferenceEntrySetIterator<K, V>
+ extends ReferenceBaseIterator<K, V> implements Iterator<Entry<K, V>> {
+
+ public ReferenceEntrySetIterator(final AbstractReferenceMap<K, V> parent) {
+ super(parent);
+ }
+
+ @Override
+ public Entry<K, V> next() {
+ return nextEntry();
+ }
+
+ }
+
+ /**
+ * The keySet iterator.
+ */
+ static class ReferenceKeySetIterator<K> extends ReferenceBaseIterator<K, Object> implements Iterator<K> {
+
+ @SuppressWarnings("unchecked")
+ ReferenceKeySetIterator(final AbstractReferenceMap<K, ?> parent) {
+ super((AbstractReferenceMap<K, Object>) parent);
+ }
+
+ @Override
+ public K next() {
+ return nextEntry().getKey();
+ }
+ }
+
+ /**
+ * The values iterator.
+ */
+ static class ReferenceValuesIterator<V> extends ReferenceBaseIterator<Object, V> implements Iterator<V> {
+
+ @SuppressWarnings("unchecked")
+ ReferenceValuesIterator(final AbstractReferenceMap<?, V> parent) {
+ super((AbstractReferenceMap<Object, V>) parent);
+ }
+
+ @Override
+ public V next() {
+ return nextEntry().getValue();
+ }
+ }
+
+ /**
+ * The MapIterator implementation.
+ */
+ static class ReferenceMapIterator<K, V> extends ReferenceBaseIterator<K, V> implements MapIterator<K, V> {
+
+ protected ReferenceMapIterator(final AbstractReferenceMap<K, V> parent) {
+ super(parent);
+ }
+
+ @Override
+ public K next() {
+ return nextEntry().getKey();
+ }
+
+ @Override
+ public K getKey() {
+ final HashEntry<K, V> current = currentEntry();
+ if (current == null) {
+ throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID);
+ }
+ return current.getKey();
+ }
+
+ @Override
+ public V getValue() {
+ final HashEntry<K, V> current = currentEntry();
+ if (current == null) {
+ throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID);
+ }
+ return current.getValue();
+ }
+
+ @Override
+ public V setValue(final V value) {
+ final HashEntry<K, V> current = currentEntry();
+ if (current == null) {
+ throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID);
+ }
+ return current.setValue(value);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ // These two classes store the hashCode of the key of
+ // of the mapping, so that after they're dequeued a quick
+ // lookup of the bucket in the table can occur.
+
+ /**
+ * A soft reference holder.
+ */
+ static class SoftRef<T> extends SoftReference<T> {
+ /** the hashCode of the key (even if the reference points to a value) */
+ private final int hash;
+
+ public SoftRef(final int hash, final T r, final ReferenceQueue<? super T> q) {
+ super(r, q);
+ this.hash = hash;
+ }
+
+ @Override
+ public int hashCode() {
+ return hash;
+ }
+ }
+
+ /**
+ * A weak reference holder.
+ */
+ static class WeakRef<T> extends WeakReference<T> {
+ /** the hashCode of the key (even if the reference points to a value) */
+ private final int hash;
+
+ public WeakRef(final int hash, final T r, final ReferenceQueue<? super T> q) {
+ super(r, q);
+ this.hash = hash;
+ }
+
+ @Override
+ public int hashCode() {
+ return hash;
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Replaces the superclass method to store the state of this class.
+ * <p>
+ * Serialization is not one of the JDK's nicest topics. Normal serialization will
+ * initialise the superclass before the subclass. Sometimes however, this isn't
+ * what you want, as in this case the <code>put()</code> method on read can be
+ * affected by subclass state.
+ * <p>
+ * 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()</code> of the first serializable subclass.
+ * <p>
+ * 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<K, V> 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.
+ * <p>
+ * Serialization is not one of the JDK's nicest topics. Normal serialization will
+ * initialise the superclass before the subclass. Sometimes however, this isn't
+ * what you want, as in this case the <code>put()</code> method on read can be
+ * affected by subclass state.
+ * <p>
+ * 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()</code> of the first serializable subclass.
+ * <p>
+ * Subclasses may override if the subclass has a specific field that must be present
+ * before <code>put()</code> or <code>calculateThreshold()</code> 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSerializableListDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSerializableListDecorator.java
new file mode 100644
index 0000000..3775575
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSerializableListDecorator.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+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<E>
+ extends AbstractListDecorator<E> {
+
+ /** 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<E> 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<E>) in.readObject());
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSerializableSetDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSerializableSetDecorator.java
new file mode 100644
index 0000000..9afd551
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSerializableSetDecorator.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+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 <E> the type of the elements in this set
+ * @since 3.1
+ */
+public abstract class AbstractSerializableSetDecorator<E>
+ extends AbstractSetDecorator<E> {
+
+ /** 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<E> 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<E>) in.readObject());
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSetDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSetDecorator.java
new file mode 100644
index 0000000..bcbfaad
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSetDecorator.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Set;
+
+/**
+ * Decorates another <code>Set</code> to provide additional behaviour.
+ * <p>
+ * Methods are forwarded directly to the decorated set.
+ * </p>
+ *
+ * @param <E> the type of the elements in this set
+ * @since 3.0
+ */
+public abstract class AbstractSetDecorator<E> extends AbstractCollectionDecorator<E> implements
+ Set<E> {
+
+ /** Serialization version */
+ private static final long serialVersionUID = -4678668309576958546L;
+
+ /**
+ * Constructor only used in deserialization, do not use otherwise.
+ * @since 3.1
+ */
+ protected AbstractSetDecorator() {
+ super();
+ }
+
+ /**
+ * Constructor that wraps (not copies).
+ *
+ * @param set the set to decorate, must not be null
+ * @throws NullPointerException if set is null
+ */
+ protected AbstractSetDecorator(final Set<E> set) {
+ super(set);
+ }
+
+ /**
+ * Gets the set being decorated.
+ *
+ * @return the decorated set
+ */
+ @Override
+ protected Set<E> decorated() {
+ return (Set<E>) 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSortedMapDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSortedMapDecorator.java
new file mode 100644
index 0000000..da41b81
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractSortedMapDecorator.java
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.ListIterator;
+import java.util.Set;
+import java.util.SortedMap;
+
+/**
+ * Provides a base decorator that enables additional functionality to be added
+ * to a Map via decoration.
+ * <p>
+ * Methods are forwarded directly to the decorated map.
+ * </p>
+ * <p>
+ * 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.
+ * </p>
+ *
+ * @param <K> the type of the keys in the map
+ * @param <V> the type of the values in the map
+ * @since 3.0
+ */
+public abstract class AbstractSortedMapDecorator<K, V> extends AbstractMapDecorator<K, V> implements
+ IterableSortedMap<K, V> {
+
+ /**
+ * Constructor only used in deserialization, do not use otherwise.
+ * @since 3.1
+ */
+ protected AbstractSortedMapDecorator() {
+ super();
+ }
+
+ /**
+ * Constructor that wraps (not copies).
+ *
+ * @param map the map to decorate, must not be null
+ * @throws NullPointerException if the map is null
+ */
+ public AbstractSortedMapDecorator(final SortedMap<K, V> map) {
+ super(map);
+ }
+
+ /**
+ * Gets the map being decorated.
+ *
+ * @return the decorated map
+ */
+ @Override
+ protected SortedMap<K, V> decorated() {
+ return (SortedMap<K, V>) super.decorated();
+ }
+
+ //-----------------------------------------------------------------------
+ @Override
+ public Comparator<? super K> comparator() {
+ return decorated().comparator();
+ }
+
+ @Override
+ public K firstKey() {
+ return decorated().firstKey();
+ }
+
+ @Override
+ public K lastKey() {
+ return decorated().lastKey();
+ }
+
+ @Override
+ public SortedMap<K, V> subMap(final K fromKey, final K toKey) {
+ return decorated().subMap(fromKey, toKey);
+ }
+
+ @Override
+ public SortedMap<K, V> headMap(final K toKey) {
+ return decorated().headMap(toKey);
+ }
+
+ @Override
+ public SortedMap<K, V> tailMap(final K fromKey) {
+ return decorated().tailMap(fromKey);
+ }
+
+ @Override
+ public K previousKey(final K key) {
+ final SortedMap<K, V> headMap = headMap(key);
+ return headMap.isEmpty() ? null : headMap.lastKey();
+ }
+
+ @Override
+ public K nextKey(final K key) {
+ final Iterator<K> it = tailMap(key).keySet().iterator();
+ it.next();
+ return it.hasNext() ? it.next() : null;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public OrderedMapIterator<K, V> mapIterator() {
+ return new SortedMapIterator<>(entrySet());
+ }
+
+ /**
+ * OrderedMapIterator implementation.
+ *
+ * @param <K> the key type
+ * @param <V> the value type
+ */
+ protected static class SortedMapIterator<K, V> extends EntrySetToMapIteratorAdapter<K, V>
+ implements OrderedMapIterator<K, V> {
+
+ /**
+ * Create a new AbstractSortedMapDecorator.SortedMapIterator.
+ * @param entrySet the entrySet to iterate
+ */
+ protected SortedMapIterator(final Set<Entry<K, V>> entrySet) {
+ super(entrySet);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public synchronized void reset() {
+ super.reset();
+ iterator = new ListIteratorWrapper<>(iterator);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean hasPrevious() {
+ return ((ListIterator<Entry<K, V>>) iterator).hasPrevious();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public K previous() {
+ entry = ((ListIterator<Entry<K, V>>) iterator).previous();
+ return getKey();
+ }
+ }
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractUntypedIteratorDecorator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractUntypedIteratorDecorator.java
new file mode 100644
index 0000000..02b8d74
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/AbstractUntypedIteratorDecorator.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Iterator;
+
+/**
+ * Provides basic behaviour for decorating an iterator with extra functionality
+ * without committing the generic type of the Iterator implementation.
+ * <p>
+ * All methods are forwarded to the decorated iterator.
+ *
+ * @since 4.0
+ */
+public abstract class AbstractUntypedIteratorDecorator<I, O> implements Iterator<O> {
+
+ /** The iterator being decorated */
+ private final Iterator<I> iterator;
+
+ /**
+ * Create a new AbstractUntypedIteratorDecorator.
+ *
+ * @param iterator the iterator to decorate
+ * @throws NullPointerException if the iterator is null
+ */
+ protected AbstractUntypedIteratorDecorator(final Iterator<I> iterator) {
+ super();
+ if (iterator == null) {
+ throw new NullPointerException("Iterator must not be null");
+ }
+ this.iterator = iterator;
+ }
+
+ /**
+ * Gets the iterator being decorated.
+ *
+ * @return the decorated iterator
+ */
+ protected Iterator<I> getIterator() {
+ return iterator;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return iterator.hasNext();
+ }
+
+ @Override
+ public void remove() {
+ iterator.remove();
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/BidiMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/BidiMap.java
new file mode 100644
index 0000000..b530c88
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/BidiMap.java
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Set;
+
+/**
+ * Defines a map that allows bidirectional lookup between key and values.
+ * <p>
+ * This extended <code>Map</code> 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</code> 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</code>.
+ * </p>
+ * <p>
+ * 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.
+ * </p>
+ * <p>
+ * 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.
+ * </p>
+ *
+ * @param <K> the type of the keys in the map
+ * @param <V> the type of the values in the map
+ *
+ * @since 3.0
+ */
+public interface BidiMap<K, V> extends IterableMap<K, V> {
+
+ /**
+ * Puts the key-value pair into the map, replacing any previous pair.
+ * <p>
+ * 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.
+ * </p>
+ * <pre>
+ * 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
+ * </pre>
+ *
+ * @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</code> 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.
+ * <p>
+ * If the value is not contained in the map, <code>null</code> is returned.
+ * </p>
+ * <p>
+ * Implementations should seek to make this method perform equally as well
+ * as <code>get(Object)</code>.
+ * </p>
+ *
+ * @param value the value to find the key for
+ * @return the mapped key, or <code>null</code> 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).
+ * <p>
+ * If the value is not contained in the map, <code>null</code> is returned.
+ * </p>
+ * <p>
+ * Implementations should seek to make this method perform equally as well
+ * as <code>remove(Object)</code>.
+ * </p>
+ *
+ * @param value the value to find the key-value pair for
+ * @return the key that was removed, <code>null</code> 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.
+ * <p>
+ * 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</code>.
+ * </p>
+ * <p>
+ * Implementations should seek to avoid creating a new object every time this
+ * method is called. See <code>AbstractMap.values()</code> etc. Calling this
+ * method on the inverse map should return the original.
+ * </p>
+ *
+ * @return an inverted bidirectional map
+ */
+ BidiMap<V, K> 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<V> values();
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/BoundedMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/BoundedMap.java
new file mode 100644
index 0000000..cbafa55
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/BoundedMap.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+/**
+ * Defines a map that is bounded in size.
+ * <p>
+ * 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.
+ * </p>
+ *
+ * @param <K> the type of the keys in this map
+ * @param <V> the type of the values in this map
+ * @since 3.0
+ */
+public interface BoundedMap<K, V> extends IterableMap<K, V> {
+
+ /**
+ * Returns true if this map is full and no new elements can be added.
+ *
+ * @return <code>true</code> 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/ComparableComparator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/ComparableComparator.java
new file mode 100644
index 0000000..98be3d0
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/ComparableComparator.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.io.Serializable;
+import java.util.Comparator;
+
+/**
+ * A {@link Comparator Comparator} that compares {@link Comparable Comparable}
+ * objects.
+ * <p>
+ * 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}.
+ * </p>
+ * <p>
+ * Note: In the 2.0 and 2.1 releases of Commons Collections, this class would
+ * throw a {@link ClassCastException} if either of the arguments to
+ * {@link #compare(Object, Object) compare} were <code>null</code>, not
+ * {@link Comparable Comparable}, or for which
+ * {@link Comparable#compareTo(Object) compareTo} gave inconsistent results.
+ * This is no longer the case. See {@link #compare(Object, Object) compare} for
+ * details.
+ * </p>
+ *
+ * @param <E> the type of objects compared by this comparator
+ *
+ * @since 2.0
+ * @see java.util.Collections#reverseOrder()
+ */
+public class ComparableComparator<E extends Comparable<? super E>> implements Comparator<E>, 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.
+ * <p>
+ * 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 <E> the element type
+ * @return the singleton ComparableComparator
+ * @since 4.0
+ */
+ public static <E extends Comparable<? super E>> ComparableComparator<E> comparableComparator() {
+ return INSTANCE;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Constructor whose use should be avoided.
+ * <p>
+ * Please use the {@link #comparableComparator()} method whenever possible.
+ */
+ public ComparableComparator() {
+ super();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Compare the two {@link Comparable Comparable} arguments.
+ * This method is equivalent to:
+ * <pre>((Comparable)obj1).compareTo(obj2)</pre>
+ *
+ * @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 <i>obj1</i> is <code>null</code>,
+ * or when <code>((Comparable)obj1).compareTo(obj2)</code> does
+ * @throws ClassCastException if <i>obj1</i> is not a <code>Comparable</code>,
+ * or when <code>((Comparable)obj1).compareTo(obj2)</code> 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 <i>that</i> Object is is a {@link Comparator Comparator}
+ * whose ordering is known to be equivalent to mine.
+ * <p>
+ * This implementation returns {@code true} iff
+ * <code><i>object</i>.{@link Object#getClass() getClass()}</code> equals
+ * <code>this.getClass()</code>. 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/ComparatorChain.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/ComparatorChain.java
new file mode 100644
index 0000000..f05aec5
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/ComparatorChain.java
@@ -0,0 +1,352 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.BitSet;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * A ComparatorChain is a Comparator that wraps one or more Comparators in
+ * sequence. The ComparatorChain calls each Comparator in sequence until either
+ * 1) any single Comparator returns a non-zero result (and that result is then
+ * returned), or 2) the ComparatorChain is exhausted (and zero is returned).
+ * This type of sorting is very similar to multi-column sorting in SQL, and this
+ * class allows Java classes to emulate that kind of behaviour when sorting a
+ * List.
+ * <p>
+ * To further facilitate SQL-like sorting, the order of any single Comparator in
+ * the list can be reversed.
+ * </p>
+ * <p>
+ * Calling a method that adds new Comparators or changes the ascend/descend sort
+ * <i>after compare(Object, Object) has been called</i> will result in an
+ * UnsupportedOperationException. However, <i>take care</i> to not alter the
+ * underlying List of Comparators or the BitSet that defines the sort order.
+ * </p>
+ * <p>
+ * Instances of ComparatorChain are not synchronized. The class is not
+ * thread-safe at construction time, but it <i>is</i> thread-safe to perform
+ * multiple comparisons after all the setup operations are complete.
+ * </p>
+ *
+ * @param <E> the type of objects compared by this comparator
+ * @since 2.0
+ */
+public class ComparatorChain<E> implements Comparator<E>, Serializable {
+
+ /** Serialization version from Collections 2.0. */
+ private static final long serialVersionUID = -721644942746081630L;
+
+ /** The list of comparators in the chain. */
+ private final List<Comparator<E>> comparatorChain;
+ /** Order - false (clear) = ascend; true (set) = descend. */
+ private BitSet orderingBits = null;
+ /** Whether the chain has been "locked". */
+ private boolean isLocked = false;
+
+ //-----------------------------------------------------------------------
+ /**
+ * Construct a ComparatorChain with no Comparators.
+ * You must add at least one Comparator before calling
+ * the compare(Object,Object) method, or an
+ * UnsupportedOperationException is thrown
+ */
+ public ComparatorChain() {
+ this(new ArrayList<Comparator<E>>(), 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<E> 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<E> comparator, final boolean reverse) {
+ comparatorChain = new ArrayList<>(1);
+ comparatorChain.add(comparator);
+ orderingBits = new BitSet(1);
+ if (reverse == true) {
+ orderingBits.set(0);
+ }
+ }
+
+ /**
+ * Construct a ComparatorChain from the Comparators in the
+ * List. All Comparators will default to the forward
+ * sort order.
+ *
+ * @param list List of Comparators
+ * @see #ComparatorChain(List,BitSet)
+ */
+ public ComparatorChain(final List<Comparator<E>> 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>i</i> in the List,
+ * the ComparatorChain will call BitSet.get(<i>i</i>).
+ * If that method returns <i>false</i>, the forward
+ * sort order is used; a return value of <i>true</i>
+ * 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<Comparator<E>> 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<E> 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<E> comparator, final boolean reverse) {
+ checkLocked();
+
+ comparatorChain.add(comparator);
+ if (reverse == true) {
+ orderingBits.set(comparatorChain.size() - 1);
+ }
+ }
+
+ /**
+ * Replace the Comparator at the given index, maintaining
+ * the existing sort order.
+ *
+ * @param index index of the Comparator to replace
+ * @param comparator Comparator to place at the given index
+ * @throws IndexOutOfBoundsException
+ * if index < 0 or index >= size()
+ */
+ public void setComparator(final int index, final Comparator<E> 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<E> comparator, final boolean reverse) {
+ checkLocked();
+
+ comparatorChain.set(index,comparator);
+ if (reverse == true) {
+ orderingBits.set(index);
+ } else {
+ orderingBits.clear(index);
+ }
+ }
+
+ /**
+ * Change the sort order at the given index in the
+ * ComparatorChain to a forward sort.
+ *
+ * @param index Index of the ComparatorChain
+ */
+ public void setForwardSort(final int index) {
+ checkLocked();
+ orderingBits.clear(index);
+ }
+
+ /**
+ * Change the sort order at the given index in the
+ * ComparatorChain to a reverse sort.
+ *
+ * @param index Index of the ComparatorChain
+ */
+ public void setReverseSort(final int index) {
+ checkLocked();
+ orderingBits.set(index);
+ }
+
+ /**
+ * Number of Comparators in the current ComparatorChain.
+ *
+ * @return Comparator count
+ */
+ public int size() {
+ return comparatorChain.size();
+ }
+
+ /**
+ * Determine if modifications can still be made to the
+ * ComparatorChain. ComparatorChains cannot be modified
+ * once they have performed a comparison.
+ *
+ * @return true = ComparatorChain cannot be modified; false =
+ * ComparatorChain can still be modified.
+ */
+ public boolean isLocked() {
+ return isLocked;
+ }
+
+ /**
+ * Throws an exception if the {@link ComparatorChain} is locked.
+ *
+ * @throws UnsupportedOperationException if the {@link ComparatorChain} is locked
+ */
+ private void checkLocked() {
+ if (isLocked == true) {
+ throw new UnsupportedOperationException(
+ "Comparator ordering cannot be changed after the first comparison is performed");
+ }
+ }
+
+ /**
+ * Throws an exception if the {@link ComparatorChain} is empty.
+ *
+ * @throws UnsupportedOperationException if the {@link ComparatorChain} is empty
+ */
+ private void checkChainIntegrity() {
+ if (comparatorChain.size() == 0) {
+ throw new UnsupportedOperationException("ComparatorChains must contain at least one Comparator");
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Perform comparisons on the Objects as per
+ * Comparator.compare(o1,o2).
+ *
+ * @param o1 the first object to compare
+ * @param o2 the second object to compare
+ * @return -1, 0, or 1
+ * @throws UnsupportedOperationException if the ComparatorChain does not contain at least one Comparator
+ */
+ @Override
+ public int compare(final E o1, final E o2) throws UnsupportedOperationException {
+ if (isLocked == false) {
+ checkChainIntegrity();
+ isLocked = true;
+ }
+
+ // iterate over all comparators in the chain
+ final Iterator<Comparator<E>> comparators = comparatorChain.iterator();
+ for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) {
+
+ final Comparator<? super E> comparator = comparators.next();
+ int retval = comparator.compare(o1,o2);
+ if (retval != 0) {
+ // invert the order if it is a reverse sort
+ if (orderingBits.get(comparatorIndex) == true) {
+ if (retval > 0) {
+ retval = -1;
+ } else {
+ retval = 1;
+ }
+ }
+ return retval;
+ }
+ }
+
+ // if comparators are exhausted, return 0
+ return 0;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Implement a hash code for this comparator that is consistent with
+ * {@link #equals(Object) equals}.
+ *
+ * @return a suitable hash code
+ * @since 3.0
+ */
+ @Override
+ public int hashCode() {
+ int hash = 0;
+ if (null != comparatorChain) {
+ hash ^= comparatorChain.hashCode();
+ }
+ if (null != orderingBits) {
+ hash ^= orderingBits.hashCode();
+ }
+ return hash;
+ }
+
+ /**
+ * Returns <code>true</code> iff <i>that</i> Object is
+ * is a {@link Comparator} whose ordering is known to be
+ * equivalent to mine.
+ * <p>
+ * This implementation returns <code>true</code>
+ * iff <code><i>object</i>.{@link Object#getClass() getClass()}</code>
+ * equals <code>this.getClass()</code>, and the underlying
+ * comparators and order bits are equal.
+ * Subclasses may want to override this behavior to remain consistent
+ * with the {@link Comparator#equals(Object)} contract.
+ *
+ * @param object the object to compare with
+ * @return true if equal
+ * @since 3.0
+ */
+ @Override
+ public boolean equals(final Object object) {
+ if (this == object) {
+ return true;
+ }
+ if (null == object) {
+ return false;
+ }
+ if (object.getClass().equals(this.getClass())) {
+ final ComparatorChain<?> chain = (ComparatorChain<?>) object;
+ return (null == orderingBits ? null == chain.orderingBits : orderingBits.equals(chain.orderingBits)) &&
+ (null == comparatorChain ? null == chain.comparatorChain :
+ comparatorChain.equals(chain.comparatorChain));
+ }
+ return false;
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/DefaultMapEntry.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/DefaultMapEntry.java
new file mode 100644
index 0000000..59aaf72
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/DefaultMapEntry.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Map;
+
+/**
+ * A restricted implementation of {@link Map.Entry Map.Entry} that prevents
+ * the {@link Map.Entry Map.Entry} contract from being broken.
+ *
+ * @param <K> the type of keys
+ * @param <V> the type of mapped values
+ * @since 3.0
+ */
+public final class DefaultMapEntry<K, V> extends AbstractMapEntry<K, V> {
+
+ /**
+ * 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</code>.
+ *
+ * @param pair the pair to copy, must not be null
+ * @throws NullPointerException if the entry is null
+ */
+ public DefaultMapEntry(final KeyValue<? extends K, ? extends V> pair) {
+ super(pair.getKey(), pair.getValue());
+ }
+
+ /**
+ * Constructs a new entry from the specified <code>Map.Entry</code>.
+ *
+ * @param entry the entry to copy, must not be null
+ * @throws NullPointerException if the entry is null
+ */
+ public DefaultMapEntry(final Map.Entry<? extends K, ? extends V> entry) {
+ super(entry.getKey(), entry.getValue());
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/DualHashBidiMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/DualHashBidiMap.java
new file mode 100644
index 0000000..a763997
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/DualHashBidiMap.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Implementation of {@link BidiMap} that uses two {@link HashMap} instances.
+ * <p>
+ * 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.
+ * </p>
+ * <p>
+ * NOTE: From Commons Collections 3.1, all subclasses will use {@link HashMap}
+ * and the flawed <code>createMap</code> method is ignored.
+ * </p>
+ *
+ * @param <K> the type of the keys in the map
+ * @param <V> the type of the values in the map
+ *
+ * @since 3.0
+ */
+public class DualHashBidiMap<K, V> extends AbstractDualBidiMap<K, V> implements Serializable {
+
+ /** Ensure serialization compatibility */
+ private static final long serialVersionUID = 721969328361808L;
+
+ /**
+ * Creates an empty <code>HashBidiMap</code>.
+ */
+ public DualHashBidiMap() {
+ super(new HashMap<K, V>(), new HashMap<V, K>());
+ }
+
+ /**
+ * Constructs a <code>HashBidiMap</code> and copies the mappings from
+ * specified <code>Map</code>.
+ *
+ * @param map the map whose mappings are to be placed in this map
+ */
+ public DualHashBidiMap(final Map<? extends K, ? extends V> map) {
+ super(new HashMap<K, V>(), new HashMap<V, K>());
+ putAll(map);
+ }
+
+ /**
+ * Constructs a <code>HashBidiMap</code> 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<K, V> normalMap, final Map<V, K> reverseMap,
+ final BidiMap<V, K> 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<V, K> createBidiMap(final Map<V, K> normalMap, final Map<K, V> reverseMap,
+ final BidiMap<K, V> 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<K, V> map = (Map<K, V>) in.readObject();
+ putAll(map);
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/DualTreeBidiMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/DualTreeBidiMap.java
new file mode 100644
index 0000000..a87e620
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/DualTreeBidiMap.java
@@ -0,0 +1,411 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+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;
+
+/**
+ * Implementation of {@link BidiMap} that uses two {@link TreeMap} instances.
+ * <p>
+ * The setValue() method on iterators will succeed only if the new value being set is
+ * not already in the bidimap.
+ * </p>
+ * <p>
+ * 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.
+ * </p>
+ * <p>
+ * NOTE: From Commons Collections 3.1, all subclasses will use {@link TreeMap}
+ * and the flawed <code>createMap</code> method is ignored.
+ * </p>
+ *
+ * @param <K> the type of the keys in this map
+ * @param <V> the type of the values in this map
+ * @since 3.0
+ */
+public class DualTreeBidiMap<K, V> extends AbstractDualBidiMap<K, V>
+ implements SortedBidiMap<K, V>, Serializable {
+
+ /** Ensure serialization compatibility */
+ private static final long serialVersionUID = 721969328361809L;
+
+ /** The key comparator to use */
+ private final Comparator<? super K> comparator;
+
+ /** The value comparator to use */
+ private final Comparator<? super V> valueComparator;
+
+ /**
+ * Creates an empty <code>DualTreeBidiMap</code>
+ */
+ public DualTreeBidiMap() {
+ super(new TreeMap<K, V>(), new TreeMap<V, K>());
+ this.comparator = null;
+ this.valueComparator = null;
+ }
+
+ /**
+ * Constructs a <code>DualTreeBidiMap</code> and copies the mappings from
+ * specified <code>Map</code>.
+ *
+ * @param map the map whose mappings are to be placed in this map
+ */
+ public DualTreeBidiMap(final Map<? extends K, ? extends V> map) {
+ super(new TreeMap<K, V>(), new TreeMap<V, K>());
+ 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<? super K> keyComparator, final Comparator<? super V> valueComparator) {
+ super(new TreeMap<K, V>(keyComparator), new TreeMap<V, K>(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<K, V> normalMap, final Map<V, K> reverseMap,
+ final BidiMap<V, K> inverseBidiMap) {
+ super(normalMap, reverseMap, inverseBidiMap);
+ this.comparator = ((SortedMap<K, V>) normalMap).comparator();
+ this.valueComparator = ((SortedMap<V, K>) 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<V, K> createBidiMap(final Map<V, K> normalMap, final Map<K, V> reverseMap,
+ final BidiMap<K, V> inverseMap) {
+ return new DualTreeBidiMap<>(normalMap, reverseMap, inverseMap);
+ }
+
+ //-----------------------------------------------------------------------
+
+ @Override
+ public Comparator<? super K> comparator() {
+ return ((SortedMap<K, V>) normalMap).comparator();
+ }
+
+ @Override
+ public Comparator<? super V> valueComparator() {
+ return ((SortedMap<V, K>) reverseMap).comparator();
+ }
+
+ @Override
+ public K firstKey() {
+ return ((SortedMap<K, V>) normalMap).firstKey();
+ }
+
+ @Override
+ public K lastKey() {
+ return ((SortedMap<K, V>) normalMap).lastKey();
+ }
+
+ @Override
+ public K nextKey(final K key) {
+ if (isEmpty()) {
+ return null;
+ }
+ if (normalMap instanceof OrderedMap) {
+ return ((OrderedMap<K, ?>) normalMap).nextKey(key);
+ }
+ final SortedMap<K, V> sm = (SortedMap<K, V>) normalMap;
+ final Iterator<K> 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<K, V>) normalMap).previousKey(key);
+ }
+ final SortedMap<K, V> sm = (SortedMap<K, V>) normalMap;
+ final SortedMap<K, V> hm = sm.headMap(key);
+ if (hm.isEmpty()) {
+ return null;
+ }
+ return hm.lastKey();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Obtains an ordered map iterator.
+ * <p>
+ * This implementation copies the elements to an ArrayList in order to
+ * provide the forward/backward behaviour.
+ *
+ * @return a new ordered map iterator
+ */
+ @Override
+ public OrderedMapIterator<K, V> mapIterator() {
+ return new BidiOrderedMapIterator<>(this);
+ }
+
+ public SortedBidiMap<V, K> inverseSortedBidiMap() {
+ return inverseBidiMap();
+ }
+
+ public OrderedBidiMap<V, K> inverseOrderedBidiMap() {
+ return inverseBidiMap();
+ }
+
+ //-----------------------------------------------------------------------
+
+ @Override
+ public SortedMap<K, V> headMap(final K toKey) {
+ final SortedMap<K, V> sub = ((SortedMap<K, V>) normalMap).headMap(toKey);
+ return new ViewMap<>(this, sub);
+ }
+
+ @Override
+ public SortedMap<K, V> tailMap(final K fromKey) {
+ final SortedMap<K, V> sub = ((SortedMap<K, V>) normalMap).tailMap(fromKey);
+ return new ViewMap<>(this, sub);
+ }
+
+ @Override
+ public SortedMap<K, V> subMap(final K fromKey, final K toKey) {
+ final SortedMap<K, V> sub = ((SortedMap<K, V>) normalMap).subMap(fromKey, toKey);
+ return new ViewMap<>(this, sub);
+ }
+
+ @Override
+ public SortedBidiMap<V, K> inverseBidiMap() {
+ return (SortedBidiMap<V, K>) super.inverseBidiMap();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Internal sorted map view.
+ */
+ protected static class ViewMap<K, V> extends AbstractSortedMapDecorator<K, V> {
+ /**
+ * Constructor.
+ * @param bidi the parent bidi map
+ * @param sm the subMap sorted map
+ */
+ protected ViewMap(final DualTreeBidiMap<K, V> bidi, final SortedMap<K, V> 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<K> it = keySet().iterator(); it.hasNext();) {
+ it.next();
+ it.remove();
+ }
+ }
+
+ @Override
+ public SortedMap<K, V> headMap(final K toKey) {
+ return new ViewMap<>(decorated(), super.headMap(toKey));
+ }
+
+ @Override
+ public SortedMap<K, V> tailMap(final K fromKey) {
+ return new ViewMap<>(decorated(), super.tailMap(fromKey));
+ }
+
+ @Override
+ public SortedMap<K, V> subMap(final K fromKey, final K toKey) {
+ return new ViewMap<>(decorated(), super.subMap(fromKey, toKey));
+ }
+
+ @Override
+ protected DualTreeBidiMap<K, V> decorated() {
+ return (DualTreeBidiMap<K, V>) 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<K, V> implements OrderedMapIterator<K, V>, ResettableIterator<K> {
+
+ /** The parent map */
+ private final AbstractDualBidiMap<K, V> parent;
+
+ /** The iterator being decorated */
+ private ListIterator<Entry<K, V>> iterator;
+
+ /** The last returned entry */
+ private Entry<K, V> last = null;
+
+ /**
+ * Constructor.
+ * @param parent the parent map
+ */
+ protected BidiOrderedMapIterator(final AbstractDualBidiMap<K, V> parent) {
+ super();
+ 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<K, V> map = (Map<K, V>) in.readObject();
+ putAll(map);
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyIterator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyIterator.java
new file mode 100644
index 0000000..ef8c209
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyIterator.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Iterator;
+
+/**
+ * Provides an implementation of an empty iterator.
+ * <p>
+ * 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</code>.
+ *
+ * @since 2.1.1 and 3.1
+ */
+public class EmptyIterator<E> extends AbstractEmptyIterator<E> implements ResettableIterator<E> {
+
+ /**
+ * 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 <E> the element type
+ * @return ResettableIterator<E>
+ */
+ public static <E> ResettableIterator<E> resettableEmptyIterator() {
+ return RESETTABLE_INSTANCE;
+ }
+
+ /**
+ * Get a typed empty iterator instance.
+ * @param <E> the element type
+ * @return Iterator<E>
+ */
+ public static <E> Iterator<E> emptyIterator() {
+ return INSTANCE;
+ }
+
+ /**
+ * Constructor.
+ */
+ protected EmptyIterator() {
+ super();
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyMapIterator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyMapIterator.java
new file mode 100644
index 0000000..adbb1aa
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyMapIterator.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+/**
+ * Provides an implementation of an empty map iterator.
+ *
+ * @param <K> the type of keys
+ * @param <V> the type of mapped values
+ * @since 3.1
+ */
+public class EmptyMapIterator<K, V> extends AbstractEmptyMapIterator<K, V> implements
+ MapIterator<K, V>, ResettableIterator<K> {
+
+ /**
+ * 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 <K> the key type
+ * @param <V> the value type
+ * @return {@link MapIterator}<K, V>
+ */
+ public static <K, V> MapIterator<K, V> emptyMapIterator() {
+ return INSTANCE;
+ }
+
+ /**
+ * Constructor.
+ */
+ protected EmptyMapIterator() {
+ super();
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyOrderedIterator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyOrderedIterator.java
new file mode 100644
index 0000000..5e6264a
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyOrderedIterator.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+/**
+ * Provides an implementation of an empty ordered iterator.
+ *
+ * @param <E> the type to iterate.
+ * @since 3.1
+ */
+public class EmptyOrderedIterator<E> extends AbstractEmptyIterator<E>
+ implements OrderedIterator<E>, ResettableIterator<E> {
+
+ /**
+ * Singleton instance of the iterator.
+ * @since 3.1
+ */
+ @SuppressWarnings("rawtypes")
+ public static final OrderedIterator INSTANCE = new EmptyOrderedIterator<>();
+
+ /**
+ * Typed instance of the iterator.
+ * @param <E> the element type
+ * @return OrderedIterator<E>
+ */
+ public static <E> OrderedIterator<E> emptyOrderedIterator() {
+ return INSTANCE;
+ }
+
+ /**
+ * Constructor.
+ */
+ protected EmptyOrderedIterator() {
+ super();
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyOrderedMapIterator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyOrderedMapIterator.java
new file mode 100644
index 0000000..f85464d
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EmptyOrderedMapIterator.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+/**
+ * Provides an implementation of an empty ordered map iterator.
+ *
+ * @param <K> the type of keys
+ * @param <V> the type of mapped values
+ * @since 3.1
+ */
+public class EmptyOrderedMapIterator<K, V> extends AbstractEmptyMapIterator<K, V>
+ implements OrderedMapIterator<K, V>, ResettableIterator<K> {
+
+ /**
+ * 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 <K> the key type
+ * @param <V> the value type
+ * @return {@link OrderedMapIterator}<K, V>
+ */
+ public static <K, V> OrderedMapIterator<K, V> emptyOrderedMapIterator() {
+ return INSTANCE;
+ }
+
+ /**
+ * Constructor.
+ */
+ protected EmptyOrderedMapIterator() {
+ super();
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EntrySetToMapIteratorAdapter.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EntrySetToMapIteratorAdapter.java
new file mode 100644
index 0000000..310874e
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/EntrySetToMapIteratorAdapter.java
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Adapts a Map entrySet to the MapIterator interface.
+ *
+ * @param <K> the type of the keys in the map
+ * @param <V> the type of the values in the map
+ *
+ * @since 4.0
+ */
+public class EntrySetToMapIteratorAdapter<K, V> implements MapIterator<K, V>, ResettableIterator<K> {
+
+ /** The adapted Map entry Set. */
+ Set<Map.Entry<K, V>> entrySet;
+
+ /** The resettable iterator in use. */
+ transient Iterator<Map.Entry<K, V>> iterator;
+
+ /** The currently positioned Map entry. */
+ transient Map.Entry<K, V> entry;
+
+ /**
+ * Create a new EntrySetToMapIteratorAdapter.
+ * @param entrySet the entrySet to adapt
+ */
+ public EntrySetToMapIteratorAdapter(final Set<Map.Entry<K, V>> 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<K, V> current() {
+ if (entry == null) {
+ throw new IllegalStateException();
+ }
+ return entry;
+ }
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/FilterIterator.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/FilterIterator.java
new file mode 100644
index 0000000..a112362
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/FilterIterator.java
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.function.Predicate;
+
+/**
+ * Decorates another {@link Iterator} using a predicate to filter elements.
+ * <p>
+ * This iterator decorates the underlying iterator, only allowing through
+ * those elements that match the specified {@link Predicate Predicate}.
+ *
+ * @since 1.0
+ */
+public class FilterIterator<E> implements Iterator<E> {
+
+ /** The iterator being used */
+ private Iterator<? extends E> iterator;
+ /** The predicate being used */
+ private Predicate<? super E> predicate;
+ /** The next object in the iteration */
+ private E nextObject;
+ /** Whether the next object has been calculated yet */
+ private boolean nextObjectSet = false;
+
+ //-----------------------------------------------------------------------
+ /**
+ * Constructs a new <code>FilterIterator</code> that will not function
+ * until {@link #setIterator(Iterator) setIterator} is invoked.
+ */
+ public FilterIterator() {
+ super();
+ }
+
+ /**
+ * Constructs a new <code>FilterIterator</code> that will not function
+ * until {@link #setPredicate(Predicate) setPredicate} is invoked.
+ *
+ * @param iterator the iterator to use
+ */
+ public FilterIterator(final Iterator<? extends E> iterator) {
+ super();
+ this.iterator = iterator;
+ }
+
+ /**
+ * Constructs a new <code>FilterIterator</code> that will use the
+ * given iterator and predicate.
+ *
+ * @param iterator the iterator to use
+ * @param predicate the predicate to use
+ */
+ public FilterIterator(final Iterator<? extends E> iterator, final Predicate<? super E> predicate) {
+ super();
+ this.iterator = iterator;
+ this.predicate = predicate;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns true if the underlying iterator contains an object that
+ * matches the predicate.
+ *
+ * @return true if there is another object that matches the predicate
+ * @throws NullPointerException if either the iterator or predicate are null
+ */
+ @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()</code> was called, but not after
+ * <code>hasNext()</code>, because the <code>hasNext()</code> call
+ * changes the base iterator.
+ *
+ * @throws IllegalStateException if <code>hasNext()</code> 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<? extends E> 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<? extends E> iterator) {
+ this.iterator = iterator;
+ nextObject = null;
+ nextObjectSet = false;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the predicate this iterator is using.
+ *
+ * @return the predicate
+ */
+ public Predicate<? super E> getPredicate() {
+ return predicate;
+ }
+
+ /**
+ * Sets the predicate this the iterator to use.
+ *
+ * @param predicate the predicate to use
+ */
+ public void setPredicate(final Predicate<? super E> 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.test(object)) {
+ nextObject = object;
+ nextObjectSet = true;
+ return true;
+ }
+ }
+ return false;
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/IterableMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/IterableMap.java
new file mode 100644
index 0000000..b40b019
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/IterableMap.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Map;
+
+/**
+ * Defines a map that can be iterated directly without needing to create an entry set.
+ * <p>
+ * 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.
+ * </p>
+ * <pre>
+ * 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);
+ * }
+ * </pre>
+ *
+ * @param <K> the type of the keys in this map
+ * @param <V> the type of the values in this map
+ *
+ * @since 3.0
+ */
+public interface IterableMap<K, V> extends Map<K, V> {
+ /**
+ * @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</code>, or
+ * <code>null</code> if there was no mapping for <code>key</code>.
+ * (A <code>null</code> return can also indicate that the map
+ * previously associated <code>null</code> with <code>key</code>,
+ * if the implementation supports <code>null</code> values.)
+ * @see Map#put(Object, Object)
+ */
+ V put(K key, V value);
+
+ /**
+ * @param t mappings to be stored in this map
+ * @see Map#putAll(Map)
+ */
+ void putAll(Map<? extends K, ? extends V> t);
+
+ /**
+ * Obtains a <code>MapIterator</code> over the map.
+ * <p>
+ * 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.
+ * <pre>
+ * 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);
+ * }
+ * </pre>
+ *
+ * @return a map iterator
+ */
+ MapIterator<K, V> mapIterator();
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/IterableSortedMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/IterableSortedMap.java
new file mode 100644
index 0000000..e08ea83
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/IterableSortedMap.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.SortedMap;
+
+/**
+ * {@link SortedMap} + {@link OrderedMap}.
+ *
+ * @param <K> the type of the keys in the map
+ * @param <V> the type of the values in the map
+ *
+ * @since 4.0
+ */
+public interface IterableSortedMap<K, V> extends SortedMap<K, V>, OrderedMap<K, V> {
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/IteratorChain.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/IteratorChain.java
new file mode 100644
index 0000000..734dd48
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/IteratorChain.java
@@ -0,0 +1,280 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Queue;
+
+/**
+ * An IteratorChain is an Iterator that wraps a number of Iterators.
+ * <p>
+ * 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.
+ * <p>
+ * 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.
+ * <p>
+ * Calling a method that adds new Iterator <i>after a method in the Iterator
+ * interface has been called</i> will result in an UnsupportedOperationException.
+ * <p>
+ * NOTE: As from version 3.0, the IteratorChain may contain no iterators. In
+ * this case the class will function as an empty iterator.
+ * <p>
+ * 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<E> implements Iterator<E> {
+
+ /** The chain of iterators */
+ private final Queue<Iterator<? extends E>> iteratorChain = new LinkedList<>();
+
+ /** The current iterator */
+ private Iterator<? extends E> currentIterator = null;
+
+ /**
+ * The "last used" Iterator is the Iterator upon which next() or hasNext()
+ * was most recently called used for the remove() operation only
+ */
+ private Iterator<? extends E> lastUsedIterator = null;
+
+ /**
+ * ComparatorChain is "locked" after the first time compare(Object,Object)
+ * is called
+ */
+ private boolean isLocked = false;
+
+ //-----------------------------------------------------------------------
+ /**
+ * Construct an IteratorChain with no Iterators.
+ * <p>
+ * You will normally use {@link #addIterator(Iterator)} to add some
+ * iterators after using this constructor.
+ */
+ public IteratorChain() {
+ super();
+ }
+
+ /**
+ * Construct an IteratorChain with a single Iterator.
+ * <p>
+ * 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.
+ * <p>
+ * 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<? extends E> iterator) {
+ super();
+ addIterator(iterator);
+ }
+
+ /**
+ * Constructs a new <code>IteratorChain</code> over the two given iterators.
+ * <p>
+ * 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<? extends E> first, final Iterator<? extends E> second) {
+ super();
+ addIterator(first);
+ addIterator(second);
+ }
+
+ /**
+ * Constructs a new <code>IteratorChain</code> over the array of iterators.
+ * <p>
+ * 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<? extends E>... iteratorChain) {
+ super();
+ for (final Iterator<? extends E> element : iteratorChain) {
+ addIterator(element);
+ }
+ }
+
+ /**
+ * Constructs a new <code>IteratorChain</code> over the collection of
+ * iterators.
+ * <p>
+ * 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<Iterator<? extends E>> iteratorChain) {
+ super();
+ for (final Iterator<? extends E> 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<? extends E> iterator) {
+ checkLocked();
+ if (iterator == null) {
+ throw new NullPointerException("Iterator must not be null");
+ }
+ iteratorChain.add(iterator);
+ }
+
+ /**
+ * Returns the remaining number of Iterators in the current IteratorChain.
+ *
+ * @return Iterator count
+ */
+ public int size() {
+ return iteratorChain.size();
+ }
+
+ /**
+ * Determine if modifications can still be made to the IteratorChain.
+ * IteratorChains cannot be modified once they have executed a method from
+ * the Iterator interface.
+ *
+ * @return true if IteratorChain cannot be modified, false if it can
+ */
+ public boolean isLocked() {
+ return isLocked;
+ }
+
+ /**
+ * Checks whether the iterator chain is now locked and in use.
+ */
+ private void checkLocked() {
+ if (isLocked == true) {
+ throw new UnsupportedOperationException(
+ "IteratorChain cannot be changed after the first use of a method from the Iterator interface");
+ }
+ }
+
+ /**
+ * Lock the chain so no more iterators can be added. This must be called
+ * from all Iterator interface methods.
+ */
+ private void lockChain() {
+ if (isLocked == false) {
+ isLocked = true;
+ }
+ }
+
+ /**
+ * Updates the current iterator field to ensure that the current Iterator is
+ * not exhausted
+ */
+ protected void updateCurrentIterator() {
+ if (currentIterator == null) {
+ if (iteratorChain.isEmpty()) {
+ currentIterator = EmptyIterator.<E> emptyIterator();
+ } else {
+ currentIterator = iteratorChain.remove();
+ }
+ // set last used iterator here, in case the user calls remove
+ // before calling hasNext() or next() (although they shouldn't)
+ lastUsedIterator = currentIterator;
+ }
+
+ while (currentIterator.hasNext() == false && !iteratorChain.isEmpty()) {
+ currentIterator = iteratorChain.remove();
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Return true if any Iterator in the IteratorChain has a remaining element.
+ *
+ * @return true if elements remain
+ */
+ @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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/KeyValue.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/KeyValue.java
new file mode 100644
index 0000000..c5d7ed3
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/KeyValue.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+/**
+ * Defines a simple key value pair.
+ * <p>
+ * 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.
+ * </p>
+ *
+ * @param <K> the type of the key
+ * @param <V> the type of the value
+ * @since 3.0
+ */
+public interface KeyValue<K, V> {
+
+ /**
+ * 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/LRUMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/LRUMap.java
new file mode 100644
index 0000000..46a8130
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/LRUMap.java
@@ -0,0 +1,530 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.Map;
+
+/**
+ * A <code>Map</code> implementation with a fixed maximum size which removes
+ * the least recently used entry if an entry is added when full.
+ * <p>
+ * 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.
+ * </p>
+ * <p>
+ * 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 MapIterator} or {@link #entrySet()} iterator.
+ * </p>
+ * <p>
+ * The map implements <code>OrderedMap</code> and entries may be queried using
+ * the bidirectional <code>OrderedMapIterator</code>. The order returned is
+ * least recently used to most recently used. Iterators from map views can
+ * also be cast to <code>OrderedIterator</code> if required.
+ * </p>
+ * <p>
+ * All the available iterators can be reset back to the start by casting to
+ * <code>ResettableIterator</code> and calling <code>reset()</code>.
+ * </p>
+ * <p>
+ * <strong>Note that LRUMap is not synchronized and is not thread-safe.</strong>
+ * 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</code>'s when accessed by concurrent threads.
+ * </p>
+ *
+ * @param <K> the type of the keys in this map
+ * @param <V> the type of the values in this map
+ * @since 3.0 (previously in main package v1.0)
+ */
+public class LRUMap<K, V>
+ extends AbstractLinkedMap<K, V> implements BoundedMap<K, V>, Serializable, Cloneable {
+
+ /** Serialisation version */
+ private static final long serialVersionUID = -612114643488955218L;
+ /** Default maximum size */
+ protected static final int DEFAULT_MAX_SIZE = 100;
+
+ /** Maximum size */
+ private transient int maxSize;
+ /** Scan behaviour */
+ private boolean scanUntilRemovable;
+
+ /**
+ * Constructs a new empty map with a maximum size of 100.
+ */
+ public LRUMap() {
+ this(DEFAULT_MAX_SIZE, DEFAULT_LOAD_FACTOR, false);
+ }
+
+ /**
+ * Constructs a new, empty map with the specified maximum size.
+ *
+ * @param maxSize the maximum size of the map
+ * @throws IllegalArgumentException if the maximum size is less than one
+ */
+ public LRUMap(final int maxSize) {
+ this(maxSize, DEFAULT_LOAD_FACTOR);
+ }
+
+ /**
+ * Constructs a new, empty map with the specified maximum size.
+ *
+ * @param maxSize the maximum size of the map
+ * @param 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 removeable entry is found, default false
+ * @throws IllegalArgumentException if the maximum size is less than one
+ * @since 3.1
+ */
+ public LRUMap(final int maxSize, final boolean scanUntilRemovable) {
+ this(maxSize, DEFAULT_LOAD_FACTOR, scanUntilRemovable);
+ }
+
+ /**
+ * Constructs a new, empty map with the specified 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 removeable entry is found, default false
+ * @throws IllegalArgumentException if the maximum size is less than one
+ * @throws IllegalArgumentException if the load factor is less than zero
+ * @since 3.1
+ */
+ public LRUMap(final int maxSize, final float loadFactor, final boolean scanUntilRemovable) {
+ 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 removeable 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 greather than max size");
+ }
+ this.maxSize = maxSize;
+ this.scanUntilRemovable = scanUntilRemovable;
+ }
+
+ /**
+ * Constructor copying elements from another map.
+ * <p>
+ * 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<? extends K, ? extends V> map) {
+ this(map, false);
+ }
+
+ /**
+ * Constructor copying elements from another map.
+ *
+ * <p>The maximum size is set from the map's size.</p>
+ *
+ * @param map the map to copy
+ * @param scanUntilRemovable scan until a removeable entry is found, default false
+ * @throws NullPointerException if the map is null
+ * @throws IllegalArgumentException if the map is empty
+ * @since 3.1
+ */
+ public LRUMap(final Map<? extends K, ? extends V> map, final boolean scanUntilRemovable) {
+ this(map.size(), DEFAULT_LOAD_FACTOR, scanUntilRemovable);
+ putAll(map);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the value mapped to the key specified.
+ * <p>
+ * 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.
+ * <p>
+ * 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<K, V> 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.
+ * <p>
+ * This implementation moves the updated entry to the end of the list.
+ *
+ * @param entry the entry to update
+ */
+ protected void moveToMRU(final LinkEntry<K, V> 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.
+ * <p>
+ * This implementation moves the updated entry to the end of the list
+ * using {@link #moveToMRU(LinkEntry)}.
+ *
+ * @param entry the entry to update
+ * @param newValue the new value to store
+ */
+ @Override
+ protected void updateEntry(final HashEntry<K, V> entry, final V newValue) {
+ moveToMRU((LinkEntry<K, V>) entry); // handles modCount
+ entry.setValue(newValue);
+ }
+
+ /**
+ * Adds a new key-value mapping into this map.
+ * <p>
+ * This implementation checks the LRU size and determines whether to
+ * discard an entry or not using {@link #removeLRU(LinkEntry)}.
+ * <p>
+ * From Commons Collections 3.1 this method uses {@link #isFull()} rather
+ * than accessing <code>size</code> and <code>maxSize</code> 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<K, V> 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 have 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 have 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.
+ * <p>
+ * 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<K, V> 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<K, V>[] tmp = data; // may protect against some sync issues
+ HashEntry<K, V> loop = tmp[removeIndex];
+ HashEntry<K, V> 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.
+ * <p>
+ * This method exists for subclasses to override. A subclass may wish to
+ * provide cleanup of resources when an entry is removed. For example:
+ * <pre>
+ * protected boolean removeLRU(LinkEntry entry) {
+ * releaseResources(entry.getValue()); // release resources held by entry
+ * return true; // actually delete entry
+ * }
+ * </pre>
+ * <p>
+ * Alternatively, a subclass may choose to not remove the entry or selectively
+ * keep certain LRU entries. For example:
+ * <pre>
+ * protected boolean removeLRU(LinkEntry entry) {
+ * if (entry.getKey().toString().startsWith("System.")) {
+ * return false; // entry not removed from LRUMap
+ * } else {
+ * return true; // actually delete entry
+ * }
+ * }
+ * </pre>
+ * 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.
+ * <p>
+ * 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<K, V> entry) {
+ return true;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns true if this map is full and no new mappings can be added.
+ *
+ * @return <code>true</code> 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<K, V> clone() {
+ return (LRUMap<K, V>) 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()</code> 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()</code> 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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/LinkedMap.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/LinkedMap.java
new file mode 100644
index 0000000..6c6faf4
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/LinkedMap.java
@@ -0,0 +1,321 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+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;
+
+/**
+ * A <code>Map</code> implementation that maintains the order of the entries.
+ * In this implementation order is maintained by original insertion.
+ * <p>
+ * This implementation improves on the JDK1.4 LinkedHashMap by adding the
+ * {@link MapIterator}
+ * functionality, additional convenience methods and allowing
+ * bidirectional iteration. It also implements <code>OrderedMap</code>.
+ * In addition, non-interface methods are provided to access the map by index.
+ * </p>
+ * <p>
+ * The <code>orderedMapIterator()</code> method provides direct access to a
+ * bidirectional iterator. The iterators from the other views can also be cast
+ * to <code>OrderedIterator</code> if required.
+ * </p>
+ * <p>
+ * All the available iterators can be reset back to the start by casting to
+ * <code>ResettableIterator</code> and calling <code>reset()</code>.
+ * </p>
+ * <p>
+ * The implementation is also designed to be subclassed, with lots of useful
+ * methods exposed.
+ * </p>
+ * <p>
+ * <strong>Note that LinkedMap is not synchronized and is not thread-safe.</strong>
+ * 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.
+ * </p>
+ *
+ * @param <K> the type of the keys in this map
+ * @param <V> the type of the values in this map
+ * @since 3.0
+ */
+public class LinkedMap<K, V> extends AbstractLinkedMap<K, V> 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<? extends K, ? extends V> map) {
+ super(map);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Clones the map without cloning the keys or values.
+ *
+ * @return a shallow clone
+ */
+ @Override
+ public LinkedMap<K, V> clone() {
+ return (LinkedMap<K, V>) 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<K, V> entry = header.after; entry != header; entry = entry.after, i++) {
+ if (isEqualKey(key, entry.key)) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * Removes the element at the specified index.
+ *
+ * @param index the index of the object to remove
+ * @return the previous value corresponding the <code>key</code>,
+ * or <code>null</code> 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.
+ * <p>
+ * The returned list is unmodifiable because changes to the values of
+ * the list (using {@link 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.
+ * <p>
+ * An alternative to this method is to use {@link #keySet()}.
+ *
+ * @see #keySet()
+ * @return The ordered list of keys.
+ */
+ public List<K> asList() {
+ return new LinkedMapList<>(this);
+ }
+
+ /**
+ * List view of map.
+ */
+ static class LinkedMapList<K> extends AbstractList<K> {
+
+ private final LinkedMap<K, ?> parent;
+
+ LinkedMapList(final LinkedMap<K, ?> 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<? super K> 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> T[] toArray(final T[] array) {
+ return parent.keySet().toArray(array);
+ }
+
+ @Override
+ public Iterator<K> iterator() {
+ return UnmodifiableIterator.unmodifiableIterator(parent.keySet().iterator());
+ }
+
+ @Override
+ public ListIterator<K> listIterator() {
+ return UnmodifiableListIterator.umodifiableListIterator(super.listIterator());
+ }
+
+ @Override
+ public ListIterator<K> listIterator(final int fromIndex) {
+ return UnmodifiableListIterator.umodifiableListIterator(super.listIterator(fromIndex));
+ }
+
+ @Override
+ public List<K> subList(final int fromIndexInclusive, final int toIndexExclusive) {
+ return UnmodifiableList.unmodifiableList(super.subList(fromIndexInclusive, toIndexExclusive));
+ }
+ }
+
+}
diff --git a/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/ListIteratorWrapper.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/ListIteratorWrapper.java
new file mode 100644
index 0000000..b9de65e
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/ListIteratorWrapper.java
@@ -0,0 +1,269 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+
+/**
+ * Converts an {@link Iterator} into a {@link ResettableListIterator}.
+ * For plain <code>Iterator</code>s this is accomplished by caching the returned
+ * elements. This class can also be used to simply add
+ * {@link ResettableIterator}
+ * functionality to a given {@link ListIterator}.
+ * <p>
+ * The <code>ListIterator</code> interface has additional useful methods
+ * for navigation - <code>previous()</code> and the index methods.
+ * This class allows a regular <code>Iterator</code> to behave as a
+ * <code>ListIterator</code>. It achieves this by building a list internally
+ * of as the underlying iterator is traversed.
+ * <p>
+ * The optional operations of <code>ListIterator</code> are not supported for plain <code>Iterator</code>s.
+ * <p>
+ * This class implements ResettableListIterator from Commons Collections 3.2.
+ *
+ * @since 2.1
+ */
+public class ListIteratorWrapper<E> implements ResettableListIterator<E> {
+
+ /** 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<? extends E> iterator;
+ /** The list being used to cache the iterator. */
+ private final List<E> list = new ArrayList<>();
+
+ /** The current index of this iterator. */
+ private int currentIndex = 0;
+ /** The current index of the wrapped iterator. */
+ private int wrappedIteratorIndex = 0;
+ /** recall whether the wrapped iterator's "cursor" is in such a state as to allow remove() to be called */
+ private boolean removeState;
+
+ // Constructor
+ //-------------------------------------------------------------------------
+ /**
+ * Constructs a new <code>ListIteratorWrapper</code> that will wrap
+ * the given iterator.
+ *
+ * @param iterator the iterator to wrap
+ * @throws NullPointerException if the iterator is null
+ */
+ public ListIteratorWrapper(final Iterator<? extends E> iterator) {
+ super();
+ if (iterator == null) {
+ throw new NullPointerException("Iterator must not be null");
+ }
+ this.iterator = iterator;
+ }
+
+ // ListIterator interface
+ //-------------------------------------------------------------------------
+ /**
+ * Throws {@link UnsupportedOperationException}
+ * unless the underlying <code>Iterator</code> is a <code>ListIterator</code>.
+ *
+ * @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<E> li = (ListIterator<E>) 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<E> li = (ListIterator<E>) 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;
+ }
+
+ /**
+ * Throws {@link UnsupportedOperationException} if {@link #previous()} has ever been called.
+ *
+ * @throws UnsupportedOperationException always
+ */
+ @Override
+ public void remove() throws UnsupportedOperationException {
+ if (iterator instanceof ListIterator) {
+ iterator.remove();
+ return;
+ }
+ int removeIndex = currentIndex;
+ if (currentIndex == wrappedIteratorIndex) {
+ --removeIndex;
+ }
+ if (!removeState || wrappedIteratorIndex - currentIndex > 1) {
+ throw new IllegalStateException(MessageFormat.format(CANNOT_REMOVE_MESSAGE, Integer.valueOf(removeIndex)));
+ }
+ iterator.remove();
+ list.remove(removeIndex);
+ currentIndex = removeIndex;
+ wrappedIteratorIndex--;
+ removeState = false;
+ }
+
+ /**
+ * Throws {@link UnsupportedOperationException}
+ * unless the underlying <code>Iterator</code> is a <code>ListIterator</code>.
+ *
+ * @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<E> li = (ListIterator<E>) iterator;
+ li.set(obj);
+ return;
+ }
+ throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE);
+ }
+
+ // ResettableIterator interface
+ //-------------------------------------------------------------------------
+ /**
+ * Resets this iterator back to the position at which the iterator
+ * was created.
+ *
+ * @since 3.2
+ */
+ @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/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/MapBackedSet.java b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/MapBackedSet.java
new file mode 100644
index 0000000..d1d7f3a
--- /dev/null
+++ b/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/collections/MapBackedSet.java
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.openjpa.lib.util.collections;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Iterator;
... 4951 lines suppressed ...