Unnamed: 0
int64
0
2.1k
func
stringlengths
30
107k
target
bool
2 classes
project
stringlengths
62
145
0
public abstract class AbstractEntryIterator<K, V, T> implements OLazyIterator<T>, OResettable { OMVRBTree<K, V> tree; OMVRBTreeEntry<K, V> begin; OMVRBTreeEntry<K, V> next; OMVRBTreeEntry<K, V> lastReturned; int expectedModCount; int pageIndex; AbstractEntryIterator(final OMVRBTreeEntry<K, V> start) { begin = start; init(); } private void init() { if (begin == null) // IN CASE OF ABSTRACTMAP.HASHCODE() return; tree = begin.getTree(); next = begin; expectedModCount = tree.modCount; lastReturned = null; pageIndex = begin.getTree().getPageIndex() > -1 ? begin.getTree().getPageIndex() - 1 : -1; } @Override public void reset() { init(); } public boolean hasNext() { if (tree != null && expectedModCount != tree.modCount) { // CONCURRENT CHANGE: TRY TO REUSE LAST POSITION pageIndex--; expectedModCount = tree.modCount; } return next != null && (pageIndex < next.getSize() - 1 || OMVRBTree.successor(next) != null); } public final boolean hasPrevious() { if (tree != null && expectedModCount != tree.modCount) { // CONCURRENT CHANGE: TRY TO REUSE LAST POSITION pageIndex = -1; expectedModCount = tree.modCount; } return next != null && (pageIndex > 0 || OMVRBTree.predecessor(next) != null); } final K nextKey() { return nextEntry().getKey(pageIndex); } final V nextValue() { return nextEntry().getValue(pageIndex); } final V prevValue() { return prevEntry().getValue(pageIndex); } final OMVRBTreeEntry<K, V> nextEntry() { if (next == null) throw new NoSuchElementException(); if (pageIndex < next.getSize() - 1) { // ITERATE INSIDE THE NODE pageIndex++; } else { // GET THE NEXT NODE if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); next = OMVRBTree.successor(next); pageIndex = 0; } lastReturned = next; tree.pageIndex = pageIndex; return next; } final OMVRBTreeEntry<K, V> prevEntry() { if (next == null) throw new NoSuchElementException(); if (pageIndex > 0) { // ITERATE INSIDE THE NODE pageIndex--; } else { if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); next = OMVRBTree.predecessor(next); pageIndex = next != null ? next.getSize() - 1 : -1; } lastReturned = next; return next; } @SuppressWarnings("unchecked") public T update(final T iValue) { if (lastReturned == null) throw new IllegalStateException(); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); tree.pageIndex = pageIndex; return (T) next.setValue((V) iValue); } public void remove() { if (lastReturned == null) throw new IllegalStateException(); if (tree.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.getLeft() != null && lastReturned.getRight() != null) next = lastReturned; tree.pageIndex = pageIndex; next = tree.deleteEntry(lastReturned); pageIndex--; expectedModCount = tree.modCount; lastReturned = null; } }
false
commons_src_main_java_com_orientechnologies_common_collection_AbstractEntryIterator.java
1
public final class OAlwaysGreaterKey implements Comparable<Comparable<?>>{ public int compareTo(Comparable<?> o) { return 1; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OAlwaysGreaterKey.java
2
public final class OAlwaysLessKey implements Comparable<Comparable<?>> { public int compareTo(Comparable<?> o) { return -1; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OAlwaysLessKey.java
3
public class OCompositeKey implements Comparable<OCompositeKey>, Serializable { private static final long serialVersionUID = 1L; /** * List of heterogeneous values that are going to be stored in {@link OMVRBTree}. */ private final List<Object> keys; private final Comparator<Object> comparator; public OCompositeKey(final List<?> keys) { this.keys = new ArrayList<Object>(keys.size()); this.comparator = ODefaultComparator.INSTANCE; for (final Object key : keys) addKey(key); } public OCompositeKey(final Object... keys) { this.keys = new ArrayList<Object>(keys.length); this.comparator = ODefaultComparator.INSTANCE; for (final Object key : keys) addKey(key); } public OCompositeKey() { this.keys = new ArrayList<Object>(); this.comparator = ODefaultComparator.INSTANCE; } /** * Clears the keys array for reuse of the object */ public void reset() { if (this.keys != null) this.keys.clear(); } /** * @return List of heterogeneous values that are going to be stored in {@link OMVRBTree}. */ public List<Object> getKeys() { return Collections.unmodifiableList(keys); } /** * Add new key value to the list of already registered values. * * If passed in value is {@link OCompositeKey} itself then its values will be copied in current index. But key itself will not be * added. * * @param key * Key to add. */ public void addKey(final Object key) { if (key instanceof OCompositeKey) { final OCompositeKey compositeKey = (OCompositeKey) key; for (final Object inKey : compositeKey.keys) { addKey(inKey); } } else { keys.add(key); } } /** * Performs partial comparison of two composite keys. * * Two objects will be equal if the common subset of their keys is equal. For example if first object contains two keys and second * contains four keys then only first two keys will be compared. * * @param otherKey * Key to compare. * * @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified * object. */ public int compareTo(final OCompositeKey otherKey) { final Iterator<Object> inIter = keys.iterator(); final Iterator<Object> outIter = otherKey.keys.iterator(); while (inIter.hasNext() && outIter.hasNext()) { final Object inKey = inIter.next(); final Object outKey = outIter.next(); if (outKey instanceof OAlwaysGreaterKey) return -1; if (outKey instanceof OAlwaysLessKey) return 1; final int result = comparator.compare(inKey, outKey); if (result != 0) return result; } return 0; } /** * {@inheritDoc } */ @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final OCompositeKey that = (OCompositeKey) o; return keys.equals(that.keys); } /** * {@inheritDoc } */ @Override public int hashCode() { return keys.hashCode(); } /** * {@inheritDoc } */ @Override public String toString() { return "OCompositeKey{" + "keys=" + keys + '}'; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OCompositeKey.java
4
@Test public class OCompositeKeyTest { @Test public void testEqualSameKeys() { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey("a"); compositeKey.addKey("b"); final OCompositeKey anotherCompositeKey = new OCompositeKey(); anotherCompositeKey.addKey("a"); anotherCompositeKey.addKey("b"); assertTrue(compositeKey.equals(anotherCompositeKey)); assertTrue(compositeKey.hashCode() == anotherCompositeKey.hashCode()); } @Test public void testEqualNotSameKeys() { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey("a"); compositeKey.addKey("b"); final OCompositeKey anotherCompositeKey = new OCompositeKey(); anotherCompositeKey.addKey("a"); anotherCompositeKey.addKey("b"); anotherCompositeKey.addKey("c"); assertFalse(compositeKey.equals(anotherCompositeKey)); } @Test public void testEqualNull() { final OCompositeKey compositeKey = new OCompositeKey(); assertFalse(compositeKey.equals(null)); } @Test public void testEqualSame() { final OCompositeKey compositeKey = new OCompositeKey(); assertTrue(compositeKey.equals(compositeKey)); } @Test public void testEqualDiffClass() { final OCompositeKey compositeKey = new OCompositeKey(); assertFalse(compositeKey.equals("1")); } @Test public void testAddKeyComparable() { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey("a"); assertEquals(compositeKey.getKeys().size(), 1); assertTrue(compositeKey.getKeys().contains("a")); } @Test public void testAddKeyComposite() { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey("a"); final OCompositeKey compositeKeyToAdd = new OCompositeKey(); compositeKeyToAdd.addKey("a"); compositeKeyToAdd.addKey("b"); compositeKey.addKey(compositeKeyToAdd); assertEquals(compositeKey.getKeys().size(), 3); assertTrue(compositeKey.getKeys().contains("a")); assertTrue(compositeKey.getKeys().contains("b")); } @Test public void testCompareToSame() { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey("a"); compositeKey.addKey("b"); final OCompositeKey anotherCompositeKey = new OCompositeKey(); anotherCompositeKey.addKey("a"); anotherCompositeKey.addKey("b"); assertEquals(compositeKey.compareTo(anotherCompositeKey), 0); } @Test public void testCompareToPartiallyOneCase() { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey("a"); compositeKey.addKey("b"); final OCompositeKey anotherCompositeKey = new OCompositeKey(); anotherCompositeKey.addKey("a"); anotherCompositeKey.addKey("b"); anotherCompositeKey.addKey("c"); assertEquals(compositeKey.compareTo(anotherCompositeKey), 0); } @Test public void testCompareToPartiallySecondCase() { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey("a"); compositeKey.addKey("b"); compositeKey.addKey("c"); final OCompositeKey anotherCompositeKey = new OCompositeKey(); anotherCompositeKey.addKey("a"); anotherCompositeKey.addKey("b"); assertEquals(compositeKey.compareTo(anotherCompositeKey), 0); } @Test public void testCompareToGT() { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey("b"); final OCompositeKey anotherCompositeKey = new OCompositeKey(); anotherCompositeKey.addKey("a"); anotherCompositeKey.addKey("b"); assertEquals(compositeKey.compareTo(anotherCompositeKey), 1); } @Test public void testCompareToLT() { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey("a"); compositeKey.addKey("b"); final OCompositeKey anotherCompositeKey = new OCompositeKey(); anotherCompositeKey.addKey("b"); assertEquals(compositeKey.compareTo(anotherCompositeKey), -1); } @Test public void testCompareToSymmetryOne() { final OCompositeKey compositeKeyOne = new OCompositeKey(); compositeKeyOne.addKey(1); compositeKeyOne.addKey(2); final OCompositeKey compositeKeyTwo = new OCompositeKey(); compositeKeyTwo.addKey(1); compositeKeyTwo.addKey(3); compositeKeyTwo.addKey(1); assertEquals(compositeKeyOne.compareTo(compositeKeyTwo), -1); assertEquals(compositeKeyTwo.compareTo(compositeKeyOne), 1); } @Test public void testCompareToSymmetryTwo() { final OCompositeKey compositeKeyOne = new OCompositeKey(); compositeKeyOne.addKey(1); compositeKeyOne.addKey(2); final OCompositeKey compositeKeyTwo = new OCompositeKey(); compositeKeyTwo.addKey(1); compositeKeyTwo.addKey(2); compositeKeyTwo.addKey(3); assertEquals(compositeKeyOne.compareTo(compositeKeyTwo), 0); assertEquals(compositeKeyTwo.compareTo(compositeKeyOne), 0); } }
false
commons_src_test_java_com_orientechnologies_common_collection_OCompositeKeyTest.java
5
public class OIterableObject<T> implements Iterable<T>, OResettable, Iterator<T> { private final T object; private boolean alreadyRead = false; public OIterableObject(T o) { object = o; } /** * Returns an iterator over a set of elements of type T. * * @return an Iterator. */ public Iterator<T> iterator() { return this; } @Override public void reset() { alreadyRead = false; } @Override public boolean hasNext() { return !alreadyRead; } @Override public T next() { if (!alreadyRead) { alreadyRead = true; return object; } else throw new NoSuchElementException(); } @Override public void remove() { throw new UnsupportedOperationException("remove"); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OIterableObject.java
6
public class OIterableObjectArray<T> implements Iterable<T> { private final Object object; private int length; public OIterableObjectArray(Object o) { object = o; length = Array.getLength(o); } /** * Returns an iterator over a set of elements of type T. * * @return an Iterator. */ public Iterator<T> iterator() { return new ObjIterator(); } private class ObjIterator implements Iterator<T> { private int p = 0; /** * Returns <tt>true</tt> if the iteration has more elements. (In other words, returns <tt>true</tt> if <tt>next</tt> would * return an element rather than throwing an exception.) * * @return <tt>true</tt> if the iterator has more elements. */ public boolean hasNext() { return p < length; } /** * Returns the next element in the iteration. * * @return the next element in the iteration. * @throws java.util.NoSuchElementException * iteration has no more elements. */ @SuppressWarnings("unchecked") public T next() { if (p < length) { return (T) Array.get(object, p++); } else { throw new NoSuchElementException(); } } /** * Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be * called only once per call to <tt>next</tt>. The behavior of an iterator is unspecified if the underlying collection is * modified while the iteration is in progress in any way other than by calling this method. * * @throws UnsupportedOperationException * if the <tt>remove</tt> operation is not supported by this Iterator. * @throws IllegalStateException * if the <tt>next</tt> method has not yet been called, or the <tt>remove</tt> method has already been called after * the last call to the <tt>next</tt> method. */ public void remove() { throw new UnsupportedOperationException(); } } }
false
commons_src_main_java_com_orientechnologies_common_collection_OIterableObjectArray.java
7
private class ObjIterator implements Iterator<T> { private int p = 0; /** * Returns <tt>true</tt> if the iteration has more elements. (In other words, returns <tt>true</tt> if <tt>next</tt> would * return an element rather than throwing an exception.) * * @return <tt>true</tt> if the iterator has more elements. */ public boolean hasNext() { return p < length; } /** * Returns the next element in the iteration. * * @return the next element in the iteration. * @throws java.util.NoSuchElementException * iteration has no more elements. */ @SuppressWarnings("unchecked") public T next() { if (p < length) { return (T) Array.get(object, p++); } else { throw new NoSuchElementException(); } } /** * Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be * called only once per call to <tt>next</tt>. The behavior of an iterator is unspecified if the underlying collection is * modified while the iteration is in progress in any way other than by calling this method. * * @throws UnsupportedOperationException * if the <tt>remove</tt> operation is not supported by this Iterator. * @throws IllegalStateException * if the <tt>next</tt> method has not yet been called, or the <tt>remove</tt> method has already been called after * the last call to the <tt>next</tt> method. */ public void remove() { throw new UnsupportedOperationException(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OIterableObjectArray.java
8
public interface OLazyIterator<T> extends Iterator<T> { public T update(T iValue); }
false
commons_src_main_java_com_orientechnologies_common_collection_OLazyIterator.java
9
public class OLazyIteratorListWrapper<T> implements OLazyIterator<T> { private ListIterator<T> underlying; public OLazyIteratorListWrapper(ListIterator<T> iUnderlying) { underlying = iUnderlying; } public boolean hasNext() { return underlying.hasNext(); } public T next() { return underlying.next(); } public void remove() { underlying.remove(); } public T update(T e) { underlying.set(e); return null; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OLazyIteratorListWrapper.java
10
@SuppressWarnings("serial") public class OLimitedMap<K, V> extends LinkedHashMap<K, V> { protected final int limit; public OLimitedMap(final int initialCapacity, final float loadFactor, final int limit) { super(initialCapacity, loadFactor, true); this.limit = limit; } @Override protected boolean removeEldestEntry(final Map.Entry<K, V> eldest) { return limit > 0 ? size() - limit > 0 : false; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OLimitedMap.java
11
@SuppressWarnings({ "unchecked", "serial" }) public abstract class OMVRBTree<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, Cloneable, java.io.Serializable { private static final OAlwaysLessKey ALWAYS_LESS_KEY = new OAlwaysLessKey(); private static final OAlwaysGreaterKey ALWAYS_GREATER_KEY = new OAlwaysGreaterKey(); protected boolean pageItemFound = false; protected int pageItemComparator = 0; protected int pageIndex = -1; protected float pageLoadFactor = 0.7f; /** * The comparator used to maintain order in this tree map, or null if it uses the natural ordering of its keys. * * @serial */ protected final Comparator<? super K> comparator; protected transient OMVRBTreeEntry<K, V> root = null; /** * The number of structural modifications to the tree. */ transient int modCount = 0; protected transient boolean runtimeCheckEnabled = false; protected transient boolean debug = false; protected Object lastSearchKey; protected OMVRBTreeEntry<K, V> lastSearchNode; protected boolean lastSearchFound = false; protected int lastSearchIndex = -1; protected int keySize = 1; /** * Indicates search behavior in case of {@link OCompositeKey} keys that have less amount of internal keys are used, whether lowest * or highest partially matched key should be used. Such keys is allowed to use only in * * @link OMVRBTree#subMap(K, boolean, K, boolean)}, {@link OMVRBTree#tailMap(Object, boolean)} and * {@link OMVRBTree#headMap(Object, boolean)} . */ public static enum PartialSearchMode { /** * Any partially matched key will be used as search result. */ NONE, /** * The biggest partially matched key will be used as search result. */ HIGHEST_BOUNDARY, /** * The smallest partially matched key will be used as search result. */ LOWEST_BOUNDARY } /** * Constructs a new, empty tree map, using the natural ordering of its keys. All keys inserted into the map must implement the * {@link Comparable} interface. Furthermore, all such keys must be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not * throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts to put a key into * the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers), * the <tt>put(Object key, Object value)</tt> call will throw a <tt>ClassCastException</tt>. */ public OMVRBTree() { this(1); } public OMVRBTree(int keySize) { comparator = ODefaultComparator.INSTANCE; init(); this.keySize = keySize; } /** * Constructs a new, empty tree map, ordered according to the given comparator. All keys inserted into the map must be <i>mutually * comparable</i> by the given comparator: <tt>comparator.compare(k1, * k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts * to put a key into the map that violates this constraint, the <tt>put(Object * key, Object value)</tt> call will throw a <tt>ClassCastException</tt>. * * @param iComparator * the comparator that will be used to order this map. If <tt>null</tt>, the {@linkplain Comparable natural ordering} of * the keys will be used. */ public OMVRBTree(final Comparator<? super K> iComparator) { init(); this.comparator = iComparator; } /** * Constructs a new tree map containing the same mappings as the given map, ordered according to the <i>natural ordering</i> of * its keys. All keys inserted into the new map must implement the {@link Comparable} interface. Furthermore, all such keys must * be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> * and <tt>k2</tt> in the map. This method runs in n*log(n) time. * * @param m * the map whose mappings are to be placed in this map * @throws ClassCastException * if the keys in m are not {@link Comparable}, or are not mutually comparable * @throws NullPointerException * if the specified map is null */ public OMVRBTree(final Map<? extends K, ? extends V> m) { comparator = ODefaultComparator.INSTANCE; init(); putAll(m); } /** * Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method * runs in linear time. * * @param m * the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort this map * @throws NullPointerException * if the specified map is null */ public OMVRBTree(final SortedMap<K, ? extends V> m) { init(); comparator = m.comparator(); try { buildFromSorted(m.size(), m.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } /** * Create a new entry with the first key/value to handle. */ protected abstract OMVRBTreeEntry<K, V> createEntry(final K key, final V value); /** * Create a new node with the same parent of the node is splitting. */ protected abstract OMVRBTreeEntry<K, V> createEntry(final OMVRBTreeEntry<K, V> parent); protected abstract int getTreeSize(); public int getNodes() { int counter = -1; OMVRBTreeEntry<K, V> entry = getFirstEntry(); while (entry != null) { entry = successor(entry); counter++; } return counter; } protected abstract void setSize(int iSize); public abstract int getDefaultPageSize(); /** * Returns <tt>true</tt> if this map contains a mapping for the specified key. * * @param key * key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public boolean containsKey(final Object key) { return getEntry(key, PartialSearchMode.NONE) != null; } /** * Returns <tt>true</tt> if this map maps one or more keys to the specified value. More formally, returns <tt>true</tt> if and * only if this map contains at least one mapping to a value <tt>v</tt> such that * <tt>(value==null ? v==null : value.equals(v))</tt>. This operation will probably require time linear in the map size for most * implementations. * * @param value * value whose presence in this map is to be tested * @return <tt>true</tt> if a mapping to <tt>value</tt> exists; <tt>false</tt> otherwise * @since 1.2 */ @Override public boolean containsValue(final Object value) { for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = next(e)) if (valEquals(value, e.getValue())) return true; return false; } @Override public int size() { return getTreeSize(); } /** * Returns the value to which the specified key is mapped, or {@code null} if this map contains no mapping for the key. * * <p> * More formally, if this map contains a mapping from a key {@code k} to a value {@code v} such that {@code key} compares equal to * {@code k} according to the map's ordering, then this method returns {@code v}; otherwise it returns {@code null}. (There can be * at most one such mapping.) * * <p> * A return value of {@code null} does not <i>necessarily</i> indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public V get(final Object key) { if (getTreeSize() == 0) return null; OMVRBTreeEntry<K, V> entry = null; // TRY TO GET LATEST SEARCH final OMVRBTreeEntry<K, V> node = getLastSearchNodeForSameKey(key); if (node != null) { // SAME SEARCH OF PREVIOUS ONE: REUSE LAST RESULT? if (lastSearchFound) // REUSE LAST RESULT, OTHERWISE THE KEY NOT EXISTS return node.getValue(lastSearchIndex); } else // SEARCH THE ITEM entry = getEntry(key, PartialSearchMode.NONE); return entry == null ? null : entry.getValue(); } public Comparator<? super K> comparator() { return comparator; } /** * @throws NoSuchElementException * {@inheritDoc} */ public K firstKey() { return key(getFirstEntry()); } /** * @throws NoSuchElementException * {@inheritDoc} */ public K lastKey() { return key(getLastEntry()); } /** * Copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of * the keys currently in the specified map. * * @param map * mappings to be stored in this map * @throws ClassCastException * if the class of a key or value in the specified map prevents it from being stored in this map * @throws NullPointerException * if the specified map is null or the specified map contains a null key and this map does not permit null keys */ @Override public void putAll(final Map<? extends K, ? extends V> map) { int mapSize = map.size(); if (getTreeSize() == 0 && mapSize != 0 && map instanceof SortedMap) { Comparator<?> c = ((SortedMap<? extends K, ? extends V>) map).comparator(); if (c == comparator || (c != null && c.equals(comparator))) { ++modCount; try { buildFromSorted(mapSize, map.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return; } } super.putAll(map); } /** * Returns this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key. * * In case of {@link OCompositeKey} keys you can specify which key can be used: lowest, highest, any. * * @param key * Key to search. * @param partialSearchMode * Which key can be used in case of {@link OCompositeKey} key is passed in. * * @return this map's entry for the given key, or <tt>null</tt> if the map does not contain an entry for the key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ public final OMVRBTreeEntry<K, V> getEntry(final Object key, final PartialSearchMode partialSearchMode) { return getEntry(key, false, partialSearchMode); } final OMVRBTreeEntry<K, V> getEntry(final Object key, final boolean iGetContainer, final PartialSearchMode partialSearchMode) { if (key == null) return setLastSearchNode(null, null); pageItemFound = false; if (getTreeSize() == 0) { pageIndex = 0; return iGetContainer ? root : null; } final K k; if (keySize == 1) k = (K) key; else if (((OCompositeKey) key).getKeys().size() == keySize) k = (K) key; else if (partialSearchMode.equals(PartialSearchMode.NONE)) k = (K) key; else { final OCompositeKey fullKey = new OCompositeKey((Comparable<? super K>) key); int itemsToAdd = keySize - fullKey.getKeys().size(); final Comparable<?> keyItem; if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY)) keyItem = ALWAYS_GREATER_KEY; else keyItem = ALWAYS_LESS_KEY; for (int i = 0; i < itemsToAdd; i++) fullKey.addKey(keyItem); k = (K) fullKey; } OMVRBTreeEntry<K, V> p = getBestEntryPoint(k); checkTreeStructure(p); if (p == null) return setLastSearchNode(key, null); OMVRBTreeEntry<K, V> lastNode = p; OMVRBTreeEntry<K, V> prevNode = null; OMVRBTreeEntry<K, V> tmpNode; int beginKey = -1; try { while (p != null && p.getSize() > 0) { searchNodeCallback(); lastNode = p; beginKey = compare(k, p.getFirstKey()); if (beginKey == 0) { // EXACT MATCH, YOU'RE VERY LUCKY: RETURN THE FIRST KEY WITHOUT SEARCH INSIDE THE NODE pageIndex = 0; pageItemFound = true; pageItemComparator = 0; return setLastSearchNode(key, p); } pageItemComparator = compare(k, p.getLastKey()); if (beginKey < 0) { if (pageItemComparator < 0) { tmpNode = predecessor(p); if (tmpNode != null && tmpNode != prevNode) { // MINOR THAN THE CURRENT: GET THE LEFT NODE prevNode = p; p = tmpNode; continue; } } } else if (beginKey > 0) { if (pageItemComparator > 0) { tmpNode = successor(p); if (tmpNode != null && tmpNode != prevNode) { // MAJOR THAN THE CURRENT: GET THE RIGHT NODE prevNode = p; p = tmpNode; continue; } } } // SEARCH INSIDE THE NODE final V value = lastNode.search(k); // PROBABLY PARTIAL KEY IS FOUND USE SEARCH MODE TO FIND PREFERRED ONE if (key instanceof OCompositeKey) { final OCompositeKey compositeKey = (OCompositeKey) key; if (value != null && compositeKey.getKeys().size() == keySize) { return setLastSearchNode(key, lastNode); } if (partialSearchMode.equals(PartialSearchMode.NONE)) { if (value != null || iGetContainer) return lastNode; else return null; } if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY)) { // FOUNDED ENTRY EITHER GREATER THAN EXISTING ITEM OR ITEM DOES NOT EXIST return adjustHighestPartialSearchResult(iGetContainer, lastNode, compositeKey); } if (partialSearchMode.equals(PartialSearchMode.LOWEST_BOUNDARY)) { return adjustLowestPartialSearchResult(iGetContainer, lastNode, compositeKey); } } if (value != null) { setLastSearchNode(key, lastNode); } if (value != null || iGetContainer) // FOUND: RETURN CURRENT NODE OR AT LEAST THE CONTAINER NODE return lastNode; // NOT FOUND return null; } } finally { checkTreeStructure(p); } return setLastSearchNode(key, null); } private OMVRBTreeEntry<K, V> adjustHighestPartialSearchResult(final boolean iGetContainer, final OMVRBTreeEntry<K, V> lastNode, final OCompositeKey compositeKey) { final int oldPageIndex = pageIndex; final OMVRBTreeEntry<K, V> prevNd = previous(lastNode); if (prevNd == null) { pageIndex = oldPageIndex; pageItemFound = false; if (iGetContainer) return lastNode; return null; } pageItemComparator = compare(prevNd.getKey(), compositeKey); if (pageItemComparator == 0) { pageItemFound = true; return prevNd; } else if (pageItemComparator > 1) { pageItemFound = false; if (iGetContainer) return prevNd; return null; } else { pageIndex = oldPageIndex; pageItemFound = false; if (iGetContainer) return lastNode; return null; } } private OMVRBTreeEntry<K, V> adjustLowestPartialSearchResult(final boolean iGetContainer, OMVRBTreeEntry<K, V> lastNode, final OCompositeKey compositeKey) { // RARE CASE WHEN NODE ITSELF DOES CONTAIN KEY, BUT ALL KEYS LESS THAN GIVEN ONE final int oldPageIndex = pageIndex; final OMVRBTreeEntry<K, V> oldNode = lastNode; if (pageIndex >= lastNode.getSize()) { lastNode = next(lastNode); if (lastNode == null) { lastNode = oldNode; pageIndex = oldPageIndex; pageItemFound = false; if (iGetContainer) return lastNode; return null; } } pageItemComparator = compare(lastNode.getKey(), compositeKey); if (pageItemComparator == 0) { pageItemFound = true; return lastNode; } else { pageItemFound = false; if (iGetContainer) return lastNode; return null; } } /** * Basic implementation that returns the root node. */ protected OMVRBTreeEntry<K, V> getBestEntryPoint(final K key) { return root; } /** * Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the least key greater than * the specified key; if no such entry exists (i.e., the greatest key in the Tree is less than the specified key), returns * <tt>null</tt>. * * @param key * Key to search. * @param partialSearchMode * In case of {@link OCompositeKey} key is passed in this parameter will be used to find preferred one. */ public OMVRBTreeEntry<K, V> getCeilingEntry(final K key, final PartialSearchMode partialSearchMode) { OMVRBTreeEntry<K, V> p = getEntry(key, true, partialSearchMode); if (p == null) return null; if (pageItemFound) return p; // NOT MATCHED, POSITION IS ALREADY TO THE NEXT ONE else if (pageIndex < p.getSize()) { if (key instanceof OCompositeKey) return adjustSearchResult((OCompositeKey) key, partialSearchMode, p); else return p; } return null; } /** * Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the greatest key less than * the specified key; if no such entry exists, returns <tt>null</tt>. * * @param key * Key to search. * @param partialSearchMode * In case of {@link OCompositeKey} composite key is passed in this parameter will be used to find preferred one. */ public OMVRBTreeEntry<K, V> getFloorEntry(final K key, final PartialSearchMode partialSearchMode) { OMVRBTreeEntry<K, V> p = getEntry(key, true, partialSearchMode); if (p == null) return null; if (pageItemFound) return p; final OMVRBTreeEntry<K, V> adjacentEntry = previous(p); if (adjacentEntry == null) return null; if (key instanceof OCompositeKey) { return adjustSearchResult((OCompositeKey) key, partialSearchMode, adjacentEntry); } return adjacentEntry; } private OMVRBTreeEntry<K, V> adjustSearchResult(final OCompositeKey key, final PartialSearchMode partialSearchMode, final OMVRBTreeEntry<K, V> foundEntry) { if (partialSearchMode.equals(PartialSearchMode.NONE)) return foundEntry; final OCompositeKey keyToSearch = key; final OCompositeKey foundKey = (OCompositeKey) foundEntry.getKey(); if (keyToSearch.getKeys().size() < keySize) { final OCompositeKey borderKey = new OCompositeKey(); final OCompositeKey keyToCompare = new OCompositeKey(); final List<Object> keyItems = foundKey.getKeys(); for (int i = 0; i < keySize - 1; i++) { final Object keyItem = keyItems.get(i); borderKey.addKey(keyItem); if (i < keyToSearch.getKeys().size()) keyToCompare.addKey(keyItem); } if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY)) borderKey.addKey(ALWAYS_GREATER_KEY); else borderKey.addKey(ALWAYS_LESS_KEY); final OMVRBTreeEntry<K, V> adjustedNode = getEntry(borderKey, true, PartialSearchMode.NONE); if (partialSearchMode.equals(PartialSearchMode.HIGHEST_BOUNDARY)) return adjustHighestPartialSearchResult(false, adjustedNode, keyToCompare); else return adjustLowestPartialSearchResult(false, adjustedNode, keyToCompare); } return foundEntry; } /** * Gets the entry for the least key greater than the specified key; if no such entry exists, returns the entry for the least key * greater than the specified key; if no such entry exists returns <tt>null</tt>. */ public OMVRBTreeEntry<K, V> getHigherEntry(final K key) { final OMVRBTreeEntry<K, V> p = getEntry(key, true, PartialSearchMode.HIGHEST_BOUNDARY); if (p == null) return null; if (pageItemFound) // MATCH, RETURN THE NEXT ONE return next(p); else if (pageIndex < p.getSize()) // NOT MATCHED, POSITION IS ALREADY TO THE NEXT ONE return p; return null; } /** * Returns the entry for the greatest key less than the specified key; if no such entry exists (i.e., the least key in the Tree is * greater than the specified key), returns <tt>null</tt>. */ public OMVRBTreeEntry<K, V> getLowerEntry(final K key) { final OMVRBTreeEntry<K, V> p = getEntry(key, true, PartialSearchMode.LOWEST_BOUNDARY); if (p == null) return null; return previous(p); } /** * Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the * old value is replaced. * * @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 <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A * <tt>null</tt> return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.) * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public V put(final K key, final V value) { OMVRBTreeEntry<K, V> parentNode = null; try { if (root == null) { root = createEntry(key, value); root.setColor(BLACK); setSize(1); modCount++; return null; } // TRY TO GET LATEST SEARCH parentNode = getLastSearchNodeForSameKey(key); if (parentNode != null) { if (lastSearchFound) { // EXACT MATCH: UPDATE THE VALUE pageIndex = lastSearchIndex; modCount++; return parentNode.setValue(value); } } // SEARCH THE ITEM parentNode = getEntry(key, true, PartialSearchMode.NONE); if (pageItemFound) { modCount++; // EXACT MATCH: UPDATE THE VALUE return parentNode.setValue(value); } setLastSearchNode(null, null); if (parentNode == null) { parentNode = root; pageIndex = 0; } if (parentNode.getFreeSpace() > 0) { // INSERT INTO THE PAGE parentNode.insert(pageIndex, key, value); } else { // CREATE NEW NODE AND COPY HALF OF VALUES FROM THE ORIGIN TO THE NEW ONE IN ORDER TO GET VALUES BALANCED final OMVRBTreeEntry<K, V> newNode = createEntry(parentNode); if (pageIndex < parentNode.getPageSplitItems()) // INSERT IN THE ORIGINAL NODE parentNode.insert(pageIndex, key, value); else // INSERT IN THE NEW NODE newNode.insert(pageIndex - parentNode.getPageSplitItems(), key, value); OMVRBTreeEntry<K, V> node = parentNode.getRight(); OMVRBTreeEntry<K, V> prevNode = parentNode; int cmp = 0; final K fk = newNode.getFirstKey(); if (comparator != null) while (node != null) { cmp = comparator.compare(fk, node.getFirstKey()); if (cmp < 0) { prevNode = node; node = node.getLeft(); } else if (cmp > 0) { prevNode = node; node = node.getRight(); } else { throw new IllegalStateException("Duplicated keys were found in OMVRBTree."); } } else while (node != null) { cmp = compare(fk, node.getFirstKey()); if (cmp < 0) { prevNode = node; node = node.getLeft(); } else if (cmp > 0) { prevNode = node; node = node.getRight(); } else { throw new IllegalStateException("Duplicated keys were found in OMVRBTree."); } } if (prevNode == parentNode) parentNode.setRight(newNode); else if (cmp < 0) prevNode.setLeft(newNode); else if (cmp > 0) prevNode.setRight(newNode); else throw new IllegalStateException("Duplicated keys were found in OMVRBTree."); fixAfterInsertion(newNode); } modCount++; setSizeDelta(+1); } finally { checkTreeStructure(parentNode); } return null; } /** * Removes the mapping for this key from this OMVRBTree if present. * * @param key * key for which mapping should be removed * @return the previous value associated with <tt>key</tt>, or <tt>null</tt> if there was no mapping for <tt>key</tt>. (A * <tt>null</tt> return can also indicate that the map previously associated <tt>null</tt> with <tt>key</tt>.) * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys */ @Override public V remove(final Object key) { OMVRBTreeEntry<K, V> p = getEntry(key, PartialSearchMode.NONE); setLastSearchNode(null, null); if (p == null) return null; V oldValue = p.getValue(); deleteEntry(p); return oldValue; } /** * Removes all of the mappings from this map. The map will be empty after this call returns. */ @Override public void clear() { modCount++; setSize(0); setLastSearchNode(null, null); setRoot(null); } /** * Returns a shallow copy of this <tt>OMVRBTree</tt> instance. (The keys and values themselves are not cloned.) * * @return a shallow copy of this map */ @Override public Object clone() { OMVRBTree<K, V> clone = null; try { clone = (OMVRBTree<K, V>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } // Put clone into "virgin" state (except for comparator) clone.pageIndex = pageIndex; clone.pageItemFound = pageItemFound; clone.pageLoadFactor = pageLoadFactor; clone.root = null; clone.setSize(0); clone.modCount = 0; clone.entrySet = null; clone.navigableKeySet = null; clone.descendingMap = null; // Initialize clone with our mappings try { clone.buildFromSorted(getTreeSize(), entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return clone; } // ONavigableMap API methods /** * @since 1.6 */ public Map.Entry<K, V> firstEntry() { return exportEntry(getFirstEntry()); } /** * @since 1.6 */ public Map.Entry<K, V> lastEntry() { return exportEntry(getLastEntry()); } /** * @since 1.6 */ public Entry<K, V> pollFirstEntry() { OMVRBTreeEntry<K, V> p = getFirstEntry(); Map.Entry<K, V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } /** * @since 1.6 */ public Entry<K, V> pollLastEntry() { OMVRBTreeEntry<K, V> p = getLastEntry(); Map.Entry<K, V> result = exportEntry(p); if (p != null) deleteEntry(p); return result; } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> lowerEntry(final K key) { return exportEntry(getLowerEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K lowerKey(final K key) { return keyOrNull(getLowerEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> floorEntry(final K key) { return exportEntry(getFloorEntry(key, PartialSearchMode.NONE)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K floorKey(final K key) { return keyOrNull(getFloorEntry(key, PartialSearchMode.NONE)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> ceilingEntry(final K key) { return exportEntry(getCeilingEntry(key, PartialSearchMode.NONE)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K ceilingKey(final K key) { return keyOrNull(getCeilingEntry(key, PartialSearchMode.NONE)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public Map.Entry<K, V> higherEntry(final K key) { return exportEntry(getHigherEntry(key)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys * @since 1.6 */ public K higherKey(final K key) { return keyOrNull(getHigherEntry(key)); } // Views /** * Fields initialized to contain an instance of the entry set view the first time this view is requested. Views are stateless, so * there's no reason to create more than one. */ private transient EntrySet entrySet = null; private transient KeySet<K> navigableKeySet = null; private transient ONavigableMap<K, V> descendingMap = null; /** * Returns a {@link Set} view of the keys contained in this map. The set's iterator returns the keys in ascending order. The set * is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration * over the set is in progress (except through the iterator's own <tt>remove</tt> operation), the results of the iteration are * undefined. The set supports element removal, which removes the corresponding mapping from the map, via the * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations. It does * not support the <tt>add</tt> or <tt>addAll</tt> operations. */ @Override public Set<K> keySet() { return navigableKeySet(); } /** * @since 1.6 */ public ONavigableSet<K> navigableKeySet() { final KeySet<K> nks = navigableKeySet; return (nks != null) ? nks : (navigableKeySet = (KeySet<K>) new KeySet<Object>((ONavigableMap<Object, Object>) this)); } /** * @since 1.6 */ public ONavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } /** * Returns a {@link Collection} view of the values contained in this map. The collection's iterator returns the values in * ascending order of the corresponding keys. The collection is backed by the map, so changes to the map are reflected in the * collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the * iterator's own <tt>remove</tt> operation), the results of the iteration are undefined. The collection supports element removal, * which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>, * <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support the <tt>add</tt> or <tt>addAll</tt> * operations. */ @Override public Collection<V> values() { final Collection<V> vs = new Values(); return (vs != null) ? vs : null; } /** * Returns a {@link Set} view of the mappings contained in this map. The set's iterator returns the entries in ascending key * order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified * while an iteration over the set is in progress (except through the iterator's own <tt>remove</tt> operation, or through the * <tt>setValue</tt> operation on a map entry returned by the iterator) the results of the iteration are undefined. The set * supports element removal, which removes the corresponding mapping from the map, via the <tt>Iterator.remove</tt>, * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support the <tt>add</tt> * or <tt>addAll</tt> operations. */ @Override public Set<Map.Entry<K, V>> entrySet() { final EntrySet es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } /** * @since 1.6 */ public ONavigableMap<K, V> descendingMap() { final ONavigableMap<K, V> km = descendingMap; return (km != null) ? km : (descendingMap = new DescendingSubMap<K, V>(this, true, null, true, true, null, true)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>fromKey</tt> or <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit * null keys * @throws IllegalArgumentException * {@inheritDoc} * @since 1.6 */ public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { return new AscendingSubMap<K, V>(this, false, fromKey, fromInclusive, false, toKey, toInclusive); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys * @throws IllegalArgumentException * {@inheritDoc} * @since 1.6 */ public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { return new AscendingSubMap<K, V>(this, true, null, true, false, toKey, inclusive); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>fromKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys * @throws IllegalArgumentException * {@inheritDoc} * @since 1.6 */ public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { return new AscendingSubMap<K, V>(this, false, fromKey, inclusive, true, null, true); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>fromKey</tt> or <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit * null keys * @throws IllegalArgumentException * {@inheritDoc} */ public SortedMap<K, V> subMap(final K fromKey, final K toKey) { return subMap(fromKey, true, toKey, false); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>toKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys * @throws IllegalArgumentException * {@inheritDoc} */ public SortedMap<K, V> headMap(final K toKey) { return headMap(toKey, false); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if <tt>fromKey</tt> is null and this map uses natural ordering, or its comparator does not permit null keys * @throws IllegalArgumentException * {@inheritDoc} */ public SortedMap<K, V> tailMap(final K fromKey) { return tailMap(fromKey, true); } // View class support public class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { return new ValueIterator(getFirstEntry()); } public Iterator<V> inverseIterator() { return new ValueInverseIterator(getLastEntry()); } @Override public int size() { return OMVRBTree.this.size(); } @Override public boolean contains(final Object o) { return OMVRBTree.this.containsValue(o); } @Override public boolean remove(final Object o) { for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = next(e)) { if (valEquals(e.getValue(), o)) { deleteEntry(e); return true; } } return false; } @Override public void clear() { OMVRBTree.this.clear(); } } public class EntrySet extends AbstractSet<Map.Entry<K, V>> { @Override public Iterator<Map.Entry<K, V>> iterator() { return new EntryIterator(getFirstEntry()); } public Iterator<Map.Entry<K, V>> inverseIterator() { return new InverseEntryIterator(getLastEntry()); } @Override public boolean contains(final Object o) { if (!(o instanceof Map.Entry)) return false; OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final V value = entry.getValue(); final V p = get(entry.getKey()); return p != null && valEquals(p, value); } @Override public boolean remove(final Object o) { if (!(o instanceof Map.Entry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final V value = entry.getValue(); OMVRBTreeEntry<K, V> p = getEntry(entry.getKey(), PartialSearchMode.NONE); if (p != null && valEquals(p.getValue(), value)) { deleteEntry(p); return true; } return false; } @Override public int size() { return OMVRBTree.this.size(); } @Override public void clear() { OMVRBTree.this.clear(); } } /* * Unlike Values and EntrySet, the KeySet class is static, delegating to a ONavigableMap to allow use by SubMaps, which outweighs * the ugliness of needing type-tests for the following Iterator methods that are defined appropriately in main versus submap * classes. */ OLazyIterator<K> keyIterator() { return new KeyIterator(getFirstEntry()); } OLazyIterator<K> descendingKeyIterator() { return new DescendingKeyIterator(getLastEntry()); } @SuppressWarnings("rawtypes") static final class KeySet<E> extends AbstractSet<E> implements ONavigableSet<E> { private final ONavigableMap<E, Object> m; KeySet(ONavigableMap<E, Object> map) { m = map; } @Override public OLazyIterator<E> iterator() { if (m instanceof OMVRBTree) return ((OMVRBTree<E, Object>) m).keyIterator(); else return (((OMVRBTree.NavigableSubMap) m).keyIterator()); } public OLazyIterator<E> descendingIterator() { if (m instanceof OMVRBTree) return ((OMVRBTree<E, Object>) m).descendingKeyIterator(); else return (((OMVRBTree.NavigableSubMap) m).descendingKeyIterator()); } @Override public int size() { return m.size(); } @Override public boolean isEmpty() { return m.isEmpty(); } @Override public boolean contains(final Object o) { return m.containsKey(o); } @Override public void clear() { m.clear(); } public E lower(final E e) { return m.lowerKey(e); } public E floor(final E e) { return m.floorKey(e); } public E ceiling(final E e) { return m.ceilingKey(e); } public E higher(final E e) { return m.higherKey(e); } public E first() { return m.firstKey(); } public E last() { return m.lastKey(); } public Comparator<? super E> comparator() { return m.comparator(); } public E pollFirst() { final Map.Entry<E, Object> e = m.pollFirstEntry(); return e == null ? null : e.getKey(); } public E pollLast() { final Map.Entry<E, Object> e = m.pollLastEntry(); return e == null ? null : e.getKey(); } @Override public boolean remove(final Object o) { final int oldSize = size(); m.remove(o); return size() != oldSize; } public ONavigableSet<E> subSet(final E fromElement, final boolean fromInclusive, final E toElement, final boolean toInclusive) { return new OMVRBTreeSet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } public ONavigableSet<E> headSet(final E toElement, final boolean inclusive) { return new OMVRBTreeSet<E>(m.headMap(toElement, inclusive)); } public ONavigableSet<E> tailSet(final E fromElement, final boolean inclusive) { return new OMVRBTreeSet<E>(m.tailMap(fromElement, inclusive)); } public SortedSet<E> subSet(final E fromElement, final E toElement) { return subSet(fromElement, true, toElement, false); } public SortedSet<E> headSet(final E toElement) { return headSet(toElement, false); } public SortedSet<E> tailSet(final E fromElement) { return tailSet(fromElement, true); } public ONavigableSet<E> descendingSet() { return new OMVRBTreeSet<E>(m.descendingMap()); } } final class EntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> { EntryIterator(final OMVRBTreeEntry<K, V> first) { super(first); } public Map.Entry<K, V> next() { return nextEntry(); } } final class InverseEntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> { InverseEntryIterator(final OMVRBTreeEntry<K, V> last) { super(last); // we have to set ourselves after current index to make iterator work if (last != null) { pageIndex = last.getTree().getPageIndex() + 1; } } public Map.Entry<K, V> next() { return prevEntry(); } } final class ValueIterator extends AbstractEntryIterator<K, V, V> { ValueIterator(final OMVRBTreeEntry<K, V> first) { super(first); } @Override public V next() { return nextValue(); } } final class ValueInverseIterator extends AbstractEntryIterator<K, V, V> { ValueInverseIterator(final OMVRBTreeEntry<K, V> last) { super(last); // we have to set ourselves after current index to make iterator work if (last != null) { pageIndex = last.getTree().getPageIndex() + 1; } } @Override public boolean hasNext() { return hasPrevious(); } @Override public V next() { return prevValue(); } } final class KeyIterator extends AbstractEntryIterator<K, V, K> { KeyIterator(final OMVRBTreeEntry<K, V> first) { super(first); } @Override public K next() { return nextKey(); } } final class DescendingKeyIterator extends AbstractEntryIterator<K, V, K> { DescendingKeyIterator(final OMVRBTreeEntry<K, V> first) { super(first); } public K next() { return prevEntry().getKey(); } } // Little utilities /** * Compares two keys using the correct comparison method for this OMVRBTree. */ final int compare(final Object k1, final Object k2) { return comparator == null ? ((Comparable<? super K>) k1).compareTo((K) k2) : comparator.compare((K) k1, (K) k2); } /** * Test two values for equality. Differs from o1.equals(o2) only in that it copes with <tt>null</tt> o1 properly. */ final static boolean valEquals(final Object o1, final Object o2) { return (o1 == null ? o2 == null : o1.equals(o2)); } /** * Return SimpleImmutableEntry for entry, or null if null */ static <K, V> Map.Entry<K, V> exportEntry(final OMVRBTreeEntry<K, V> omvrbTreeEntryPosition) { return omvrbTreeEntryPosition == null ? null : new OSimpleImmutableEntry<K, V>(omvrbTreeEntryPosition); } /** * Return SimpleImmutableEntry for entry, or null if null */ static <K, V> Map.Entry<K, V> exportEntry(final OMVRBTreeEntryPosition<K, V> omvrbTreeEntryPosition) { return omvrbTreeEntryPosition == null ? null : new OSimpleImmutableEntry<K, V>(omvrbTreeEntryPosition.entry); } /** * Return key for entry, or null if null */ static <K, V> K keyOrNull(final OMVRBTreeEntry<K, V> e) { return e == null ? null : e.getKey(); } /** * Return key for entry, or null if null */ static <K, V> K keyOrNull(OMVRBTreeEntryPosition<K, V> e) { return e == null ? null : e.getKey(); } /** * Returns the key corresponding to the specified Entry. * * @throws NoSuchElementException * if the Entry is null */ static <K> K key(OMVRBTreeEntry<K, ?> e) { if (e == null) throw new NoSuchElementException(); return e.getKey(); } // SubMaps /** * @serial include */ static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, java.io.Serializable { /** * The backing map. */ final OMVRBTree<K, V> m; /** * Endpoints are represented as triples (fromStart, lo, loInclusive) and (toEnd, hi, hiInclusive). If fromStart is true, then * the low (absolute) bound is the start of the backing map, and the other values are ignored. Otherwise, if loInclusive is * true, lo is the inclusive bound, else lo is the exclusive bound. Similarly for the upper bound. */ final K lo, hi; final boolean fromStart, toEnd; final boolean loInclusive, hiInclusive; NavigableSubMap(final OMVRBTree<K, V> m, final boolean fromStart, K lo, final boolean loInclusive, final boolean toEnd, K hi, final boolean hiInclusive) { if (!fromStart && !toEnd) { if (m.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); } else { if (!fromStart) // type check m.compare(lo, lo); if (!toEnd) m.compare(hi, hi); } this.m = m; this.fromStart = fromStart; this.lo = lo; this.loInclusive = loInclusive; this.toEnd = toEnd; this.hi = hi; this.hiInclusive = hiInclusive; } // internal utilities final boolean tooLow(final Object key) { if (!fromStart) { int c = m.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } final boolean tooHigh(final Object key) { if (!toEnd) { int c = m.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } final boolean inRange(final Object key) { return !tooLow(key) && !tooHigh(key); } final boolean inClosedRange(final Object key) { return (fromStart || m.compare(key, lo) >= 0) && (toEnd || m.compare(hi, key) >= 0); } final boolean inRange(final Object key, final boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } /* * Absolute versions of relation operations. Subclasses map to these using like-named "sub" versions that invert senses for * descending maps */ final OMVRBTreeEntryPosition<K, V> absLowest() { OMVRBTreeEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo, PartialSearchMode.LOWEST_BOUNDARY) : m.getHigherEntry(lo))); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absHighest() { OMVRBTreeEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi, PartialSearchMode.HIGHEST_BOUNDARY) : m.getLowerEntry(hi))); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absCeiling(K key) { if (tooLow(key)) return absLowest(); OMVRBTreeEntry<K, V> e = m.getCeilingEntry(key, PartialSearchMode.NONE); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absHigher(K key) { if (tooLow(key)) return absLowest(); OMVRBTreeEntry<K, V> e = m.getHigherEntry(key); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absFloor(K key) { if (tooHigh(key)) return absHighest(); OMVRBTreeEntry<K, V> e = m.getFloorEntry(key, PartialSearchMode.NONE); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absLower(K key) { if (tooHigh(key)) return absHighest(); OMVRBTreeEntry<K, V> e = m.getLowerEntry(key); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } /** Returns the absolute high fence for ascending traversal */ final OMVRBTreeEntryPosition<K, V> absHighFence() { return (toEnd ? null : new OMVRBTreeEntryPosition<K, V>(hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi, PartialSearchMode.LOWEST_BOUNDARY))); } /** Return the absolute low fence for descending traversal */ final OMVRBTreeEntryPosition<K, V> absLowFence() { return (fromStart ? null : new OMVRBTreeEntryPosition<K, V>(loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo, PartialSearchMode.HIGHEST_BOUNDARY))); } // Abstract methods defined in ascending vs descending classes // These relay to the appropriate absolute versions abstract OMVRBTreeEntry<K, V> subLowest(); abstract OMVRBTreeEntry<K, V> subHighest(); abstract OMVRBTreeEntry<K, V> subCeiling(K key); abstract OMVRBTreeEntry<K, V> subHigher(K key); abstract OMVRBTreeEntry<K, V> subFloor(K key); abstract OMVRBTreeEntry<K, V> subLower(K key); /** Returns ascending iterator from the perspective of this submap */ abstract OLazyIterator<K> keyIterator(); /** Returns descending iterator from the perspective of this submap */ abstract OLazyIterator<K> descendingKeyIterator(); // public methods @Override public boolean isEmpty() { return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty(); } @Override public int size() { return (fromStart && toEnd) ? m.size() : entrySet().size(); } @Override public final boolean containsKey(Object key) { return inRange(key) && m.containsKey(key); } @Override public final V put(K key, V value) { if (!inRange(key)) throw new IllegalArgumentException("key out of range"); return m.put(key, value); } @Override public final V get(Object key) { return !inRange(key) ? null : m.get(key); } @Override public final V remove(Object key) { return !inRange(key) ? null : m.remove(key); } public final Map.Entry<K, V> ceilingEntry(K key) { return exportEntry(subCeiling(key)); } public final K ceilingKey(K key) { return keyOrNull(subCeiling(key)); } public final Map.Entry<K, V> higherEntry(K key) { return exportEntry(subHigher(key)); } public final K higherKey(K key) { return keyOrNull(subHigher(key)); } public final Map.Entry<K, V> floorEntry(K key) { return exportEntry(subFloor(key)); } public final K floorKey(K key) { return keyOrNull(subFloor(key)); } public final Map.Entry<K, V> lowerEntry(K key) { return exportEntry(subLower(key)); } public final K lowerKey(K key) { return keyOrNull(subLower(key)); } public final K firstKey() { return key(subLowest()); } public final K lastKey() { return key(subHighest()); } public final Map.Entry<K, V> firstEntry() { return exportEntry(subLowest()); } public final Map.Entry<K, V> lastEntry() { return exportEntry(subHighest()); } public final Map.Entry<K, V> pollFirstEntry() { OMVRBTreeEntry<K, V> e = subLowest(); Map.Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } public final Map.Entry<K, V> pollLastEntry() { OMVRBTreeEntry<K, V> e = subHighest(); Map.Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } // Views transient ONavigableMap<K, V> descendingMapView = null; transient EntrySetView entrySetView = null; transient KeySet<K> navigableKeySetView = null; @SuppressWarnings("rawtypes") public final ONavigableSet<K> navigableKeySet() { KeySet<K> nksv = navigableKeySetView; return (nksv != null) ? nksv : (navigableKeySetView = new OMVRBTree.KeySet(this)); } @Override public final Set<K> keySet() { return navigableKeySet(); } public ONavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } public final SortedMap<K, V> subMap(final K fromKey, final K toKey) { return subMap(fromKey, true, toKey, false); } public final SortedMap<K, V> headMap(final K toKey) { return headMap(toKey, false); } public final SortedMap<K, V> tailMap(final K fromKey) { return tailMap(fromKey, true); } // View classes abstract class EntrySetView extends AbstractSet<Map.Entry<K, V>> { private transient int size = -1, sizeModCount; @Override public int size() { if (fromStart && toEnd) return m.size(); if (size == -1 || sizeModCount != m.modCount) { sizeModCount = m.modCount; size = 0; Iterator<?> i = iterator(); while (i.hasNext()) { size++; i.next(); } } return size; } @Override public boolean isEmpty() { OMVRBTreeEntryPosition<K, V> n = absLowest(); return n == null || tooHigh(n.getKey()); } @Override public boolean contains(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; V nodeValue = m.get(key); return nodeValue != null && valEquals(nodeValue, entry.getValue()); } @Override public boolean remove(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; final OMVRBTreeEntry<K, V> node = m.getEntry(key, PartialSearchMode.NONE); if (node != null && valEquals(node.getValue(), entry.getValue())) { m.deleteEntry(node); return true; } return false; } } /** * Iterators for SubMaps */ abstract class SubMapIterator<T> implements OLazyIterator<T> { OMVRBTreeEntryPosition<K, V> lastReturned; OMVRBTreeEntryPosition<K, V> next; final K fenceKey; int expectedModCount; SubMapIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { expectedModCount = m.modCount; lastReturned = null; next = first; fenceKey = fence == null ? null : fence.getKey(); } public final boolean hasNext() { if (next != null) { final K k = next.getKey(); return k != fenceKey && !k.equals(fenceKey); } return false; } final OMVRBTreeEntryPosition<K, V> nextEntry() { final OMVRBTreeEntryPosition<K, V> e; if (next != null) e = new OMVRBTreeEntryPosition<K, V>(next); else e = null; if (e == null || e.entry == null) throw new NoSuchElementException(); final K k = e.getKey(); if (k == fenceKey || k.equals(fenceKey)) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next.assign(OMVRBTree.next(e)); lastReturned = e; return e; } final OMVRBTreeEntryPosition<K, V> prevEntry() { final OMVRBTreeEntryPosition<K, V> e; if (next != null) e = new OMVRBTreeEntryPosition<K, V>(next); else e = null; if (e == null || e.entry == null) throw new NoSuchElementException(); final K k = e.getKey(); if (k == fenceKey || k.equals(fenceKey)) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next.assign(OMVRBTree.previous(e)); lastReturned = e; return e; } final public T update(final T iValue) { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); return (T) lastReturned.entry.setValue((V) iValue); } final void removeAscending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.entry.getLeft() != null && lastReturned.entry.getRight() != null) next = lastReturned; m.deleteEntry(lastReturned.entry); lastReturned = null; expectedModCount = m.modCount; } final void removeDescending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); m.deleteEntry(lastReturned.entry); lastReturned = null; expectedModCount = m.modCount; } } final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { SubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { super(first, fence); } public Map.Entry<K, V> next() { final Map.Entry<K, V> e = OMVRBTree.exportEntry(next); nextEntry(); return e; } public void remove() { removeAscending(); } } final class SubMapKeyIterator extends SubMapIterator<K> { SubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { super(first, fence); } public K next() { return nextEntry().getKey(); } public void remove() { removeAscending(); } } final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { DescendingSubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public Map.Entry<K, V> next() { final Map.Entry<K, V> e = OMVRBTree.exportEntry(next); prevEntry(); return e; } public void remove() { removeDescending(); } } final class DescendingSubMapKeyIterator extends SubMapIterator<K> { DescendingSubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public K next() { return prevEntry().getKey(); } public void remove() { removeDescending(); } } } /** * @serial include */ static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866124060L; AscendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd, K hi, final boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return m.comparator(); } public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<K, V>(m, false, fromKey, fromInclusive, false, toKey, toInclusive); } public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, toKey, inclusive); } public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new AscendingSubMap<K, V>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive); } public ONavigableMap<K, V> descendingMap() { ONavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } @Override OLazyIterator<K> keyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } @Override OLazyIterator<K> descendingKeyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } final class AscendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new SubMapEntryIterator(absLowest(), absHighFence()); } } @Override public Set<Map.Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new AscendingEntrySetView(); } @Override OMVRBTreeEntry<K, V> subLowest() { return absLowest().entry; } @Override OMVRBTreeEntry<K, V> subHighest() { return absHighest().entry; } @Override OMVRBTreeEntry<K, V> subCeiling(final K key) { return absCeiling(key).entry; } @Override OMVRBTreeEntry<K, V> subHigher(final K key) { return absHigher(key).entry; } @Override OMVRBTreeEntry<K, V> subFloor(final K key) { return absFloor(key).entry; } @Override OMVRBTreeEntry<K, V> subLower(final K key) { return absLower(key).entry; } } /** * @serial include */ static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866120460L; private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator); DescendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd, final K hi, final boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return reverseComparator; } public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<K, V>(m, false, toKey, toInclusive, false, fromKey, fromInclusive); } public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<K, V>(m, false, toKey, inclusive, toEnd, hi, hiInclusive); } public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, fromKey, inclusive); } public ONavigableMap<K, V> descendingMap() { ONavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } @Override OLazyIterator<K> keyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } @Override OLazyIterator<K> descendingKeyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } final class DescendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new DescendingSubMapEntryIterator(absHighest(), absLowFence()); } } @Override public Set<Map.Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new DescendingEntrySetView(); } @Override OMVRBTreeEntry<K, V> subLowest() { return absHighest().entry; } @Override OMVRBTreeEntry<K, V> subHighest() { return absLowest().entry; } @Override OMVRBTreeEntry<K, V> subCeiling(final K key) { return absFloor(key).entry; } @Override OMVRBTreeEntry<K, V> subHigher(final K key) { return absLower(key).entry; } @Override OMVRBTreeEntry<K, V> subFloor(final K key) { return absCeiling(key).entry; } @Override OMVRBTreeEntry<K, V> subLower(final K key) { return absHigher(key).entry; } } // Red-black mechanics public static final boolean RED = false; public static final boolean BLACK = true; /** * Node in the Tree. Doubles as a means to pass key-value pairs back to user (see Map.Entry). */ /** * Returns the first Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is * empty. */ public OMVRBTreeEntry<K, V> getFirstEntry() { OMVRBTreeEntry<K, V> p = root; if (p != null) { if (p.getSize() > 0) pageIndex = 0; while (p.getLeft() != null) p = p.getLeft(); } return p; } /** * Returns the last Entry in the OMVRBTree (according to the OMVRBTree's key-sort function). Returns null if the OMVRBTree is * empty. */ protected OMVRBTreeEntry<K, V> getLastEntry() { OMVRBTreeEntry<K, V> p = root; if (p != null) while (p.getRight() != null) p = p.getRight(); if (p != null) pageIndex = p.getSize() - 1; return p; } public static <K, V> OMVRBTreeEntry<K, V> successor(final OMVRBTreeEntryPosition<K, V> t) { t.entry.getTree().setPageIndex(t.position); return successor(t.entry); } /** * Returns the successor of the specified Entry, or null if no such. */ public static <K, V> OMVRBTreeEntry<K, V> successor(final OMVRBTreeEntry<K, V> t) { if (t == null) return null; OMVRBTreeEntry<K, V> p = null; if (t.getRight() != null) { p = t.getRight(); while (p.getLeft() != null) p = p.getLeft(); } else { p = t.getParent(); OMVRBTreeEntry<K, V> ch = t; while (p != null && ch == p.getRight()) { ch = p; p = p.getParent(); } } return p; } public static <K, V> OMVRBTreeEntry<K, V> next(final OMVRBTreeEntryPosition<K, V> t) { t.entry.getTree().setPageIndex(t.position); return next(t.entry); } /** * Returns the next item of the tree. */ public static <K, V> OMVRBTreeEntry<K, V> next(final OMVRBTreeEntry<K, V> t) { if (t == null) return null; final OMVRBTreeEntry<K, V> succ; if (t.tree.pageIndex < t.getSize() - 1) { // ITERATE INSIDE THE NODE succ = t; t.tree.pageIndex++; } else { // GET THE NEXT NODE succ = OMVRBTree.successor(t); t.tree.pageIndex = 0; } return succ; } public static <K, V> OMVRBTreeEntry<K, V> predecessor(final OMVRBTreeEntryPosition<K, V> t) { t.entry.getTree().setPageIndex(t.position); return predecessor(t.entry); } /** * Returns the predecessor of the specified Entry, or null if no such. */ public static <K, V> OMVRBTreeEntry<K, V> predecessor(final OMVRBTreeEntry<K, V> t) { if (t == null) return null; else if (t.getLeft() != null) { OMVRBTreeEntry<K, V> p = t.getLeft(); while (p.getRight() != null) p = p.getRight(); return p; } else { OMVRBTreeEntry<K, V> p = t.getParent(); Entry<K, V> ch = t; while (p != null && ch == p.getLeft()) { ch = p; p = p.getParent(); } return p; } } public static <K, V> OMVRBTreeEntry<K, V> previous(final OMVRBTreeEntryPosition<K, V> t) { t.entry.getTree().setPageIndex(t.position); return previous(t.entry); } /** * Returns the previous item of the tree. */ public static <K, V> OMVRBTreeEntry<K, V> previous(final OMVRBTreeEntry<K, V> t) { if (t == null) return null; final int index = t.getTree().getPageIndex(); final OMVRBTreeEntry<K, V> prev; if (index <= 0) { prev = predecessor(t); if (prev != null) t.tree.pageIndex = prev.getSize() - 1; else t.tree.pageIndex = 0; } else { prev = t; t.tree.pageIndex = index - 1; } return prev; } /** * Balancing operations. * * Implementations of rebalancings during insertion and deletion are slightly different than the CLR version. Rather than using * dummy nilnodes, we use a set of accessors that deal properly with null. They are used to avoid messiness surrounding nullness * checks in the main algorithms. */ private static <K, V> boolean colorOf(final OMVRBTreeEntry<K, V> p) { return (p == null ? BLACK : p.getColor()); } private static <K, V> OMVRBTreeEntry<K, V> parentOf(final OMVRBTreeEntry<K, V> p) { return (p == null ? null : p.getParent()); } private static <K, V> void setColor(final OMVRBTreeEntry<K, V> p, final boolean c) { if (p != null) p.setColor(c); } private static <K, V> OMVRBTreeEntry<K, V> leftOf(final OMVRBTreeEntry<K, V> p) { return (p == null) ? null : p.getLeft(); } private static <K, V> OMVRBTreeEntry<K, V> rightOf(final OMVRBTreeEntry<K, V> p) { return (p == null) ? null : p.getRight(); } /** From CLR */ protected void rotateLeft(final OMVRBTreeEntry<K, V> p) { if (p != null) { OMVRBTreeEntry<K, V> r = p.getRight(); p.setRight(r.getLeft()); if (r.getLeft() != null) r.getLeft().setParent(p); r.setParent(p.getParent()); if (p.getParent() == null) setRoot(r); else if (p.getParent().getLeft() == p) p.getParent().setLeft(r); else p.getParent().setRight(r); p.setParent(r); r.setLeft(p); } } protected void setRoot(final OMVRBTreeEntry<K, V> iRoot) { root = iRoot; } /** From CLR */ protected void rotateRight(final OMVRBTreeEntry<K, V> p) { if (p != null) { OMVRBTreeEntry<K, V> l = p.getLeft(); p.setLeft(l.getRight()); if (l.getRight() != null) l.getRight().setParent(p); l.setParent(p.getParent()); if (p.getParent() == null) setRoot(l); else if (p.getParent().getRight() == p) p.getParent().setRight(l); else p.getParent().setLeft(l); l.setRight(p); p.setParent(l); } } private OMVRBTreeEntry<K, V> grandparent(final OMVRBTreeEntry<K, V> n) { return parentOf(parentOf(n)); } private OMVRBTreeEntry<K, V> uncle(final OMVRBTreeEntry<K, V> n) { if (parentOf(n) == leftOf(grandparent(n))) return rightOf(grandparent(n)); else return leftOf(grandparent(n)); } private void fixAfterInsertion(final OMVRBTreeEntry<K, V> n) { if (parentOf(n) == null) setColor(n, BLACK); else insert_case2(n); } private void insert_case2(final OMVRBTreeEntry<K, V> n) { if (colorOf(parentOf(n)) == BLACK) return; /* Tree is still valid */ else insert_case3(n); } private void insert_case3(final OMVRBTreeEntry<K, V> n) { if (uncle(n) != null && colorOf(uncle(n)) == RED) { setColor(parentOf(n), BLACK); setColor(uncle(n), BLACK); setColor(grandparent(n), RED); fixAfterInsertion(grandparent(n)); } else insert_case4(n); } private void insert_case4(OMVRBTreeEntry<K, V> n) { if (n == rightOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) { rotateLeft(parentOf(n)); n = leftOf(n); } else if (n == leftOf(parentOf(n)) && parentOf(n) == rightOf(grandparent(n))) { rotateRight(parentOf(n)); n = rightOf(n); } insert_case5(n); } private void insert_case5(final OMVRBTreeEntry<K, V> n) { setColor(parentOf(n), BLACK); setColor(grandparent(n), RED); if (n == leftOf(parentOf(n)) && parentOf(n) == leftOf(grandparent(n))) { rotateRight(grandparent(n)); } else { rotateLeft(grandparent(n)); } } /** * Delete node p, and then re-balance the tree. * * @param p * node to delete * @return */ OMVRBTreeEntry<K, V> deleteEntry(OMVRBTreeEntry<K, V> p) { setSizeDelta(-1); modCount++; if (pageIndex > -1) { // DELETE INSIDE THE NODE p.remove(); if (p.getSize() > 0) return p; } final OMVRBTreeEntry<K, V> next = successor(p); // DELETE THE ENTIRE NODE, RE-BUILDING THE STRUCTURE removeNode(p); // RETURN NEXT NODE return next; } /** * Remove a node from the tree. * * @param p * Node to remove * * @return Node that was removed. Passed and removed nodes may be different in case node to remove contains two children. In this * case node successor will be found and removed but it's content will be copied to the node that was passed in method. */ protected OMVRBTreeEntry<K, V> removeNode(OMVRBTreeEntry<K, V> p) { modCount++; // If strictly internal, copy successor's element to p and then make p // point to successor. if (p.getLeft() != null && p.getRight() != null) { OMVRBTreeEntry<K, V> s = next(p); p.copyFrom(s); p = s; } // p has 2 children // Start fixup at replacement node, if it exists. final OMVRBTreeEntry<K, V> replacement = (p.getLeft() != null ? p.getLeft() : p.getRight()); if (replacement != null) { // Link replacement to parent replacement.setParent(p.getParent()); if (p.getParent() == null) setRoot(replacement); else if (p == p.getParent().getLeft()) p.getParent().setLeft(replacement); else p.getParent().setRight(replacement); // Null out links so they are OK to use by fixAfterDeletion. p.setLeft(null); p.setRight(null); p.setParent(null); // Fix replacement if (p.getColor() == BLACK) fixAfterDeletion(replacement); } else if (p.getParent() == null && size() == 0) { // return if we are the only node. Check the size to be sure the map is empty clear(); } else { // No children. Use self as phantom replacement and unlink. if (p.getColor() == BLACK) fixAfterDeletion(p); if (p.getParent() != null) { if (p == p.getParent().getLeft()) p.getParent().setLeft(null); else if (p == p.getParent().getRight()) p.getParent().setRight(null); p.setParent(null); } } return p; } /** From CLR */ private void fixAfterDeletion(OMVRBTreeEntry<K, V> x) { while (x != root && colorOf(x) == BLACK) { if (x == leftOf(parentOf(x))) { OMVRBTreeEntry<K, V> sib = rightOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateLeft(parentOf(x)); sib = rightOf(parentOf(x)); } if (colorOf(leftOf(sib)) == BLACK && colorOf(rightOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(rightOf(sib)) == BLACK) { setColor(leftOf(sib), BLACK); setColor(sib, RED); rotateRight(sib); sib = rightOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(rightOf(sib), BLACK); rotateLeft(parentOf(x)); x = root; } } else { // symmetric OMVRBTreeEntry<K, V> sib = leftOf(parentOf(x)); if (colorOf(sib) == RED) { setColor(sib, BLACK); setColor(parentOf(x), RED); rotateRight(parentOf(x)); sib = leftOf(parentOf(x)); } if (x != null && colorOf(rightOf(sib)) == BLACK && colorOf(leftOf(sib)) == BLACK) { setColor(sib, RED); x = parentOf(x); } else { if (colorOf(leftOf(sib)) == BLACK) { setColor(rightOf(sib), BLACK); setColor(sib, RED); rotateLeft(sib); sib = leftOf(parentOf(x)); } setColor(sib, colorOf(parentOf(x))); setColor(parentOf(x), BLACK); setColor(leftOf(sib), BLACK); rotateRight(parentOf(x)); x = root; } } } setColor(x, BLACK); } /** * Save the state of the <tt>OMVRBTree</tt> instance to a stream (i.e., serialize it). * * @serialData The <i>size</i> of the OMVRBTree (the number of key-value mappings) is emitted (int), followed by the key (Object) * and value (Object) for each key-value mapping represented by the OMVRBTree. The key-value mappings are emitted in * key-order (as determined by the OMVRBTree's Comparator, or by the keys' natural ordering if the OMVRBTree has no * Comparator). */ private void writeObject(final ObjectOutputStream s) throws java.io.IOException { // Write out the Comparator and any hidden stuff s.defaultWriteObject(); // Write out size (number of Mappings) s.writeInt(size()); // Write out keys and values (alternating) for (Iterator<Map.Entry<K, V>> i = entrySet().iterator(); i.hasNext();) { Entry<K, V> e = i.next(); s.writeObject(e.getKey()); s.writeObject(e.getValue()); } } /** * Reconstitute the <tt>OMVRBTree</tt> instance from a stream (i.e., deserialize it). */ private void readObject(final java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the Comparator and any hidden stuff s.defaultReadObject(); // Read in size setSize(s.readInt()); buildFromSorted(size(), null, s, null); } /** Intended to be called only from OTreeSet.readObject */ void readOTreeSet(int iSize, ObjectInputStream s, V defaultVal) throws java.io.IOException, ClassNotFoundException { buildFromSorted(iSize, null, s, defaultVal); } /** Intended to be called only from OTreeSet.addAll */ void addAllForOTreeSet(SortedSet<? extends K> set, V defaultVal) { try { buildFromSorted(set.size(), set.iterator(), null, defaultVal); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } /** * Linear time tree building algorithm from sorted data. Can accept keys and/or values from iterator or stream. This leads to too * many parameters, but seems better than alternatives. The four formats that this method accepts are: * * 1) An iterator of Map.Entries. (it != null, defaultVal == null). 2) An iterator of keys. (it != null, defaultVal != null). 3) A * stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it == * null, defaultVal != null). * * It is assumed that the comparator of the OMVRBTree is already set prior to calling this method. * * @param size * the number of keys (or key-value pairs) to be read from the iterator or stream * @param it * If non-null, new entries are created from entries or keys read from this iterator. * @param str * If non-null, new entries are created from keys and possibly values read from this stream in serialized form. Exactly * one of it and str should be non-null. * @param defaultVal * if non-null, this default value is used for each value in the map. If null, each value is read from iterator or * stream, as described above. * @throws IOException * propagated from stream reads. This cannot occur if str is null. * @throws ClassNotFoundException * propagated from readObject. This cannot occur if str is null. */ private void buildFromSorted(final int size, final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException, ClassNotFoundException { setSize(size); root = buildFromSorted(0, 0, size - 1, computeRedLevel(size), it, str, defaultVal); } /** * Recursive "helper method" that does the real work of the previous method. Identically named parameters have identical * definitions. Additional parameters are documented below. It is assumed that the comparator and size fields of the OMVRBTree are * already set prior to calling this method. (It ignores both fields.) * * @param level * the current level of tree. Initial call should be 0. * @param lo * the first element index of this subtree. Initial should be 0. * @param hi * the last element index of this subtree. Initial should be size-1. * @param redLevel * the level at which nodes should be red. Must be equal to computeRedLevel for tree of this size. */ private final OMVRBTreeEntry<K, V> buildFromSorted(final int level, final int lo, final int hi, final int redLevel, final Iterator<?> it, final java.io.ObjectInputStream str, final V defaultVal) throws java.io.IOException, ClassNotFoundException { /* * Strategy: The root is the middlemost element. To get to it, we have to first recursively construct the entire left subtree, * so as to grab all of its elements. We can then proceed with right subtree. * * The lo and hi arguments are the minimum and maximum indices to pull out of the iterator or stream for current subtree. They * are not actually indexed, we just proceed sequentially, ensuring that items are extracted in corresponding order. */ if (hi < lo) return null; final int mid = (lo + hi) / 2; OMVRBTreeEntry<K, V> left = null; if (lo < mid) left = buildFromSorted(level + 1, lo, mid - 1, redLevel, it, str, defaultVal); // extract key and/or value from iterator or stream K key; V value; if (it != null) { if (defaultVal == null) { OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) it.next(); key = entry.getKey(); value = entry.getValue(); } else { key = (K) it.next(); value = defaultVal; } } else { // use stream key = (K) str.readObject(); value = (defaultVal != null ? defaultVal : (V) str.readObject()); } final OMVRBTreeEntry<K, V> middle = createEntry(key, value); // color nodes in non-full bottom most level red if (level == redLevel) middle.setColor(RED); if (left != null) { middle.setLeft(left); left.setParent(middle); } if (mid < hi) { OMVRBTreeEntry<K, V> right = buildFromSorted(level + 1, mid + 1, hi, redLevel, it, str, defaultVal); middle.setRight(right); right.setParent(middle); } return middle; } /** * Find the level down to which to assign all nodes BLACK. This is the last `full' level of the complete binary tree produced by * buildTree. The remaining nodes are colored RED. (This makes a `nice' set of color assignments wrt future insertions.) This * level number is computed by finding the number of splits needed to reach the zeroeth node. (The answer is ~lg(N), but in any * case must be computed by same quick O(lg(N)) loop.) */ private static int computeRedLevel(final int sz) { int level = 0; for (int m = sz - 1; m >= 0; m = m / 2 - 1) level++; return level; } public int getPageIndex() { return pageIndex; } public void setPageIndex(final int iPageIndex) { pageIndex = iPageIndex; } private void init() { } public OMVRBTreeEntry<K, V> getRoot() { return root; } protected void printInMemoryStructure(final OMVRBTreeEntry<K, V> iRootNode) { printInMemoryNode("root", iRootNode, 0); } private void printInMemoryNode(final String iLabel, OMVRBTreeEntry<K, V> iNode, int iLevel) { if (iNode == null) return; for (int i = 0; i < iLevel; ++i) System.out.print(' '); System.out.println(iLabel + ": " + iNode.toString() + " (" + (iNode.getColor() ? "B" : "R") + ")"); ++iLevel; printInMemoryNode(iLevel + ".left", iNode.getLeftInMemory(), iLevel); printInMemoryNode(iLevel + ".right", iNode.getRightInMemory(), iLevel); } public void checkTreeStructure(final OMVRBTreeEntry<K, V> iRootNode) { if (!runtimeCheckEnabled || iRootNode == null) return; int currPageIndex = pageIndex; OMVRBTreeEntry<K, V> prevNode = null; int i = 0; for (OMVRBTreeEntry<K, V> e = iRootNode.getFirstInMemory(); e != null; e = e.getNextInMemory()) { if (e.getSize() == 0) OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has 0 items\n", e); if (prevNode != null) { if (prevNode.getTree() == null) OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Freed record %d found in memory\n", i); if (compare(e.getFirstKey(), e.getLastKey()) > 0) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] begin key is > than last key\n", e.getFirstKey(), e.getLastKey()); printInMemoryStructure(iRootNode); } if (compare(e.getFirstKey(), prevNode.getLastKey()) < 0) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s starts with a key minor than the last key of the previous node %s\n", e, prevNode); printInMemoryStructure(e.getParentInMemory() != null ? e.getParentInMemory() : e); } } if (e.getLeftInMemory() != null && e.getLeftInMemory() == e) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has left that points to itself!\n", e); printInMemoryStructure(iRootNode); } if (e.getRightInMemory() != null && e.getRightInMemory() == e) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has right that points to itself!\n", e); printInMemoryStructure(iRootNode); } if (e.getLeftInMemory() != null && e.getLeftInMemory() == e.getRightInMemory()) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s has left and right equals!\n", e); printInMemoryStructure(iRootNode); } if (e.getParentInMemory() != null && e.getParentInMemory().getRightInMemory() != e && e.getParentInMemory().getLeftInMemory() != e) { OLogManager.instance().error(this, "[OMVRBTree.checkTreeStructure] Node %s is the children of node %s but the cross-reference is missed!\n", e, e.getParentInMemory()); printInMemoryStructure(iRootNode); } prevNode = e; ++i; } pageIndex = currPageIndex; } public boolean isRuntimeCheckEnabled() { return runtimeCheckEnabled; } public void setChecks(boolean checks) { this.runtimeCheckEnabled = checks; } public void setRuntimeCheckEnabled(boolean runtimeCheckEnabled) { this.runtimeCheckEnabled = runtimeCheckEnabled; } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } protected OMVRBTreeEntry<K, V> getLastSearchNodeForSameKey(final Object key) { if (key != null && lastSearchKey != null) { if (key instanceof OCompositeKey) return key.equals(lastSearchKey) ? lastSearchNode : null; if (comparator != null) return comparator.compare((K) key, (K) lastSearchKey) == 0 ? lastSearchNode : null; else try { return ((Comparable<? super K>) key).compareTo((K) lastSearchKey) == 0 ? lastSearchNode : null; } catch (Exception e) { // IGNORE IT } } return null; } protected OMVRBTreeEntry<K, V> setLastSearchNode(final Object iKey, final OMVRBTreeEntry<K, V> iNode) { lastSearchKey = iKey; lastSearchNode = iNode; lastSearchFound = iNode != null ? iNode.tree.pageItemFound : false; lastSearchIndex = iNode != null ? iNode.tree.pageIndex : -1; return iNode; } protected void searchNodeCallback() { } protected void setSizeDelta(final int iDelta) { setSize(size() + iDelta); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
12
static final class AscendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866124060L; AscendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd, K hi, final boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return m.comparator(); } public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<K, V>(m, false, fromKey, fromInclusive, false, toKey, toInclusive); } public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, toKey, inclusive); } public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new AscendingSubMap<K, V>(m, false, fromKey, inclusive, toEnd, hi, hiInclusive); } public ONavigableMap<K, V> descendingMap() { ONavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } @Override OLazyIterator<K> keyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } @Override OLazyIterator<K> descendingKeyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } final class AscendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new SubMapEntryIterator(absLowest(), absHighFence()); } } @Override public Set<Map.Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new AscendingEntrySetView(); } @Override OMVRBTreeEntry<K, V> subLowest() { return absLowest().entry; } @Override OMVRBTreeEntry<K, V> subHighest() { return absHighest().entry; } @Override OMVRBTreeEntry<K, V> subCeiling(final K key) { return absCeiling(key).entry; } @Override OMVRBTreeEntry<K, V> subHigher(final K key) { return absHigher(key).entry; } @Override OMVRBTreeEntry<K, V> subFloor(final K key) { return absFloor(key).entry; } @Override OMVRBTreeEntry<K, V> subLower(final K key) { return absLower(key).entry; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
13
final class AscendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new SubMapEntryIterator(absLowest(), absHighFence()); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
14
final class DescendingKeyIterator extends AbstractEntryIterator<K, V, K> { DescendingKeyIterator(final OMVRBTreeEntry<K, V> first) { super(first); } public K next() { return prevEntry().getKey(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
15
static final class DescendingSubMap<K, V> extends NavigableSubMap<K, V> { private static final long serialVersionUID = 912986545866120460L; private final Comparator<? super K> reverseComparator = Collections.reverseOrder(m.comparator); DescendingSubMap(final OMVRBTree<K, V> m, final boolean fromStart, final K lo, final boolean loInclusive, final boolean toEnd, final K hi, final boolean hiInclusive) { super(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive); } public Comparator<? super K> comparator() { return reverseComparator; } public ONavigableMap<K, V> subMap(final K fromKey, final boolean fromInclusive, final K toKey, final boolean toInclusive) { if (!inRange(fromKey, fromInclusive)) throw new IllegalArgumentException("fromKey out of range"); if (!inRange(toKey, toInclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<K, V>(m, false, toKey, toInclusive, false, fromKey, fromInclusive); } public ONavigableMap<K, V> headMap(final K toKey, final boolean inclusive) { if (!inRange(toKey, inclusive)) throw new IllegalArgumentException("toKey out of range"); return new DescendingSubMap<K, V>(m, false, toKey, inclusive, toEnd, hi, hiInclusive); } public ONavigableMap<K, V> tailMap(final K fromKey, final boolean inclusive) { if (!inRange(fromKey, inclusive)) throw new IllegalArgumentException("fromKey out of range"); return new DescendingSubMap<K, V>(m, fromStart, lo, loInclusive, false, fromKey, inclusive); } public ONavigableMap<K, V> descendingMap() { ONavigableMap<K, V> mv = descendingMapView; return (mv != null) ? mv : (descendingMapView = new AscendingSubMap<K, V>(m, fromStart, lo, loInclusive, toEnd, hi, hiInclusive)); } @Override OLazyIterator<K> keyIterator() { return new DescendingSubMapKeyIterator(absHighest(), absLowFence()); } @Override OLazyIterator<K> descendingKeyIterator() { return new SubMapKeyIterator(absLowest(), absHighFence()); } final class DescendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new DescendingSubMapEntryIterator(absHighest(), absLowFence()); } } @Override public Set<Map.Entry<K, V>> entrySet() { EntrySetView es = entrySetView; return (es != null) ? es : new DescendingEntrySetView(); } @Override OMVRBTreeEntry<K, V> subLowest() { return absHighest().entry; } @Override OMVRBTreeEntry<K, V> subHighest() { return absLowest().entry; } @Override OMVRBTreeEntry<K, V> subCeiling(final K key) { return absFloor(key).entry; } @Override OMVRBTreeEntry<K, V> subHigher(final K key) { return absLower(key).entry; } @Override OMVRBTreeEntry<K, V> subFloor(final K key) { return absCeiling(key).entry; } @Override OMVRBTreeEntry<K, V> subLower(final K key) { return absHigher(key).entry; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
16
final class DescendingEntrySetView extends EntrySetView { @Override public Iterator<Map.Entry<K, V>> iterator() { return new DescendingSubMapEntryIterator(absHighest(), absLowFence()); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
17
final class EntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> { EntryIterator(final OMVRBTreeEntry<K, V> first) { super(first); } public Map.Entry<K, V> next() { return nextEntry(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
18
public class EntrySet extends AbstractSet<Map.Entry<K, V>> { @Override public Iterator<Map.Entry<K, V>> iterator() { return new EntryIterator(getFirstEntry()); } public Iterator<Map.Entry<K, V>> inverseIterator() { return new InverseEntryIterator(getLastEntry()); } @Override public boolean contains(final Object o) { if (!(o instanceof Map.Entry)) return false; OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final V value = entry.getValue(); final V p = get(entry.getKey()); return p != null && valEquals(p, value); } @Override public boolean remove(final Object o) { if (!(o instanceof Map.Entry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final V value = entry.getValue(); OMVRBTreeEntry<K, V> p = getEntry(entry.getKey(), PartialSearchMode.NONE); if (p != null && valEquals(p.getValue(), value)) { deleteEntry(p); return true; } return false; } @Override public int size() { return OMVRBTree.this.size(); } @Override public void clear() { OMVRBTree.this.clear(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
19
final class InverseEntryIterator extends AbstractEntryIterator<K, V, Map.Entry<K, V>> { InverseEntryIterator(final OMVRBTreeEntry<K, V> last) { super(last); // we have to set ourselves after current index to make iterator work if (last != null) { pageIndex = last.getTree().getPageIndex() + 1; } } public Map.Entry<K, V> next() { return prevEntry(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
20
final class KeyIterator extends AbstractEntryIterator<K, V, K> { KeyIterator(final OMVRBTreeEntry<K, V> first) { super(first); } @Override public K next() { return nextKey(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
21
@SuppressWarnings("rawtypes") static final class KeySet<E> extends AbstractSet<E> implements ONavigableSet<E> { private final ONavigableMap<E, Object> m; KeySet(ONavigableMap<E, Object> map) { m = map; } @Override public OLazyIterator<E> iterator() { if (m instanceof OMVRBTree) return ((OMVRBTree<E, Object>) m).keyIterator(); else return (((OMVRBTree.NavigableSubMap) m).keyIterator()); } public OLazyIterator<E> descendingIterator() { if (m instanceof OMVRBTree) return ((OMVRBTree<E, Object>) m).descendingKeyIterator(); else return (((OMVRBTree.NavigableSubMap) m).descendingKeyIterator()); } @Override public int size() { return m.size(); } @Override public boolean isEmpty() { return m.isEmpty(); } @Override public boolean contains(final Object o) { return m.containsKey(o); } @Override public void clear() { m.clear(); } public E lower(final E e) { return m.lowerKey(e); } public E floor(final E e) { return m.floorKey(e); } public E ceiling(final E e) { return m.ceilingKey(e); } public E higher(final E e) { return m.higherKey(e); } public E first() { return m.firstKey(); } public E last() { return m.lastKey(); } public Comparator<? super E> comparator() { return m.comparator(); } public E pollFirst() { final Map.Entry<E, Object> e = m.pollFirstEntry(); return e == null ? null : e.getKey(); } public E pollLast() { final Map.Entry<E, Object> e = m.pollLastEntry(); return e == null ? null : e.getKey(); } @Override public boolean remove(final Object o) { final int oldSize = size(); m.remove(o); return size() != oldSize; } public ONavigableSet<E> subSet(final E fromElement, final boolean fromInclusive, final E toElement, final boolean toInclusive) { return new OMVRBTreeSet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } public ONavigableSet<E> headSet(final E toElement, final boolean inclusive) { return new OMVRBTreeSet<E>(m.headMap(toElement, inclusive)); } public ONavigableSet<E> tailSet(final E fromElement, final boolean inclusive) { return new OMVRBTreeSet<E>(m.tailMap(fromElement, inclusive)); } public SortedSet<E> subSet(final E fromElement, final E toElement) { return subSet(fromElement, true, toElement, false); } public SortedSet<E> headSet(final E toElement) { return headSet(toElement, false); } public SortedSet<E> tailSet(final E fromElement) { return tailSet(fromElement, true); } public ONavigableSet<E> descendingSet() { return new OMVRBTreeSet<E>(m.descendingMap()); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
22
static abstract class NavigableSubMap<K, V> extends AbstractMap<K, V> implements ONavigableMap<K, V>, java.io.Serializable { /** * The backing map. */ final OMVRBTree<K, V> m; /** * Endpoints are represented as triples (fromStart, lo, loInclusive) and (toEnd, hi, hiInclusive). If fromStart is true, then * the low (absolute) bound is the start of the backing map, and the other values are ignored. Otherwise, if loInclusive is * true, lo is the inclusive bound, else lo is the exclusive bound. Similarly for the upper bound. */ final K lo, hi; final boolean fromStart, toEnd; final boolean loInclusive, hiInclusive; NavigableSubMap(final OMVRBTree<K, V> m, final boolean fromStart, K lo, final boolean loInclusive, final boolean toEnd, K hi, final boolean hiInclusive) { if (!fromStart && !toEnd) { if (m.compare(lo, hi) > 0) throw new IllegalArgumentException("fromKey > toKey"); } else { if (!fromStart) // type check m.compare(lo, lo); if (!toEnd) m.compare(hi, hi); } this.m = m; this.fromStart = fromStart; this.lo = lo; this.loInclusive = loInclusive; this.toEnd = toEnd; this.hi = hi; this.hiInclusive = hiInclusive; } // internal utilities final boolean tooLow(final Object key) { if (!fromStart) { int c = m.compare(key, lo); if (c < 0 || (c == 0 && !loInclusive)) return true; } return false; } final boolean tooHigh(final Object key) { if (!toEnd) { int c = m.compare(key, hi); if (c > 0 || (c == 0 && !hiInclusive)) return true; } return false; } final boolean inRange(final Object key) { return !tooLow(key) && !tooHigh(key); } final boolean inClosedRange(final Object key) { return (fromStart || m.compare(key, lo) >= 0) && (toEnd || m.compare(hi, key) >= 0); } final boolean inRange(final Object key, final boolean inclusive) { return inclusive ? inRange(key) : inClosedRange(key); } /* * Absolute versions of relation operations. Subclasses map to these using like-named "sub" versions that invert senses for * descending maps */ final OMVRBTreeEntryPosition<K, V> absLowest() { OMVRBTreeEntry<K, V> e = (fromStart ? m.getFirstEntry() : (loInclusive ? m.getCeilingEntry(lo, PartialSearchMode.LOWEST_BOUNDARY) : m.getHigherEntry(lo))); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absHighest() { OMVRBTreeEntry<K, V> e = (toEnd ? m.getLastEntry() : (hiInclusive ? m.getFloorEntry(hi, PartialSearchMode.HIGHEST_BOUNDARY) : m.getLowerEntry(hi))); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absCeiling(K key) { if (tooLow(key)) return absLowest(); OMVRBTreeEntry<K, V> e = m.getCeilingEntry(key, PartialSearchMode.NONE); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absHigher(K key) { if (tooLow(key)) return absLowest(); OMVRBTreeEntry<K, V> e = m.getHigherEntry(key); return (e == null || tooHigh(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absFloor(K key) { if (tooHigh(key)) return absHighest(); OMVRBTreeEntry<K, V> e = m.getFloorEntry(key, PartialSearchMode.NONE); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } final OMVRBTreeEntryPosition<K, V> absLower(K key) { if (tooHigh(key)) return absHighest(); OMVRBTreeEntry<K, V> e = m.getLowerEntry(key); return (e == null || tooLow(e.getKey())) ? null : new OMVRBTreeEntryPosition<K, V>(e); } /** Returns the absolute high fence for ascending traversal */ final OMVRBTreeEntryPosition<K, V> absHighFence() { return (toEnd ? null : new OMVRBTreeEntryPosition<K, V>(hiInclusive ? m.getHigherEntry(hi) : m.getCeilingEntry(hi, PartialSearchMode.LOWEST_BOUNDARY))); } /** Return the absolute low fence for descending traversal */ final OMVRBTreeEntryPosition<K, V> absLowFence() { return (fromStart ? null : new OMVRBTreeEntryPosition<K, V>(loInclusive ? m.getLowerEntry(lo) : m.getFloorEntry(lo, PartialSearchMode.HIGHEST_BOUNDARY))); } // Abstract methods defined in ascending vs descending classes // These relay to the appropriate absolute versions abstract OMVRBTreeEntry<K, V> subLowest(); abstract OMVRBTreeEntry<K, V> subHighest(); abstract OMVRBTreeEntry<K, V> subCeiling(K key); abstract OMVRBTreeEntry<K, V> subHigher(K key); abstract OMVRBTreeEntry<K, V> subFloor(K key); abstract OMVRBTreeEntry<K, V> subLower(K key); /** Returns ascending iterator from the perspective of this submap */ abstract OLazyIterator<K> keyIterator(); /** Returns descending iterator from the perspective of this submap */ abstract OLazyIterator<K> descendingKeyIterator(); // public methods @Override public boolean isEmpty() { return (fromStart && toEnd) ? m.isEmpty() : entrySet().isEmpty(); } @Override public int size() { return (fromStart && toEnd) ? m.size() : entrySet().size(); } @Override public final boolean containsKey(Object key) { return inRange(key) && m.containsKey(key); } @Override public final V put(K key, V value) { if (!inRange(key)) throw new IllegalArgumentException("key out of range"); return m.put(key, value); } @Override public final V get(Object key) { return !inRange(key) ? null : m.get(key); } @Override public final V remove(Object key) { return !inRange(key) ? null : m.remove(key); } public final Map.Entry<K, V> ceilingEntry(K key) { return exportEntry(subCeiling(key)); } public final K ceilingKey(K key) { return keyOrNull(subCeiling(key)); } public final Map.Entry<K, V> higherEntry(K key) { return exportEntry(subHigher(key)); } public final K higherKey(K key) { return keyOrNull(subHigher(key)); } public final Map.Entry<K, V> floorEntry(K key) { return exportEntry(subFloor(key)); } public final K floorKey(K key) { return keyOrNull(subFloor(key)); } public final Map.Entry<K, V> lowerEntry(K key) { return exportEntry(subLower(key)); } public final K lowerKey(K key) { return keyOrNull(subLower(key)); } public final K firstKey() { return key(subLowest()); } public final K lastKey() { return key(subHighest()); } public final Map.Entry<K, V> firstEntry() { return exportEntry(subLowest()); } public final Map.Entry<K, V> lastEntry() { return exportEntry(subHighest()); } public final Map.Entry<K, V> pollFirstEntry() { OMVRBTreeEntry<K, V> e = subLowest(); Map.Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } public final Map.Entry<K, V> pollLastEntry() { OMVRBTreeEntry<K, V> e = subHighest(); Map.Entry<K, V> result = exportEntry(e); if (e != null) m.deleteEntry(e); return result; } // Views transient ONavigableMap<K, V> descendingMapView = null; transient EntrySetView entrySetView = null; transient KeySet<K> navigableKeySetView = null; @SuppressWarnings("rawtypes") public final ONavigableSet<K> navigableKeySet() { KeySet<K> nksv = navigableKeySetView; return (nksv != null) ? nksv : (navigableKeySetView = new OMVRBTree.KeySet(this)); } @Override public final Set<K> keySet() { return navigableKeySet(); } public ONavigableSet<K> descendingKeySet() { return descendingMap().navigableKeySet(); } public final SortedMap<K, V> subMap(final K fromKey, final K toKey) { return subMap(fromKey, true, toKey, false); } public final SortedMap<K, V> headMap(final K toKey) { return headMap(toKey, false); } public final SortedMap<K, V> tailMap(final K fromKey) { return tailMap(fromKey, true); } // View classes abstract class EntrySetView extends AbstractSet<Map.Entry<K, V>> { private transient int size = -1, sizeModCount; @Override public int size() { if (fromStart && toEnd) return m.size(); if (size == -1 || sizeModCount != m.modCount) { sizeModCount = m.modCount; size = 0; Iterator<?> i = iterator(); while (i.hasNext()) { size++; i.next(); } } return size; } @Override public boolean isEmpty() { OMVRBTreeEntryPosition<K, V> n = absLowest(); return n == null || tooHigh(n.getKey()); } @Override public boolean contains(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; V nodeValue = m.get(key); return nodeValue != null && valEquals(nodeValue, entry.getValue()); } @Override public boolean remove(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; final OMVRBTreeEntry<K, V> node = m.getEntry(key, PartialSearchMode.NONE); if (node != null && valEquals(node.getValue(), entry.getValue())) { m.deleteEntry(node); return true; } return false; } } /** * Iterators for SubMaps */ abstract class SubMapIterator<T> implements OLazyIterator<T> { OMVRBTreeEntryPosition<K, V> lastReturned; OMVRBTreeEntryPosition<K, V> next; final K fenceKey; int expectedModCount; SubMapIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { expectedModCount = m.modCount; lastReturned = null; next = first; fenceKey = fence == null ? null : fence.getKey(); } public final boolean hasNext() { if (next != null) { final K k = next.getKey(); return k != fenceKey && !k.equals(fenceKey); } return false; } final OMVRBTreeEntryPosition<K, V> nextEntry() { final OMVRBTreeEntryPosition<K, V> e; if (next != null) e = new OMVRBTreeEntryPosition<K, V>(next); else e = null; if (e == null || e.entry == null) throw new NoSuchElementException(); final K k = e.getKey(); if (k == fenceKey || k.equals(fenceKey)) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next.assign(OMVRBTree.next(e)); lastReturned = e; return e; } final OMVRBTreeEntryPosition<K, V> prevEntry() { final OMVRBTreeEntryPosition<K, V> e; if (next != null) e = new OMVRBTreeEntryPosition<K, V>(next); else e = null; if (e == null || e.entry == null) throw new NoSuchElementException(); final K k = e.getKey(); if (k == fenceKey || k.equals(fenceKey)) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next.assign(OMVRBTree.previous(e)); lastReturned = e; return e; } final public T update(final T iValue) { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); return (T) lastReturned.entry.setValue((V) iValue); } final void removeAscending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.entry.getLeft() != null && lastReturned.entry.getRight() != null) next = lastReturned; m.deleteEntry(lastReturned.entry); lastReturned = null; expectedModCount = m.modCount; } final void removeDescending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); m.deleteEntry(lastReturned.entry); lastReturned = null; expectedModCount = m.modCount; } } final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { SubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { super(first, fence); } public Map.Entry<K, V> next() { final Map.Entry<K, V> e = OMVRBTree.exportEntry(next); nextEntry(); return e; } public void remove() { removeAscending(); } } final class SubMapKeyIterator extends SubMapIterator<K> { SubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { super(first, fence); } public K next() { return nextEntry().getKey(); } public void remove() { removeAscending(); } } final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { DescendingSubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public Map.Entry<K, V> next() { final Map.Entry<K, V> e = OMVRBTree.exportEntry(next); prevEntry(); return e; } public void remove() { removeDescending(); } } final class DescendingSubMapKeyIterator extends SubMapIterator<K> { DescendingSubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public K next() { return prevEntry().getKey(); } public void remove() { removeDescending(); } } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
23
final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { DescendingSubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public Map.Entry<K, V> next() { final Map.Entry<K, V> e = OMVRBTree.exportEntry(next); prevEntry(); return e; } public void remove() { removeDescending(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
24
final class DescendingSubMapKeyIterator extends SubMapIterator<K> { DescendingSubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> last, final OMVRBTreeEntryPosition<K, V> fence) { super(last, fence); } public K next() { return prevEntry().getKey(); } public void remove() { removeDescending(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
25
abstract class EntrySetView extends AbstractSet<Map.Entry<K, V>> { private transient int size = -1, sizeModCount; @Override public int size() { if (fromStart && toEnd) return m.size(); if (size == -1 || sizeModCount != m.modCount) { sizeModCount = m.modCount; size = 0; Iterator<?> i = iterator(); while (i.hasNext()) { size++; i.next(); } } return size; } @Override public boolean isEmpty() { OMVRBTreeEntryPosition<K, V> n = absLowest(); return n == null || tooHigh(n.getKey()); } @Override public boolean contains(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; V nodeValue = m.get(key); return nodeValue != null && valEquals(nodeValue, entry.getValue()); } @Override public boolean remove(final Object o) { if (!(o instanceof OMVRBTreeEntry)) return false; final OMVRBTreeEntry<K, V> entry = (OMVRBTreeEntry<K, V>) o; final K key = entry.getKey(); if (!inRange(key)) return false; final OMVRBTreeEntry<K, V> node = m.getEntry(key, PartialSearchMode.NONE); if (node != null && valEquals(node.getValue(), entry.getValue())) { m.deleteEntry(node); return true; } return false; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
26
final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K, V>> { SubMapEntryIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { super(first, fence); } public Map.Entry<K, V> next() { final Map.Entry<K, V> e = OMVRBTree.exportEntry(next); nextEntry(); return e; } public void remove() { removeAscending(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
27
abstract class SubMapIterator<T> implements OLazyIterator<T> { OMVRBTreeEntryPosition<K, V> lastReturned; OMVRBTreeEntryPosition<K, V> next; final K fenceKey; int expectedModCount; SubMapIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { expectedModCount = m.modCount; lastReturned = null; next = first; fenceKey = fence == null ? null : fence.getKey(); } public final boolean hasNext() { if (next != null) { final K k = next.getKey(); return k != fenceKey && !k.equals(fenceKey); } return false; } final OMVRBTreeEntryPosition<K, V> nextEntry() { final OMVRBTreeEntryPosition<K, V> e; if (next != null) e = new OMVRBTreeEntryPosition<K, V>(next); else e = null; if (e == null || e.entry == null) throw new NoSuchElementException(); final K k = e.getKey(); if (k == fenceKey || k.equals(fenceKey)) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next.assign(OMVRBTree.next(e)); lastReturned = e; return e; } final OMVRBTreeEntryPosition<K, V> prevEntry() { final OMVRBTreeEntryPosition<K, V> e; if (next != null) e = new OMVRBTreeEntryPosition<K, V>(next); else e = null; if (e == null || e.entry == null) throw new NoSuchElementException(); final K k = e.getKey(); if (k == fenceKey || k.equals(fenceKey)) throw new NoSuchElementException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); next.assign(OMVRBTree.previous(e)); lastReturned = e; return e; } final public T update(final T iValue) { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); return (T) lastReturned.entry.setValue((V) iValue); } final void removeAscending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); // deleted entries are replaced by their successors if (lastReturned.entry.getLeft() != null && lastReturned.entry.getRight() != null) next = lastReturned; m.deleteEntry(lastReturned.entry); lastReturned = null; expectedModCount = m.modCount; } final void removeDescending() { if (lastReturned == null) throw new IllegalStateException(); if (m.modCount != expectedModCount) throw new ConcurrentModificationException(); m.deleteEntry(lastReturned.entry); lastReturned = null; expectedModCount = m.modCount; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
28
final class SubMapKeyIterator extends SubMapIterator<K> { SubMapKeyIterator(final OMVRBTreeEntryPosition<K, V> first, final OMVRBTreeEntryPosition<K, V> fence) { super(first, fence); } public K next() { return nextEntry().getKey(); } public void remove() { removeAscending(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
29
public static enum PartialSearchMode { /** * Any partially matched key will be used as search result. */ NONE, /** * The biggest partially matched key will be used as search result. */ HIGHEST_BOUNDARY, /** * The smallest partially matched key will be used as search result. */ LOWEST_BOUNDARY }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
30
final class ValueInverseIterator extends AbstractEntryIterator<K, V, V> { ValueInverseIterator(final OMVRBTreeEntry<K, V> last) { super(last); // we have to set ourselves after current index to make iterator work if (last != null) { pageIndex = last.getTree().getPageIndex() + 1; } } @Override public boolean hasNext() { return hasPrevious(); } @Override public V next() { return prevValue(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
31
final class ValueIterator extends AbstractEntryIterator<K, V, V> { ValueIterator(final OMVRBTreeEntry<K, V> first) { super(first); } @Override public V next() { return nextValue(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
32
public class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { return new ValueIterator(getFirstEntry()); } public Iterator<V> inverseIterator() { return new ValueInverseIterator(getLastEntry()); } @Override public int size() { return OMVRBTree.this.size(); } @Override public boolean contains(final Object o) { return OMVRBTree.this.containsValue(o); } @Override public boolean remove(final Object o) { for (OMVRBTreeEntry<K, V> e = getFirstEntry(); e != null; e = next(e)) { if (valEquals(e.getValue(), o)) { deleteEntry(e); return true; } } return false; } @Override public void clear() { OMVRBTree.this.clear(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTree.java
33
@Test public class OMVRBTreeCompositeTest { protected OMVRBTree<OCompositeKey, Double> tree; @BeforeMethod public void beforeMethod() throws Exception { tree = new OMVRBTreeMemory<OCompositeKey, Double>(4, 0.5f, 2); for (double i = 1; i < 4; i++) { for (double j = 1; j < 10; j++) { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey(i); compositeKey.addKey(j); tree.put(compositeKey, i * 4 + j); } } } @Test public void testGetEntrySameKeys() { OMVRBTreeEntry<OCompositeKey, Double> result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.NONE); assertEquals(result.getKey(), compositeKey(1.0, 2.0)); result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY); assertEquals(result.getKey(), compositeKey(1.0, 2.0)); result = tree.getEntry(compositeKey(1.0, 2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY); assertEquals(result.getKey(), compositeKey(1.0, 2.0)); } @Test public void testGetEntryPartialKeys() { OMVRBTreeEntry<OCompositeKey, Double> result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.NONE); assertEquals(result.getKey().getKeys().get(0), 2.0); result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY); assertEquals(result.getKey(), compositeKey(2.0, 1.0)); result = tree.getEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY); assertEquals(result.getKey(), compositeKey(2.0, 9.0)); } @Test public void testSubMapInclusiveDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), true) .descendingMap(); assertEquals(navigableMap.size(), 18); for (double i = 2; i <= 3; i++) { for (double j = 1; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } } @Test public void testSubMapFromInclusiveDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), false) .descendingMap(); assertEquals(navigableMap.size(), 9); for (double j = 1; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(2.0, j))); } } @Test public void testSubMapToInclusiveDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), true) .descendingMap(); assertEquals(navigableMap.size(), 9); for (double i = 1; i <= 9; i++) { assertTrue(navigableMap.containsKey(compositeKey(3.0, i))); } } @Test public void testSubMapNonInclusiveDescending() { ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), false) .descendingMap(); assertEquals(navigableMap.size(), 0); assertTrue(navigableMap.isEmpty()); navigableMap = tree.subMap(compositeKey(1.0), false, compositeKey(3.0), false); assertEquals(navigableMap.size(), 9); for (double i = 1; i <= 9; i++) { assertTrue(navigableMap.containsKey(compositeKey(2.0, i))); } } @Test public void testSubMapInclusive() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), true); assertEquals(navigableMap.size(), 18); for (double i = 2; i <= 3; i++) { for (double j = 1; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } } @Test public void testSubMapFromInclusive() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), true, compositeKey(3.0), false); assertEquals(navigableMap.size(), 9); for (double j = 1; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(2.0, j))); } } @Test public void testSubMapToInclusive() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), true); assertEquals(navigableMap.size(), 9); for (double i = 1; i <= 9; i++) { assertTrue(navigableMap.containsKey(compositeKey(3.0, i))); } } @Test public void testSubMapNonInclusive() { ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0), false, compositeKey(3.0), false); assertEquals(navigableMap.size(), 0); assertTrue(navigableMap.isEmpty()); navigableMap = tree.subMap(compositeKey(1.0), false, compositeKey(3.0), false); assertEquals(navigableMap.size(), 9); for (double i = 1; i <= 9; i++) { assertTrue(navigableMap.containsKey(compositeKey(2.0, i))); } } @Test public void testSubMapInclusivePartialKey() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), true); assertEquals(navigableMap.size(), 15); for (double i = 2; i <= 3; i++) { for (double j = 1; j <= 9; j++) { if (i == 2 && j < 4) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } } @Test public void testSubMapFromInclusivePartialKey() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), false); assertEquals(navigableMap.size(), 6); for (double j = 4; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(2.0, j))); } } @Test public void testSubMapToInclusivePartialKey() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), true); assertEquals(navigableMap.size(), 14); for (double i = 2; i <= 3; i++) { for (double j = 1; j <= 9; j++) { if (i == 2 && j <= 4) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } } @Test public void testSubMapNonInclusivePartial() { ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), false); assertEquals(navigableMap.size(), 5); for (double i = 5; i <= 9; i++) { assertTrue(navigableMap.containsKey(compositeKey(2.0, i))); } } @Test public void testSubMapInclusivePartialKeyDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), true) .descendingMap(); assertEquals(navigableMap.size(), 15); for (double i = 2; i <= 3; i++) { for (double j = 1; j <= 9; j++) { if (i == 2 && j < 4) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } } @Test public void testSubMapFromInclusivePartialKeyDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), true, compositeKey(3.0), false) .descendingMap(); assertEquals(navigableMap.size(), 6); for (double j = 4; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(2.0, j))); } } @Test public void testSubMapToInclusivePartialKeyDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), true) .descendingMap(); assertEquals(navigableMap.size(), 14); for (double i = 2; i <= 3; i++) { for (double j = 1; j <= 9; j++) { if (i == 2 && j <= 4) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } } @Test public void testSubMapNonInclusivePartialDescending() { ONavigableMap<OCompositeKey, Double> navigableMap = tree.subMap(compositeKey(2.0, 4.0), false, compositeKey(3.0), false) .descendingMap(); assertEquals(navigableMap.size(), 5); for (double i = 5; i <= 9; i++) { assertTrue(navigableMap.containsKey(compositeKey(2.0, i))); } } @Test public void testTailMapInclusivePartial() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), true); assertEquals(navigableMap.size(), 18); for (double i = 2; i <= 3; i++) for (double j = 1; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testTailMapNonInclusivePartial() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), false); assertEquals(navigableMap.size(), 9); for (double i = 1; i <= 9; i++) { assertTrue(navigableMap.containsKey(compositeKey(3.0, i))); } } @Test public void testTailMapInclusivePartialDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), true).descendingMap(); assertEquals(navigableMap.size(), 18); for (double i = 2; i <= 3; i++) for (double j = 1; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testTailMapNonInclusivePartialDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0), false).descendingMap(); assertEquals(navigableMap.size(), 9); for (double i = 1; i <= 9; i++) { assertTrue(navigableMap.containsKey(compositeKey(3.0, i))); } } @Test public void testTailMapInclusive() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), true); assertEquals(navigableMap.size(), 16); for (double i = 2; i <= 3; i++) for (double j = 1; j <= 9; j++) { if (i == 2 && j < 3) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testTailMapNonInclusive() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), false); assertEquals(navigableMap.size(), 15); for (double i = 2; i <= 3; i++) for (double j = 1; j <= 9; j++) { if (i == 2 && j <= 3) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testTailMapInclusiveDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), true).descendingMap(); assertEquals(navigableMap.size(), 16); for (double i = 2; i <= 3; i++) for (double j = 1; j <= 9; j++) { if (i == 2 && j < 3) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testTailMapNonInclusiveDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.tailMap(compositeKey(2.0, 3.0), false).descendingMap(); assertEquals(navigableMap.size(), 15); for (double i = 2; i <= 3; i++) for (double j = 1; j <= 9; j++) { if (i == 2 && j <= 3) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testHeadMapInclusivePartial() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), true); assertEquals(navigableMap.size(), 27); for (double i = 1; i <= 3; i++) for (double j = 1; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testHeadMapNonInclusivePartial() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), false); assertEquals(navigableMap.size(), 18); for (double i = 1; i < 3; i++) for (double j = 1; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testHeadMapInclusivePartialDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), true).descendingMap(); assertEquals(navigableMap.size(), 27); for (double i = 1; i <= 3; i++) for (double j = 1; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testHeadMapNonInclusivePartialDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0), false).descendingMap(); assertEquals(navigableMap.size(), 18); for (double i = 1; i < 3; i++) for (double j = 1; j <= 9; j++) { assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testHeadMapInclusive() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), true); assertEquals(navigableMap.size(), 20); for (double i = 1; i <= 3; i++) for (double j = 1; j <= 9; j++) { if (i == 3 && j > 2) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testHeadMapNonInclusive() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), false); assertEquals(navigableMap.size(), 19); for (double i = 1; i < 3; i++) for (double j = 1; j <= 9; j++) { if (i == 3 && j >= 2) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testHeadMapInclusiveDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), true).descendingMap(); assertEquals(navigableMap.size(), 20); for (double i = 1; i <= 3; i++) for (double j = 1; j <= 9; j++) { if (i == 3 && j > 2) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testHeadMapNonInclusiveDescending() { final ONavigableMap<OCompositeKey, Double> navigableMap = tree.headMap(compositeKey(3.0, 2.0), false).descendingMap(); assertEquals(navigableMap.size(), 19); for (double i = 1; i < 3; i++) for (double j = 1; j <= 9; j++) { if (i == 3 && j >= 2) continue; assertTrue(navigableMap.containsKey(compositeKey(i, j))); } } @Test public void testGetCeilingEntryKeyExistPartial() { OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.NONE); assertEquals(entry.getKey().getKeys().get(0), 3.0); entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY); assertEquals(entry.getKey(), compositeKey(3.0, 9.0)); entry = tree.getCeilingEntry(compositeKey(3.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY); assertEquals(entry.getKey(), compositeKey(3.0, 1.0)); } @Test public void testGetCeilingEntryKeyNotExistPartial() { OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.NONE); assertEquals(entry.getKey().getKeys().get(0), 2.0); entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY); assertEquals(entry.getKey(), compositeKey(2.0, 9.0)); entry = tree.getCeilingEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY); assertEquals(entry.getKey(), compositeKey(2.0, 1.0)); } @Test public void testGetFloorEntryKeyExistPartial() { OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.NONE); assertEquals(entry.getKey().getKeys().get(0), 2.0); entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY); assertEquals(entry.getKey(), compositeKey(2.0, 9.0)); entry = tree.getFloorEntry(compositeKey(2.0), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY); assertEquals(entry.getKey(), compositeKey(2.0, 1.0)); } @Test public void testGetFloorEntryKeyNotExistPartial() { OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.NONE); assertEquals(entry.getKey().getKeys().get(0), 1.0); entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY); assertEquals(entry.getKey(), compositeKey(1.0, 9.0)); entry = tree.getFloorEntry(compositeKey(1.3), OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY); assertEquals(entry.getKey(), compositeKey(1.0, 1.0)); } @Test public void testHigherEntryKeyExistPartial() { OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(2.0)); assertEquals(entry.getKey(), compositeKey(3.0, 1.0)); } @Test public void testHigherEntryKeyNotExist() { OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(1.3)); assertEquals(entry.getKey(), compositeKey(2.0, 1.0)); } @Test public void testHigherEntryNullResult() { OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getHigherEntry(compositeKey(12.0)); assertNull(entry); } @Test public void testLowerEntryNullResult() { OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(0.0)); assertNull(entry); } @Test public void testLowerEntryKeyExist() { OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(2.0)); assertEquals(entry.getKey(), compositeKey(1.0, 9.0)); } @Test public void testLowerEntryKeyNotExist() { OMVRBTreeEntry<OCompositeKey, Double> entry = tree.getLowerEntry(compositeKey(2.5)); assertEquals(entry.getKey(), compositeKey(2.0, 9.0)); } private OCompositeKey compositeKey(Comparable<?>... params) { return new OCompositeKey(Arrays.asList(params)); } }
false
core_src_test_java_com_orientechnologies_common_collection_OMVRBTreeCompositeTest.java
34
@SuppressWarnings("unchecked") public abstract class OMVRBTreeEntry<K, V> implements Map.Entry<K, V>, Comparable<OMVRBTreeEntry<K, V>> { protected OMVRBTree<K, V> tree; private int pageSplitItems; public static final int BINARY_SEARCH_THRESHOLD = 10; /** * Constructor called on unmarshalling. * */ protected OMVRBTreeEntry(final OMVRBTree<K, V> iTree) { tree = iTree; } public abstract void setLeft(OMVRBTreeEntry<K, V> left); public abstract OMVRBTreeEntry<K, V> getLeft(); public abstract void setRight(OMVRBTreeEntry<K, V> right); public abstract OMVRBTreeEntry<K, V> getRight(); public abstract OMVRBTreeEntry<K, V> setParent(OMVRBTreeEntry<K, V> parent); public abstract OMVRBTreeEntry<K, V> getParent(); protected abstract OMVRBTreeEntry<K, V> getLeftInMemory(); protected abstract OMVRBTreeEntry<K, V> getParentInMemory(); protected abstract OMVRBTreeEntry<K, V> getRightInMemory(); protected abstract OMVRBTreeEntry<K, V> getNextInMemory(); /** * Returns the first Entry only by traversing the memory, or null if no such. */ public OMVRBTreeEntry<K, V> getFirstInMemory() { OMVRBTreeEntry<K, V> node = this; OMVRBTreeEntry<K, V> prev = this; while (node != null) { prev = node; node = node.getPreviousInMemory(); } return prev; } /** * Returns the previous of the current Entry only by traversing the memory, or null if no such. */ public OMVRBTreeEntry<K, V> getPreviousInMemory() { OMVRBTreeEntry<K, V> t = this; OMVRBTreeEntry<K, V> p = null; if (t.getLeftInMemory() != null) { p = t.getLeftInMemory(); while (p.getRightInMemory() != null) p = p.getRightInMemory(); } else { p = t.getParentInMemory(); while (p != null && t == p.getLeftInMemory()) { t = p; p = p.getParentInMemory(); } } return p; } protected OMVRBTree<K, V> getTree() { return tree; } public int getDepth() { int level = 0; OMVRBTreeEntry<K, V> entry = this; while (entry.getParent() != null) { level++; entry = entry.getParent(); } return level; } /** * Returns the key. * * @return the key */ public K getKey() { return getKey(tree.pageIndex); } public K getKey(final int iIndex) { if (iIndex >= getSize()) throw new IndexOutOfBoundsException("Requested index " + iIndex + " when the range is 0-" + getSize()); tree.pageIndex = iIndex; return getKeyAt(iIndex); } protected abstract K getKeyAt(final int iIndex); /** * Returns the value associated with the key. * * @return the value associated with the key */ public V getValue() { if (tree.pageIndex == -1) return getValueAt(0); return getValueAt(tree.pageIndex); } public V getValue(final int iIndex) { tree.pageIndex = iIndex; return getValueAt(iIndex); } protected abstract V getValueAt(int iIndex); public int getFreeSpace() { return getPageSize() - getSize(); } /** * Execute a binary search between the keys of the node. The keys are always kept ordered. It update the pageIndex attribute with * the most closer key found (useful for the next inserting). * * @param iKey * Key to find * @return The value found if any, otherwise null */ protected V search(final K iKey) { tree.pageItemFound = false; int size = getSize(); if (size == 0) return null; // CHECK THE LOWER LIMIT if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare(iKey, getKeyAt(0)); else tree.pageItemComparator = ((Comparable<? super K>) iKey).compareTo(getKeyAt(0)); if (tree.pageItemComparator == 0) { // FOUND: SET THE INDEX AND RETURN THE NODE tree.pageItemFound = true; tree.pageIndex = 0; return getValueAt(tree.pageIndex); } else if (tree.pageItemComparator < 0) { // KEY OUT OF FIRST ITEM: AVOID SEARCH AND RETURN THE FIRST POSITION tree.pageIndex = 0; return null; } else { // CHECK THE UPPER LIMIT if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare((K) iKey, getKeyAt(size - 1)); else tree.pageItemComparator = ((Comparable<? super K>) iKey).compareTo(getKeyAt(size - 1)); if (tree.pageItemComparator > 0) { // KEY OUT OF LAST ITEM: AVOID SEARCH AND RETURN THE LAST POSITION tree.pageIndex = size; return null; } } if (size < BINARY_SEARCH_THRESHOLD) return linearSearch(iKey); else return binarySearch(iKey); } /** * Linear search inside the node * * @param iKey * Key to search * @return Value if found, otherwise null and the tree.pageIndex updated with the closest-after-first position valid for further * inserts. */ private V linearSearch(final K iKey) { V value = null; int i = 0; tree.pageItemComparator = -1; for (int s = getSize(); i < s; ++i) { if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare(getKeyAt(i), iKey); else tree.pageItemComparator = ((Comparable<? super K>) getKeyAt(i)).compareTo(iKey); if (tree.pageItemComparator == 0) { // FOUND: SET THE INDEX AND RETURN THE NODE tree.pageItemFound = true; value = getValueAt(i); break; } else if (tree.pageItemComparator > 0) break; } tree.pageIndex = i; return value; } /** * Binary search inside the node * * @param iKey * Key to search * @return Value if found, otherwise null and the tree.pageIndex updated with the closest-after-first position valid for further * inserts. */ private V binarySearch(final K iKey) { int low = 0; int high = getSize() - 1; int mid = 0; while (low <= high) { mid = (low + high) >>> 1; Object midVal = getKeyAt(mid); if (tree.comparator != null) tree.pageItemComparator = tree.comparator.compare((K) midVal, iKey); else tree.pageItemComparator = ((Comparable<? super K>) midVal).compareTo(iKey); if (tree.pageItemComparator == 0) { // FOUND: SET THE INDEX AND RETURN THE NODE tree.pageItemFound = true; tree.pageIndex = mid; return getValueAt(tree.pageIndex); } if (low == high) break; if (tree.pageItemComparator < 0) low = mid + 1; else high = mid; } tree.pageIndex = mid; return null; } protected abstract void insert(final int iPosition, final K key, final V value); protected abstract void remove(); protected abstract void setColor(boolean iColor); public abstract boolean getColor(); public abstract int getSize(); public K getLastKey() { return getKey(getSize() - 1); } public K getFirstKey() { return getKey(0); } protected abstract void copyFrom(final OMVRBTreeEntry<K, V> iSource); public int getPageSplitItems() { return pageSplitItems; } protected void init() { pageSplitItems = (int) (getPageSize() * tree.pageLoadFactor); } public abstract int getPageSize(); /** * Compares two nodes by their first keys. */ public int compareTo(final OMVRBTreeEntry<K, V> o) { if (o == null) return 1; if (o == this) return 0; if (getSize() == 0) return -1; if (o.getSize() == 0) return 1; if (tree.comparator != null) return tree.comparator.compare(getFirstKey(), o.getFirstKey()); return ((Comparable<K>) getFirstKey()).compareTo(o.getFirstKey()); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { int idx = tree.pageIndex; if (idx > -1 && idx < getSize()) return getKeyAt(idx) + "=" + getValueAt(idx); return null; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntry.java
35
@SuppressWarnings("unchecked") public class OMVRBTreeEntryMemory<K, V> extends OMVRBTreeEntry<K, V> { protected int size = 1; protected int pageSize; protected K[] keys; protected V[] values; protected OMVRBTreeEntryMemory<K, V> left = null; protected OMVRBTreeEntryMemory<K, V> right = null; protected OMVRBTreeEntryMemory<K, V> parent; protected boolean color = OMVRBTree.RED; /** * Constructor called on unmarshalling. * */ protected OMVRBTreeEntryMemory(final OMVRBTree<K, V> iTree) { super(iTree); } /** * Make a new cell with given key, value, and parent, and with <tt>null</tt> child links, and BLACK color. */ protected OMVRBTreeEntryMemory(final OMVRBTree<K, V> iTree, final K iKey, final V iValue, final OMVRBTreeEntryMemory<K, V> iParent) { super(iTree); setParent(iParent); pageSize = tree.getDefaultPageSize(); keys = (K[]) new Object[pageSize]; keys[0] = iKey; values = (V[]) new Object[pageSize]; values[0] = iValue; init(); } /** * Copy values from the parent node. * * @param iParent * @param iPosition */ protected OMVRBTreeEntryMemory(final OMVRBTreeEntryMemory<K, V> iParent, final int iPosition) { super(iParent.getTree()); pageSize = tree.getDefaultPageSize(); keys = (K[]) new Object[pageSize]; values = (V[]) new Object[pageSize]; size = iParent.size - iPosition; System.arraycopy(iParent.keys, iPosition, keys, 0, size); System.arraycopy(iParent.values, iPosition, values, 0, size); Arrays.fill(iParent.keys, iPosition, iParent.size, null); Arrays.fill(iParent.values, iPosition, iParent.size, null); iParent.size = iPosition; setParent(iParent); init(); } @Override protected void setColor(final boolean iColor) { this.color = iColor; } @Override public boolean getColor() { return color; } @Override public void setLeft(final OMVRBTreeEntry<K, V> iLeft) { left = (OMVRBTreeEntryMemory<K, V>) iLeft; if (iLeft != null && iLeft.getParent() != this) iLeft.setParent(this); } @Override public OMVRBTreeEntry<K, V> getLeft() { return left; } @Override public void setRight(final OMVRBTreeEntry<K, V> iRight) { right = (OMVRBTreeEntryMemory<K, V>) iRight; if (iRight != null && iRight.getParent() != this) iRight.setParent(this); } @Override public OMVRBTreeEntry<K, V> getRight() { return right; } @Override public OMVRBTreeEntry<K, V> setParent(final OMVRBTreeEntry<K, V> iParent) { parent = (OMVRBTreeEntryMemory<K, V>) iParent; return iParent; } @Override public OMVRBTreeEntry<K, V> getParent() { return parent; } /** * Returns the successor of the current Entry only by traversing the memory, or null if no such. */ @Override public OMVRBTreeEntryMemory<K, V> getNextInMemory() { OMVRBTreeEntryMemory<K, V> t = this; OMVRBTreeEntryMemory<K, V> p = null; if (t.right != null) { p = t.right; while (p.left != null) p = p.left; } else { p = t.parent; while (p != null && t == p.right) { t = p; p = p.parent; } } return p; } public int getSize() { return size; } public int getPageSize() { return pageSize; } @Override protected OMVRBTreeEntry<K, V> getLeftInMemory() { return left; } @Override protected OMVRBTreeEntry<K, V> getParentInMemory() { return parent; } @Override protected OMVRBTreeEntry<K, V> getRightInMemory() { return right; } protected K getKeyAt(final int iIndex) { return keys[iIndex]; } protected V getValueAt(int iIndex) { return values[iIndex]; } /** * Replaces the value currently associated with the key with the given value. * * @return the value associated with the key before this method was called */ public V setValue(final V value) { V oldValue = this.getValue(); this.values[tree.pageIndex] = value; return oldValue; } protected void insert(final int iPosition, final K key, final V value) { if (iPosition < size) { // MOVE RIGHT TO MAKE ROOM FOR THE ITEM System.arraycopy(keys, iPosition, keys, iPosition + 1, size - iPosition); System.arraycopy(values, iPosition, values, iPosition + 1, size - iPosition); } keys[iPosition] = key; values[iPosition] = value; size++; } protected void remove() { if (tree.pageIndex == size - 1) { // LAST ONE: JUST REMOVE IT } else if (tree.pageIndex > -1) { // SHIFT LEFT THE VALUES System.arraycopy(keys, tree.pageIndex + 1, keys, tree.pageIndex, size - tree.pageIndex - 1); System.arraycopy(values, tree.pageIndex + 1, values, tree.pageIndex, size - tree.pageIndex - 1); } // FREE RESOURCES keys[size - 1] = null; values[size - 1] = null; size--; tree.pageIndex = 0; } protected void copyFrom(final OMVRBTreeEntry<K, V> iSource) { OMVRBTreeEntryMemory<K, V> source = (OMVRBTreeEntryMemory<K, V>) iSource; keys = (K[]) new Object[source.keys.length]; for (int i = 0; i < source.keys.length; ++i) keys[i] = source.keys[i]; values = (V[]) new Object[source.values.length]; for (int i = 0; i < source.values.length; ++i) values[i] = source.values[i]; size = source.size; } @Override public String toString() { if (keys == null) return "?"; final StringBuilder buffer = new StringBuilder(); final Object k = tree.pageIndex >= size ? '?' : getKey(); buffer.append(k); buffer.append(" (size="); buffer.append(size); if (size > 0) { buffer.append(" ["); buffer.append(keys[0] != null ? keys[0] : "{lazy}"); buffer.append('-'); buffer.append(keys[size - 1] != null ? keys[size - 1] : "{lazy}"); buffer.append(']'); } buffer.append(')'); return buffer.toString(); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntryMemory.java
36
public class OMVRBTreeEntryPosition<K, V> { public OMVRBTreeEntry<K, V> entry; public int position; public OMVRBTreeEntryPosition(final OMVRBTreeEntryPosition<K, V> entryPosition) { this.entry = entryPosition.entry; this.position = entryPosition.position; } public OMVRBTreeEntryPosition(final OMVRBTreeEntry<K, V> entry) { assign(entry); } public OMVRBTreeEntryPosition(final OMVRBTreeEntry<K, V> entry, final int iPosition) { assign(entry, iPosition); } public void assign(final OMVRBTreeEntry<K, V> entry, final int iPosition) { this.entry = entry; this.position = iPosition; } public void assign(final OMVRBTreeEntry<K, V> entry) { this.entry = entry; this.position = entry != null ? entry.getTree().getPageIndex() : -1; } public K getKey() { return entry != null ? entry.getKey(position) : null; } public V getValue() { return entry != null ? entry.getValue(position) : null; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeEntryPosition.java
37
@SuppressWarnings("serial") public class OMVRBTreeMemory<K, V> extends OMVRBTree<K, V> { /** * The number of entries in the tree */ protected int size = 0; protected int defaultPageSize = 63; /** * Memory based MVRB-Tree implementation. Constructs a new, empty tree map, using the natural ordering of its keys. All keys * inserted into the map must implement the {@link Comparable} interface. Furthermore, all such keys must be <i>mutually * comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> * in the map. If the user attempts to put a key into the map that violates this constraint (for example, the user attempts to put * a string key into a map whose keys are integers), the <tt>put(Object key, Object value)</tt> call will throw a * <tt>ClassCastException</tt>. */ public OMVRBTreeMemory() { runtimeCheckEnabled = false; } public OMVRBTreeMemory(final int iPageSize, final float iLoadFactor) { this(iPageSize, iLoadFactor, 1); } public OMVRBTreeMemory(final int iPageSize, final float iLoadFactor, final int keySize) { super(keySize); defaultPageSize = iPageSize; pageLoadFactor = iLoadFactor; } /** * Constructs a new, empty tree map, ordered according to the given comparator. All keys inserted into the map must be <i>mutually * comparable</i> by the given comparator: <tt>comparator.compare(k1, * k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and <tt>k2</tt> in the map. If the user attempts * to put a key into the map that violates this constraint, the <tt>put(Object * key, Object value)</tt> call will throw a <tt>ClassCastException</tt>. * * @param comparator * the comparator that will be used to order this map. If <tt>null</tt>, the {@linkplain Comparable natural ordering} of * the keys will be used. */ public OMVRBTreeMemory(final Comparator<? super K> comparator) { super(comparator); } /** * Constructs a new tree map containing the same mappings as the given map, ordered according to the <i>natural ordering</i> of * its keys. All keys inserted into the new map must implement the {@link Comparable} interface. Furthermore, all such keys must * be <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> * and <tt>k2</tt> in the map. This method runs in n*log(n) time. * * @param m * the map whose mappings are to be placed in this map * @throws ClassCastException * if the keys in m are not {@link Comparable}, or are not mutually comparable * @throws NullPointerException * if the specified map is null */ public OMVRBTreeMemory(final Map<? extends K, ? extends V> m) { super(m); } /** * Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method * runs in linear time. * * @param m * the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort this map * @throws NullPointerException * if the specified map is null */ public OMVRBTreeMemory(final SortedMap<K, ? extends V> m) { super(m); } @Override public int getTreeSize() { return size; } protected void setSize(int pSize) { size = pSize; } public int getDefaultPageSize() { return defaultPageSize; } @Override protected OMVRBTreeEntry<K, V> createEntry(final K key, final V value) { return new OMVRBTreeEntryMemory<K, V>(this, key, value, null); } @Override protected OMVRBTreeEntry<K, V> createEntry(final OMVRBTreeEntry<K, V> parent) { return new OMVRBTreeEntryMemory<K, V>((OMVRBTreeEntryMemory<K, V>) parent, parent.getPageSplitItems()); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeMemory.java
38
@Test public class OMVRBTreeNonCompositeTest { protected OMVRBTree<Double, Double> tree; @BeforeMethod public void beforeMethod() throws Exception { tree = new OMVRBTreeMemory<Double, Double>(4, 0.5f); for (double i = 1; i < 10; i++) { tree.put(i, i); } } @Test public void testGetEntry() { assertEquals(tree.get(1.0), 1.0); assertEquals(tree.get(3.0), 3.0); assertEquals(tree.get(7.0), 7.0); assertEquals(tree.get(9.0), 9.0); assertNull(tree.get(10.0)); } @Test public void testSubMapInclusive() { final ONavigableMap<Double, Double> navigableMap = tree.subMap(2.0, true, 7.0, true); assertEquals(navigableMap.size(), 6); for (double i = 2; i <= 7; i++) { assertTrue(navigableMap.containsKey(i)); } } @Test public void testSubMapFromInclusive() { final ONavigableMap<Double, Double> navigableMap = tree.subMap(2.0, true, 7.0, false); assertEquals(navigableMap.size(), 5); for (double i = 2; i < 7; i++) { assertTrue(navigableMap.containsKey(i)); } } @Test public void testSubMapToInclusive() { final ONavigableMap<Double, Double> navigableMap = tree.subMap(2.0, false, 7.0, true); assertEquals(navigableMap.size(), 5); for (double i = 3; i <= 7; i++) { assertTrue(navigableMap.containsKey(i)); } } @Test public void testSubMapNonInclusive() { final ONavigableMap<Double, Double> navigableMap = tree.subMap(2.0, false, 7.0, false); assertEquals(navigableMap.size(), 4); for (double i = 3; i < 7; i++) { assertTrue(navigableMap.containsKey(i)); } } @Test public void testTailMapInclusive() { final ONavigableMap<Double, Double> navigableMap = tree.tailMap(2.0, true); assertEquals(navigableMap.size(), 8); for (double i = 2; i <= 9; i++) { assertTrue(navigableMap.containsKey(i)); } } @Test public void testTailMapNonInclusive() { final ONavigableMap<Double, Double> navigableMap = tree.tailMap(2.0, false); assertEquals(navigableMap.size(), 7); for (double i = 3; i <= 9; i++) { assertTrue(navigableMap.containsKey(i)); } } @Test public void testHeadMapInclusive() { final ONavigableMap<Double, Double> navigableMap = tree.headMap(7.0, true); assertEquals(navigableMap.size(), 7); for (double i = 1; i <= 7; i++) { assertTrue(navigableMap.containsKey(i)); } } @Test public void testHeadMapNonInclusive() { final ONavigableMap<Double, Double> navigableMap = tree.headMap(7.0, false); assertEquals(navigableMap.size(), 6); for (double i = 1; i < 7; i++) { assertTrue(navigableMap.containsKey(i)); } } @Test public void testGetCeilingEntryKeyExist() { OMVRBTreeEntry<Double, Double> entry = tree.getCeilingEntry(4.0, OMVRBTree.PartialSearchMode.NONE); assertEquals(entry.getKey(), 4.0); entry = tree.getCeilingEntry(4.0, OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY); assertEquals(entry.getKey(), 4.0); entry = tree.getCeilingEntry(4.0, OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY); assertEquals(entry.getKey(), 4.0); } @Test public void testGetCeilingEntryKeyNotExist() { OMVRBTreeEntry<Double, Double> entry = tree.getCeilingEntry(4.3, OMVRBTree.PartialSearchMode.NONE); assertEquals(entry.getKey(), 5.0); entry = tree.getCeilingEntry(4.3, OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY); assertEquals(entry.getKey(), 5.0); entry = tree.getCeilingEntry(4.3, OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY); assertEquals(entry.getKey(), 5.0); entry = tree.getCeilingEntry(20.0, OMVRBTree.PartialSearchMode.NONE); assertNull(entry); entry = tree.getCeilingEntry(-1.0, OMVRBTree.PartialSearchMode.NONE); assertEquals(entry.getKey(), 1.0); } @Test public void testGetFloorEntryKeyExist() { OMVRBTreeEntry<Double, Double> entry = tree.getFloorEntry(4.0, OMVRBTree.PartialSearchMode.NONE); assertEquals(entry.getKey(), 4.0); entry = tree.getFloorEntry(4.0, OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY); assertEquals(entry.getKey(), 4.0); } @Test public void testGetFloorEntryKeyNotExist() { OMVRBTreeEntry<Double, Double> entry = tree.getFloorEntry(4.3, OMVRBTree.PartialSearchMode.NONE); assertEquals(entry.getKey(), 4.0); entry = tree.getFloorEntry(4.3, OMVRBTree.PartialSearchMode.HIGHEST_BOUNDARY); assertEquals(entry.getKey(), 4.0); entry = tree.getFloorEntry(4.3, OMVRBTree.PartialSearchMode.LOWEST_BOUNDARY); assertEquals(entry.getKey(), 4.0); entry = tree.getFloorEntry(20.0, OMVRBTree.PartialSearchMode.NONE); assertEquals(entry.getKey(), 9.0); entry = tree.getFloorEntry(-1.0, OMVRBTree.PartialSearchMode.NONE); assertNull(entry); } @Test public void testHigherEntryKeyExist() { OMVRBTreeEntry<Double, Double> entry = tree.getHigherEntry(4.0); assertEquals(entry.getKey(), 5.0); } @Test public void testHigherEntryKeyNotExist() { OMVRBTreeEntry<Double, Double> entry = tree.getHigherEntry(4.5); assertEquals(entry.getKey(), 5.0); } @Test public void testHigherEntryNullResult() { OMVRBTreeEntry<Double, Double> entry = tree.getHigherEntry(12.0); assertNull(entry); } @Test public void testLowerEntryNullResult() { OMVRBTreeEntry<Double, Double> entry = tree.getLowerEntry(0.0); assertNull(entry); } @Test public void testLowerEntryKeyExist() { OMVRBTreeEntry<Double, Double> entry = tree.getLowerEntry(4.0); assertEquals(entry.getKey(), 3.0); } @Test public void testLowerEntryKeyNotExist() { OMVRBTreeEntry<Double, Double> entry = tree.getLowerEntry(4.5); assertEquals(entry.getKey(), 4.0); } }
false
core_src_test_java_com_orientechnologies_common_collection_OMVRBTreeNonCompositeTest.java
39
@SuppressWarnings("unchecked") public class OMVRBTreeSet<E> extends AbstractSet<E> implements ONavigableSet<E>, Cloneable, java.io.Serializable { /** * The backing map. */ private transient ONavigableMap<E, Object> m; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); /** * Constructs a set backed by the specified navigable map. */ OMVRBTreeSet(ONavigableMap<E, Object> m) { this.m = m; } /** * Constructs a new, empty tree set, sorted according to the natural ordering of its elements. All elements inserted into the set * must implement the {@link Comparable} interface. Furthermore, all such elements must be <i>mutually comparable</i>: * {@code e1.compareTo(e2)} must not throw a {@code ClassCastException} for any elements {@code e1} and {@code e2} in the set. If * the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string * element to a set whose elements are integers), the {@code add} call will throw a {@code ClassCastException}. */ public OMVRBTreeSet() { this(new OMVRBTreeMemory<E, Object>()); } /** * Constructs a new, empty tree set, sorted according to the specified comparator. All elements inserted into the set must be * <i>mutually comparable</i> by the specified comparator: {@code comparator.compare(e1, e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and {@code e2} in the set. If the user attempts to add an element to the * set that violates this constraint, the {@code add} call will throw a {@code ClassCastException}. * * @param comparator * the comparator that will be used to order this set. If {@code null}, the {@linkplain Comparable natural ordering} of * the elements will be used. */ public OMVRBTreeSet(Comparator<? super E> comparator) { this(new OMVRBTreeMemory<E, Object>(comparator)); } /** * Constructs a new tree set containing the elements in the specified collection, sorted according to the <i>natural ordering</i> * of its elements. All elements inserted into the set must implement the {@link Comparable} interface. Furthermore, all such * elements must be <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a {@code ClassCastException} for any * elements {@code e1} and {@code e2} in the set. * * @param c * collection whose elements will comprise the new set * @throws ClassCastException * if the elements in {@code c} are not {@link Comparable}, or are not mutually comparable * @throws NullPointerException * if the specified collection is null */ public OMVRBTreeSet(Collection<? extends E> c) { this(); addAll(c); } /** * Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set. * * @param s * sorted set whose elements will comprise the new set * @throws NullPointerException * if the specified sorted set is null */ public OMVRBTreeSet(SortedSet<E> s) { this(s.comparator()); addAll(s); } /** * Returns an iterator over the elements in this set in ascending order. * * @return an iterator over the elements in this set in ascending order */ @Override public OLazyIterator<E> iterator() { return m.navigableKeySet().iterator(); } /** * Returns an iterator over the elements in this set in descending order. * * @return an iterator over the elements in this set in descending order * @since 1.6 */ public OLazyIterator<E> descendingIterator() { return m.descendingKeySet().iterator(); } /** * @since 1.6 */ public ONavigableSet<E> descendingSet() { return new OMVRBTreeSet<E>(m.descendingMap()); } /** * Returns the number of elements in this set (its cardinality). * * @return the number of elements in this set (its cardinality) */ @Override public int size() { return m.size(); } /** * Returns {@code true} if this set contains no elements. * * @return {@code true} if this set contains no elements */ @Override public boolean isEmpty() { return m.isEmpty(); } /** * Returns {@code true} if this set contains the specified element. More formally, returns {@code true} if and only if this set * contains an element {@code e} such that <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>. * * @param o * object to be checked for containment in this set * @return {@code true} if this set contains the specified element * @throws ClassCastException * if the specified object cannot be compared with the elements currently in the set * @throws NullPointerException * if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements */ @Override public boolean contains(Object o) { return m.containsKey(o); } /** * Adds the specified element to this set if it is not already present. More formally, adds the specified element {@code e} to * this set if the set contains no element {@code e2} such that <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set unchanged and returns {@code false}. * * @param e * element to be added to this set * @return {@code true} if this set did not already contain the specified element * @throws ClassCastException * if the specified object cannot be compared with the elements currently in this set * @throws NullPointerException * if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements */ @Override public boolean add(E e) { return m.put(e, PRESENT) == null; } /** * Removes the specified element from this set if it is present. More formally, removes an element {@code e} such that * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if this set contains such an element. Returns {@code true} if * this set contained the element (or equivalently, if this set changed as a result of the call). (This set will not contain the * element once the call returns.) * * @param o * object to be removed from this set, if present * @return {@code true} if this set contained the specified element * @throws ClassCastException * if the specified object cannot be compared with the elements currently in this set * @throws NullPointerException * if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements */ @Override public boolean remove(Object o) { return m.remove(o) == PRESENT; } /** * Removes all of the elements from this set. The set will be empty after this call returns. */ @Override public void clear() { m.clear(); } /** * Adds all of the elements in the specified collection to this set. * * @param c * collection containing elements to be added to this set * @return {@code true} if this set changed as a result of the call * @throws ClassCastException * if the elements provided cannot be compared with the elements currently in the set * @throws NullPointerException * if the specified collection is null or if any element is null and this set uses natural ordering, or its comparator * does not permit null elements */ @Override public boolean addAll(Collection<? extends E> c) { // Use linear-time version if applicable if (m.size() == 0 && c.size() > 0 && c instanceof SortedSet && m instanceof OMVRBTree) { SortedSet<? extends E> set = (SortedSet<? extends E>) c; OMVRBTree<E, Object> map = (OMVRBTree<E, Object>) m; Comparator<? super E> cc = (Comparator<? super E>) set.comparator(); Comparator<? super E> mc = map.comparator(); if (cc == mc || (cc != null && cc.equals(mc))) { map.addAllForOTreeSet(set, PRESENT); return true; } } return super.addAll(c); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if {@code fromElement} or {@code toElement} is null and this set uses natural ordering, or its comparator does not * permit null elements * @throws IllegalArgumentException * {@inheritDoc} * @since 1.6 */ public ONavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return new OMVRBTreeSet<E>(m.subMap(fromElement, fromInclusive, toElement, toInclusive)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if {@code toElement} is null and this set uses natural ordering, or its comparator does not permit null elements * @throws IllegalArgumentException * {@inheritDoc} * @since 1.6 */ public ONavigableSet<E> headSet(E toElement, boolean inclusive) { return new OMVRBTreeSet<E>(m.headMap(toElement, inclusive)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if {@code fromElement} is null and this set uses natural ordering, or its comparator does not permit null elements * @throws IllegalArgumentException * {@inheritDoc} * @since 1.6 */ public ONavigableSet<E> tailSet(E fromElement, boolean inclusive) { return new OMVRBTreeSet<E>(m.tailMap(fromElement, inclusive)); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if {@code fromElement} or {@code toElement} is null and this set uses natural ordering, or its comparator does not * permit null elements * @throws IllegalArgumentException * {@inheritDoc} */ public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if {@code toElement} is null and this set uses natural ordering, or its comparator does not permit null elements * @throws IllegalArgumentException * {@inheritDoc} */ public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if {@code fromElement} is null and this set uses natural ordering, or its comparator does not permit null elements * @throws IllegalArgumentException * {@inheritDoc} */ public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } public Comparator<? super E> comparator() { return m.comparator(); } /** * @throws NoSuchElementException * {@inheritDoc} */ public E first() { return m.firstKey(); } /** * @throws NoSuchElementException * {@inheritDoc} */ public E last() { return m.lastKey(); } // ONavigableSet API methods /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements * @since 1.6 */ public E lower(E e) { return m.lowerKey(e); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements * @since 1.6 */ public E floor(E e) { return m.floorKey(e); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements * @since 1.6 */ public E ceiling(E e) { return m.ceilingKey(e); } /** * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements * @since 1.6 */ public E higher(E e) { return m.higherKey(e); } /** * @since 1.6 */ public E pollFirst() { Map.Entry<E, ?> e = m.pollFirstEntry(); return (e == null) ? null : e.getKey(); } /** * @since 1.6 */ public E pollLast() { Map.Entry<E, ?> e = m.pollLastEntry(); return (e == null) ? null : e.getKey(); } /** * Returns a shallow copy of this {@code OTreeSet} instance. (The elements themselves are not cloned.) * * @return a shallow copy of this set */ @Override public Object clone() { OMVRBTreeSet<E> clone = null; try { clone = (OMVRBTreeSet<E>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } clone.m = new OMVRBTreeMemory<E, Object>(m); return clone; } /** * Save the state of the {@code OTreeSet} instance to a stream (that is, serialize it). * * @serialData Emits the comparator used to order this set, or {@code null} if it obeys its elements' natural ordering (Object), * followed by the size of the set (the number of elements it contains) (int), followed by all of its elements (each * an Object) in order (as determined by the set's Comparator, or by the elements' natural ordering if the set has no * Comparator). */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden stuff s.defaultWriteObject(); // Write out Comparator s.writeObject(m.comparator()); // Write out size s.writeInt(m.size()); // Write out all elements in the proper order. for (Iterator<E> i = m.keySet().iterator(); i.hasNext();) s.writeObject(i.next()); } /** * Reconstitute the {@code OTreeSet} instance from a stream (that is, deserialize it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in any hidden stuff s.defaultReadObject(); // Read in Comparator Comparator<? super E> c = (Comparator<? super E>) s.readObject(); // Create backing OMVRBTree OMVRBTree<E, Object> tm; if (c == null) tm = new OMVRBTreeMemory<E, Object>(); else tm = new OMVRBTreeMemory<E, Object>(c); m = tm; // Read in size int size = s.readInt(); tm.readOTreeSet(size, s, PRESENT); } private static final long serialVersionUID = -2479143000061671589L; }
false
commons_src_main_java_com_orientechnologies_common_collection_OMVRBTreeSet.java
40
public class OMultiCollectionIterator<T> implements Iterator<T>, Iterable<T>, OResettable, OSizeable { private Collection<Object> sources; private Iterator<?> iteratorOfInternalCollections; private Iterator<T> partialIterator; private int browsed = 0; private int limit = -1; private boolean embedded = false; public OMultiCollectionIterator() { sources = new ArrayList<Object>(); } public OMultiCollectionIterator(final Collection<Object> iSources) { sources = iSources; iteratorOfInternalCollections = iSources.iterator(); getNextPartial(); } public OMultiCollectionIterator(final Iterator<? extends Collection<?>> iterator) { iteratorOfInternalCollections = iterator; getNextPartial(); } @Override public boolean hasNext() { if (iteratorOfInternalCollections == null) { if (sources == null || sources.isEmpty()) return false; // THE FIRST TIME CREATE THE ITERATOR iteratorOfInternalCollections = sources.iterator(); getNextPartial(); } if (partialIterator == null) return false; if (limit > -1 && browsed >= limit) return false; if (partialIterator.hasNext()) return true; else if (iteratorOfInternalCollections.hasNext()) return getNextPartial(); return false; } @Override public T next() { if (!hasNext()) throw new NoSuchElementException(); browsed++; return partialIterator.next(); } @Override public Iterator<T> iterator() { reset(); return this; } @Override public void reset() { iteratorOfInternalCollections = null; partialIterator = null; browsed = 0; } public OMultiCollectionIterator<T> add(final Object iValue) { if (iValue != null) { if (iteratorOfInternalCollections != null) throw new IllegalStateException("MultiCollection iterator is in use and new collections cannot be added"); sources.add(iValue); } return this; } public int size() { // SUM ALL THE COLLECTION SIZES int size = 0; for (Object o : sources) { if (o != null) if (o instanceof Collection<?>) size += ((Collection<?>) o).size(); else if (o instanceof Map<?, ?>) size += ((Map<?, ?>) o).size(); else if (o instanceof OSizeable) size += ((OSizeable) o).size(); else if (o.getClass().isArray()) size += Array.getLength(o); else if (o instanceof Iterator<?> && o instanceof OResettable) { while (((Iterator<?>) o).hasNext()) { size++; ((Iterator<?>) o).next(); } ((OResettable) o).reset(); } else size++; } return size; } @Override public void remove() { throw new UnsupportedOperationException("OMultiCollectionIterator.remove()"); } public int getLimit() { return limit; } public void setLimit(final int limit) { this.limit = limit; } @SuppressWarnings("unchecked") protected boolean getNextPartial() { if (iteratorOfInternalCollections != null) while (iteratorOfInternalCollections.hasNext()) { final Object next = iteratorOfInternalCollections.next(); if (next != null) { if (next instanceof Iterator<?>) { if (next instanceof OResettable) ((OResettable) next).reset(); if (((Iterator<T>) next).hasNext()) { partialIterator = (Iterator<T>) next; return true; } } else if (next instanceof Collection<?>) { if (!((Collection<T>) next).isEmpty()) { partialIterator = ((Collection<T>) next).iterator(); return true; } } else if (next.getClass().isArray()) { final int arraySize = Array.getLength(next); if (arraySize > 0) { if (arraySize == 1) partialIterator = new OIterableObject<T>((T) Array.get(next, 0)); else partialIterator = (Iterator<T>) OMultiValue.getMultiValueIterator(next); return true; } } else { partialIterator = new OIterableObject<T>((T) next); return true; } } } return false; } public boolean isEmbedded() { return embedded; } public OMultiCollectionIterator<T> setEmbedded(final boolean embedded) { this.embedded = embedded; return this; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMultiCollectionIterator.java
41
@SuppressWarnings("unchecked") public class OMultiValue { /** * Checks if a class is a multi-value type. * * @param iType * Class to check * @return true if it's an array, a collection or a map, otherwise false */ public static boolean isMultiValue(final Class<?> iType) { return (iType.isArray() || Collection.class.isAssignableFrom(iType) || Map.class.isAssignableFrom(iType) || OMultiCollectionIterator.class .isAssignableFrom(iType)); } /** * Checks if the object is a multi-value type. * * @param iObject * Object to check * @return true if it's an array, a collection or a map, otherwise false */ public static boolean isMultiValue(final Object iObject) { return iObject == null ? false : isMultiValue(iObject.getClass()); } public static boolean isIterable(final Object iObject) { return iObject == null ? false : iObject instanceof Iterable<?> ? true : iObject instanceof Iterator<?>; } /** * Returns the size of the multi-value object * * @param iObject * Multi-value object (array, collection or map) * @return the size of the multi value object */ public static int getSize(final Object iObject) { if (iObject == null) return 0; if (iObject instanceof OSizeable) return ((OSizeable) iObject).size(); if (!isMultiValue(iObject)) return 0; if (iObject instanceof Collection<?>) return ((Collection<Object>) iObject).size(); if (iObject instanceof Map<?, ?>) return ((Map<?, Object>) iObject).size(); if (iObject.getClass().isArray()) return Array.getLength(iObject); return 0; } /** * Returns the first item of the Multi-value object (array, collection or map) * * @param iObject * Multi-value object (array, collection or map) * @return The first item if any */ public static Object getFirstValue(final Object iObject) { if (iObject == null) return null; if (!isMultiValue(iObject) || getSize(iObject) == 0) return null; try { if (iObject instanceof List<?>) return ((List<Object>) iObject).get(0); else if (iObject instanceof Collection<?>) return ((Collection<Object>) iObject).iterator().next(); else if (iObject instanceof Map<?, ?>) return ((Map<?, Object>) iObject).values().iterator().next(); else if (iObject.getClass().isArray()) return Array.get(iObject, 0); } catch (Exception e) { // IGNORE IT OLogManager.instance().debug(iObject, "Error on reading the first item of the Multi-value field '%s'", iObject); } return null; } /** * Returns the last item of the Multi-value object (array, collection or map) * * @param iObject * Multi-value object (array, collection or map) * @return The last item if any */ public static Object getLastValue(final Object iObject) { if (iObject == null) return null; if (!isMultiValue(iObject)) return null; try { if (iObject instanceof List<?>) return ((List<Object>) iObject).get(((List<Object>) iObject).size() - 1); else if (iObject instanceof Collection<?>) { Object last = null; for (Object o : (Collection<Object>) iObject) last = o; return last; } else if (iObject instanceof Map<?, ?>) { Object last = null; for (Object o : ((Map<?, Object>) iObject).values()) last = o; return last; } else if (iObject.getClass().isArray()) return Array.get(iObject, Array.getLength(iObject) - 1); } catch (Exception e) { // IGNORE IT OLogManager.instance().debug(iObject, "Error on reading the last item of the Multi-value field '%s'", iObject); } return null; } /** * Returns the iIndex item of the Multi-value object (array, collection or map) * * @param iObject * Multi-value object (array, collection or map) * @param iIndex * integer as the position requested * @return The first item if any */ public static Object getValue(final Object iObject, final int iIndex) { if (iObject == null) return null; if (!isMultiValue(iObject)) return null; if (iIndex > getSize(iObject)) return null; try { if (iObject instanceof List<?>) return ((List<?>) iObject).get(iIndex); else if (iObject instanceof Set<?>) { int i = 0; for (Object o : ((Set<?>) iObject)) { if (i++ == iIndex) { return o; } } } else if (iObject instanceof Map<?, ?>) { int i = 0; for (Object o : ((Map<?, ?>) iObject).values()) { if (i++ == iIndex) { return o; } } } else if (iObject.getClass().isArray()) return Array.get(iObject, iIndex); } catch (Exception e) { // IGNORE IT OLogManager.instance().debug(iObject, "Error on reading the first item of the Multi-value field '%s'", iObject); } return null; } /** * Returns an Iterable<Object> object to browse the multi-value instance (array, collection or map) * * @param iObject * Multi-value object (array, collection or map) */ public static Iterable<Object> getMultiValueIterable(final Object iObject) { if (iObject == null) return null; if (iObject instanceof Iterable<?>) return (Iterable<Object>) iObject; else if (iObject instanceof Collection<?>) return ((Collection<Object>) iObject); else if (iObject instanceof Map<?, ?>) return ((Map<?, Object>) iObject).values(); else if (iObject.getClass().isArray()) return new OIterableObjectArray<Object>(iObject); else if (iObject instanceof Iterator<?>) { final List<Object> temp = new ArrayList<Object>(); for (Iterator<Object> it = (Iterator<Object>) iObject; it.hasNext();) temp.add(it.next()); return temp; } return null; } /** * Returns an Iterator<Object> object to browse the multi-value instance (array, collection or map) * * @param iObject * Multi-value object (array, collection or map) */ public static Iterator<Object> getMultiValueIterator(final Object iObject) { if (iObject == null) return null; if (iObject instanceof Iterator<?>) return (Iterator<Object>) iObject; if (!isMultiValue(iObject)) return null; if (iObject instanceof Collection<?>) return ((Collection<Object>) iObject).iterator(); if (iObject instanceof Map<?, ?>) return ((Map<?, Object>) iObject).values().iterator(); if (iObject.getClass().isArray()) return new OIterableObjectArray<Object>(iObject).iterator(); return new OIterableObject<Object>(iObject); } /** * Returns a stringified version of the multi-value object. * * @param iObject * Multi-value object (array, collection or map) * @return a stringified version of the multi-value object. */ public static String toString(final Object iObject) { final StringBuilder sb = new StringBuilder(); if (iObject instanceof Collection<?>) { final Collection<Object> coll = (Collection<Object>) iObject; sb.append('['); for (final Iterator<Object> it = coll.iterator(); it.hasNext();) { try { Object e = it.next(); sb.append(e == iObject ? "(this Collection)" : e); if (it.hasNext()) sb.append(", "); } catch (NoSuchElementException ex) { // IGNORE THIS } } return sb.append(']').toString(); } else if (iObject instanceof Map<?, ?>) { final Map<String, Object> map = (Map<String, Object>) iObject; Entry<String, Object> e; sb.append('{'); for (final Iterator<Entry<String, Object>> it = map.entrySet().iterator(); it.hasNext();) { try { e = it.next(); sb.append(e.getKey()); sb.append(":"); sb.append(e.getValue() == iObject ? "(this Map)" : e.getValue()); if (it.hasNext()) sb.append(", "); } catch (NoSuchElementException ex) { // IGNORE THIS } } return sb.append('}').toString(); } return iObject.toString(); } /** * Utility function that add a value to the main object. It takes care about collections/array and single values. * * @param iObject * MultiValue where to add value(s) * @param iToAdd * Single value, array of values or collections of values. Map are not supported. * @return */ public static Object add(final Object iObject, final Object iToAdd) { if (iObject != null) { if (iObject instanceof Collection<?>) { // COLLECTION - ? final Collection<Object> coll = (Collection<Object>) iObject; if (iToAdd instanceof Collection<?>) { // COLLECTION - COLLECTION for (Object o : (Collection<Object>) iToAdd) { if (isMultiValue(o)) add(coll, o); else coll.add(o); } } else if (iToAdd != null && iToAdd.getClass().isArray()) { // ARRAY - COLLECTION for (int i = 0; i < Array.getLength(iToAdd); ++i) { Object o = Array.get(iToAdd, i); if (isMultiValue(o)) add(coll, o); else coll.add(o); } } else if (iToAdd instanceof Map<?, ?>) { // MAP for (Entry<Object, Object> entry : ((Map<Object, Object>) iToAdd).entrySet()) coll.add(entry.getValue()); } else if (iToAdd instanceof Iterable<?>) { // ITERABLE for (Object o : (Iterable<?>) iToAdd) coll.add(o); } else if (iToAdd instanceof Iterator<?>) { // ITERATOR for (Iterator<?> it = (Iterator<?>) iToAdd; it.hasNext();) coll.add(it.next()); } else coll.add(iToAdd); } else if (iObject.getClass().isArray()) { // ARRAY - ? final Object[] copy; if (iToAdd instanceof Collection<?>) { // ARRAY - COLLECTION final int tot = Array.getLength(iObject) + ((Collection<Object>) iToAdd).size(); copy = Arrays.copyOf((Object[]) iObject, tot); final Iterator<Object> it = ((Collection<Object>) iToAdd).iterator(); for (int i = Array.getLength(iObject); i < tot; ++i) copy[i] = it.next(); } else if (iToAdd != null && iToAdd.getClass().isArray()) { // ARRAY - ARRAY final int tot = Array.getLength(iObject) + Array.getLength(iToAdd); copy = Arrays.copyOf((Object[]) iObject, tot); System.arraycopy(iToAdd, 0, iObject, Array.getLength(iObject), Array.getLength(iToAdd)); } else { copy = Arrays.copyOf((Object[]) iObject, Array.getLength(iObject) + 1); copy[copy.length - 1] = iToAdd; } return copy; } else throw new IllegalArgumentException("Object " + iObject + " is not a multi value"); } return iObject; } /** * Utility function that remove a value from the main object. It takes care about collections/array and single values. * * @param iObject * MultiValue where to add value(s) * @param iToRemove * Single value, array of values or collections of values. Map are not supported. * @param iAllOccurrences * True if the all occurrences must be removed or false of only the first one (Like java.util.Collection.remove()) * @return */ public static Object remove(Object iObject, Object iToRemove, final boolean iAllOccurrences) { if (iObject != null) { if (iObject instanceof OMultiCollectionIterator<?>) { final Collection<Object> list = new LinkedList<Object>(); for (Object o : ((OMultiCollectionIterator<?>) iObject)) list.add(o); iObject = list; } if (iToRemove instanceof OMultiCollectionIterator<?>) { // TRANSFORM IN SET ONCE TO OPTIMIZE LOOPS DURING REMOVE final Set<Object> set = new HashSet<Object>(); for (Object o : ((OMultiCollectionIterator<?>) iToRemove)) set.add(o); iToRemove = set; } if (iObject instanceof Collection<?>) { // COLLECTION - ? final Collection<Object> coll = (Collection<Object>) iObject; if (iToRemove instanceof Collection<?>) { // COLLECTION - COLLECTION for (Object o : (Collection<Object>) iToRemove) { if (isMultiValue(o)) remove(coll, o, iAllOccurrences); else coll.remove(o); } } else if (iToRemove != null && iToRemove.getClass().isArray()) { // ARRAY - COLLECTION for (int i = 0; i < Array.getLength(iToRemove); ++i) { Object o = Array.get(iToRemove, i); if (isMultiValue(o)) remove(coll, o, iAllOccurrences); else coll.remove(o); } } else if (iToRemove instanceof Map<?, ?>) { // MAP for (Entry<Object, Object> entry : ((Map<Object, Object>) iToRemove).entrySet()) coll.remove(entry.getKey()); } else if (iToRemove instanceof Iterator<?>) { // ITERATOR if (iToRemove instanceof OMultiCollectionIterator<?>) ((OMultiCollectionIterator<?>) iToRemove).reset(); if (iAllOccurrences) { OMultiCollectionIterator<?> it = (OMultiCollectionIterator<?>) iToRemove; batchRemove(coll, it); } else { for (Iterator<?> it = (Iterator<?>) iToRemove; it.hasNext();) { final Object itemToRemove = it.next(); while (coll.remove(itemToRemove)) if (!iAllOccurrences) // REMOVE ONLY THE FIRST ITEM break; // REMOVE ALL THE ITEM } } } else coll.remove(iToRemove); } else if (iObject.getClass().isArray()) { // ARRAY - ? final Object[] copy; if (iToRemove instanceof Collection<?>) { // ARRAY - COLLECTION final int sourceTot = Array.getLength(iObject); final int tot = sourceTot - ((Collection<Object>) iToRemove).size(); copy = new Object[tot]; int k = 0; for (int i = 0; i < sourceTot; ++i) { Object o = Array.get(iObject, i); if (o != null) { boolean found = false; for (Object toRemove : (Collection<Object>) iToRemove) { if (o.equals(toRemove)) { // SKIP found = true; break; } } if (!found) copy[k++] = o; } } } else if (iToRemove != null && iToRemove.getClass().isArray()) { throw new UnsupportedOperationException("Cannot execute remove() against an array"); } else { throw new UnsupportedOperationException("Cannot execute remove() against an array"); } return copy; } else throw new IllegalArgumentException("Object " + iObject + " is not a multi value"); } return iObject; } private static void batchRemove(Collection<Object> coll, Iterator<?> it) { int approximateRemainingSize; if (it instanceof OSizeable) { approximateRemainingSize = ((OSizeable) it).size(); } else { approximateRemainingSize = -1; } while (it.hasNext()) { Set batch = prepareBatch(it, approximateRemainingSize); coll.removeAll(batch); approximateRemainingSize -= batch.size(); } } private static Set prepareBatch(Iterator<?> it, int approximateRemainingSize) { final HashSet batch; if (approximateRemainingSize > -1) { if (approximateRemainingSize > 10000) batch = new HashSet(13400); else batch = new HashSet((int) (approximateRemainingSize / 0.75)); } else { batch = new HashSet(); } int count = 0; while (count < 10000 && it.hasNext()) { batch.add(it.next()); count++; } return batch; } public static Object[] array(final Object iValue) { return array(iValue, Object.class); } public static <T> T[] array(final Object iValue, final Class<? extends T> iClass) { return array(iValue, iClass, null); } public static <T> T[] array(final Object iValue, final Class<? extends T> iClass, final OCallable<Object, Object> iCallback) { if (iValue == null) return null; final T[] result; if (isMultiValue(iValue)) { // CREATE STATIC ARRAY AND FILL IT result = (T[]) Array.newInstance(iClass, getSize(iValue)); int i = 0; for (Iterator<T> it = (Iterator<T>) getMultiValueIterator(iValue); it.hasNext(); ++i) result[i] = (T) convert(it.next(), iCallback); } else if (isIterable(iValue)) { // SIZE UNKNOWN: USE A LIST AS TEMPORARY OBJECT final List<T> temp = new ArrayList<T>(); for (Iterator<T> it = (Iterator<T>) getMultiValueIterator(iValue); it.hasNext();) temp.add((T) convert(it.next(), iCallback)); if (iClass.equals(Object.class)) result = (T[]) temp.toArray(); else // CONVERT THEM result = temp.toArray((T[]) Array.newInstance(iClass, getSize(iValue))); } else { result = (T[]) Array.newInstance(iClass, 1); result[0] = (T) (T) convert(iValue, iCallback); } return result; } public static Object convert(final Object iObject, final OCallable<Object, Object> iCallback) { return iCallback != null ? iCallback.call(iObject) : iObject; } public static boolean equals(final Collection<Object> col1, final Collection<Object> col2) { if (col1.size() != col2.size()) return false; return col1.containsAll(col2) && col2.containsAll(col1); } }
false
commons_src_main_java_com_orientechnologies_common_collection_OMultiValue.java
42
public interface ONavigableMap<K, V> extends SortedMap<K, V> { /** * Returns a key-value mapping associated with the greatest key strictly less than the given key, or {@code null} if there is no * such key. * * @param key * the key * @return an entry with the greatest key less than {@code key}, or {@code null} if there is no such key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map does not permit null keys */ Map.Entry<K, V> lowerEntry(K key); /** * Returns the greatest key strictly less than the given key, or {@code null} if there is no such key. * * @param key * the key * @return the greatest key less than {@code key}, or {@code null} if there is no such key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map does not permit null keys */ K lowerKey(K key); /** * Returns a key-value mapping associated with the greatest key less than or equal to the given key, or {@code null} if there is * no such key. * * @param key * the key * @return an entry with the greatest key less than or equal to {@code key}, or {@code null} if there is no such key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map does not permit null keys */ Map.Entry<K, V> floorEntry(K key); /** * Returns the greatest key less than or equal to the given key, or {@code null} if there is no such key. * * @param key * the key * @return the greatest key less than or equal to {@code key}, or {@code null} if there is no such key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map does not permit null keys */ K floorKey(K key); /** * Returns a key-value mapping associated with the least key greater than or equal to the given key, or {@code null} if there is * no such key. * * @param key * the key * @return an entry with the least key greater than or equal to {@code key}, or {@code null} if there is no such key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map does not permit null keys */ Map.Entry<K, V> ceilingEntry(K key); /** * Returns the least key greater than or equal to the given key, or {@code null} if there is no such key. * * @param key * the key * @return the least key greater than or equal to {@code key}, or {@code null} if there is no such key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map does not permit null keys */ K ceilingKey(K key); /** * Returns a key-value mapping associated with the least key strictly greater than the given key, or {@code null} if there is no * such key. * * @param key * the key * @return an entry with the least key greater than {@code key}, or {@code null} if there is no such key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map does not permit null keys */ Map.Entry<K, V> higherEntry(K key); /** * Returns the least key strictly greater than the given key, or {@code null} if there is no such key. * * @param key * the key * @return the least key greater than {@code key}, or {@code null} if there is no such key * @throws ClassCastException * if the specified key cannot be compared with the keys currently in the map * @throws NullPointerException * if the specified key is null and this map does not permit null keys */ K higherKey(K key); /** * Returns a key-value mapping associated with the least key in this map, or {@code null} if the map is empty. * * @return an entry with the least key, or {@code null} if this map is empty */ Map.Entry<K, V> firstEntry(); /** * Returns a key-value mapping associated with the greatest key in this map, or {@code null} if the map is empty. * * @return an entry with the greatest key, or {@code null} if this map is empty */ Map.Entry<K, V> lastEntry(); /** * Removes and returns a key-value mapping associated with the least key in this map, or {@code null} if the map is empty. * * @return the removed first entry of this map, or {@code null} if this map is empty */ Map.Entry<K, V> pollFirstEntry(); /** * Removes and returns a key-value mapping associated with the greatest key in this map, or {@code null} if the map is empty. * * @return the removed last entry of this map, or {@code null} if this map is empty */ Map.Entry<K, V> pollLastEntry(); /** * Returns a reverse order view of the mappings contained in this map. The descending map is backed by this map, so changes to the * map are reflected in the descending map, and vice-versa. If either map is modified while an iteration over a collection view of * either map is in progress (except through the iterator's own {@code remove} operation), the results of the iteration are * undefined. * * <p> * The returned map has an ordering equivalent to * <tt>{@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator())</tt>. The expression * {@code m.descendingMap().descendingMap()} returns a view of {@code m} essentially equivalent to {@code m}. * * @return a reverse order view of this map */ ONavigableMap<K, V> descendingMap(); /** * Returns a {@link ONavigableSet} view of the keys contained in this map. The set's iterator returns the keys in ascending order. * The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an * iteration over the set is in progress (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 Set.remove}, {@code removeAll}, {@code retainAll}, and {@code clear} operations. It does not * support the {@code add} or {@code addAll} operations. * * @return a navigable set view of the keys in this map */ ONavigableSet<K> navigableKeySet(); /** * Returns a reverse order {@link ONavigableSet} view of the keys contained in this map. The set's iterator returns the keys in * descending order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is * modified while an iteration over the set is in progress (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 Set.remove}, {@code removeAll}, {@code retainAll}, and {@code clear} operations. It * does not support the {@code add} or {@code addAll} operations. * * @return a reverse order navigable set view of the keys in this map */ ONavigableSet<K> descendingKeySet(); /** * Returns a view of the portion of this map whose keys range from {@code fromKey} to {@code toKey}. If {@code fromKey} and * {@code toKey} are equal, the returned map is empty unless {@code fromExclusive} and {@code toExclusive} are both true. The * returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map * supports all optional map operations that this map supports. * * <p> * The returned map will throw an {@code IllegalArgumentException} on an attempt to insert a key outside of its range, or to * construct a submap either of whose endpoints lie outside its range. * * @param fromKey * low endpoint of the keys in the returned map * @param fromInclusive * {@code true} if the low endpoint is to be included in the returned view * @param toKey * high endpoint of the keys in the returned map * @param toInclusive * {@code true} if the high endpoint is to be included in the returned view * @return a view of the portion of this map whose keys range from {@code fromKey} to {@code toKey} * @throws ClassCastException * if {@code fromKey} and {@code toKey} cannot be compared to one another using this map's comparator (or, if the map * has no comparator, using natural ordering). Implementations may, but are not required to, throw this exception if * {@code fromKey} or {@code toKey} cannot be compared to keys currently in the map. * @throws NullPointerException * if {@code fromKey} or {@code toKey} is null and this map does not permit null keys * @throws IllegalArgumentException * if {@code fromKey} is greater than {@code toKey}; or if this map itself has a restricted range, and {@code fromKey} * or {@code toKey} lies outside the bounds of the range */ ONavigableMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive); /** * Returns a view of the portion of this map whose keys are less than (or equal to, if {@code inclusive} is true) {@code toKey}. * The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned * map supports all optional map operations that this map supports. * * <p> * The returned map will throw an {@code IllegalArgumentException} on an attempt to insert a key outside its range. * * @param toKey * high endpoint of the keys in the returned map * @param inclusive * {@code true} if the high endpoint is to be included in the returned view * @return a view of the portion of this map whose keys are less than (or equal to, if {@code inclusive} is true) {@code toKey} * @throws ClassCastException * if {@code toKey} is not compatible with this map's comparator (or, if the map has no comparator, if {@code toKey} * does not implement {@link Comparable}). Implementations may, but are not required to, throw this exception if * {@code toKey} cannot be compared to keys currently in the map. * @throws NullPointerException * if {@code toKey} is null and this map does not permit null keys * @throws IllegalArgumentException * if this map itself has a restricted range, and {@code toKey} lies outside the bounds of the range */ ONavigableMap<K, V> headMap(K toKey, boolean inclusive); /** * Returns a view of the portion of this map whose keys are greater than (or equal to, if {@code inclusive} is true) * {@code fromKey}. The returned map is backed by this map, so changes in the returned map are reflected in this map, and * vice-versa. The returned map supports all optional map operations that this map supports. * * <p> * The returned map will throw an {@code IllegalArgumentException} on an attempt to insert a key outside its range. * * @param fromKey * low endpoint of the keys in the returned map * @param inclusive * {@code true} if the low endpoint is to be included in the returned view * @return a view of the portion of this map whose keys are greater than (or equal to, if {@code inclusive} is true) * {@code fromKey} * @throws ClassCastException * if {@code fromKey} is not compatible with this map's comparator (or, if the map has no comparator, if {@code fromKey} * does not implement {@link Comparable}). Implementations may, but are not required to, throw this exception if * {@code fromKey} cannot be compared to keys currently in the map. * @throws NullPointerException * if {@code fromKey} is null and this map does not permit null keys * @throws IllegalArgumentException * if this map itself has a restricted range, and {@code fromKey} lies outside the bounds of the range */ ONavigableMap<K, V> tailMap(K fromKey, boolean inclusive); /** * {@inheritDoc} * * <p> * Equivalent to {@code subMap(fromKey, true, toKey, false)}. * * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * {@inheritDoc} * @throws IllegalArgumentException * {@inheritDoc} */ SortedMap<K, V> subMap(K fromKey, K toKey); /** * {@inheritDoc} * * <p> * Equivalent to {@code headMap(toKey, false)}. * * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * {@inheritDoc} * @throws IllegalArgumentException * {@inheritDoc} */ SortedMap<K, V> headMap(K toKey); /** * {@inheritDoc} * * <p> * Equivalent to {@code tailMap(fromKey, true)}. * * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * {@inheritDoc} * @throws IllegalArgumentException * {@inheritDoc} */ SortedMap<K, V> tailMap(K fromKey); }
false
commons_src_main_java_com_orientechnologies_common_collection_ONavigableMap.java
43
public interface ONavigableSet<E> extends SortedSet<E> { /** * Returns the greatest element in this set strictly less than the given element, or {@code null} if there is no such element. * * @param e * the value to match * @return the greatest element less than {@code e}, or {@code null} if there is no such element * @throws ClassCastException * if the specified element cannot be compared with the elements currently in the set * @throws NullPointerException * if the specified element is null and this set does not permit null elements */ E lower(E e); /** * Returns the greatest element in this set less than or equal to the given element, or {@code null} if there is no such element. * * @param e * the value to match * @return the greatest element less than or equal to {@code e}, or {@code null} if there is no such element * @throws ClassCastException * if the specified element cannot be compared with the elements currently in the set * @throws NullPointerException * if the specified element is null and this set does not permit null elements */ E floor(E e); /** * Returns the least element in this set greater than or equal to the given element, or {@code null} if there is no such element. * * @param e * the value to match * @return the least element greater than or equal to {@code e}, or {@code null} if there is no such element * @throws ClassCastException * if the specified element cannot be compared with the elements currently in the set * @throws NullPointerException * if the specified element is null and this set does not permit null elements */ E ceiling(E e); /** * Returns the least element in this set strictly greater than the given element, or {@code null} if there is no such element. * * @param e * the value to match * @return the least element greater than {@code e}, or {@code null} if there is no such element * @throws ClassCastException * if the specified element cannot be compared with the elements currently in the set * @throws NullPointerException * if the specified element is null and this set does not permit null elements */ E higher(E e); /** * Retrieves and removes the first (lowest) element, or returns {@code null} if this set is empty. * * @return the first element, or {@code null} if this set is empty */ E pollFirst(); /** * Retrieves and removes the last (highest) element, or returns {@code null} if this set is empty. * * @return the last element, or {@code null} if this set is empty */ E pollLast(); /** * Returns an iterator over the elements in this set, in ascending order. * * @return an iterator over the elements in this set, in ascending order */ OLazyIterator<E> iterator(); /** * Returns a reverse order view of the elements contained in this set. The descending set is backed by this set, so changes to the * set are reflected in the descending set, and vice-versa. If either set is modified while an iteration over either set is in * progress (except through the iterator's own {@code remove} operation), the results of the iteration are undefined. * * <p> * The returned set has an ordering equivalent to * <tt>{@link Collections#reverseOrder(Comparator) Collections.reverseOrder}(comparator())</tt>. The expression * {@code s.descendingSet().descendingSet()} returns a view of {@code s} essentially equivalent to {@code s}. * * @return a reverse order view of this set */ ONavigableSet<E> descendingSet(); /** * Returns an iterator over the elements in this set, in descending order. Equivalent in effect to * {@code descendingSet().iterator()}. * * @return an iterator over the elements in this set, in descending order */ Iterator<E> descendingIterator(); /** * Returns a view of the portion of this set whose elements range from {@code fromElement} to {@code toElement}. If * {@code fromElement} and {@code toElement} are equal, the returned set is empty unless {@code fromExclusive} and * {@code toExclusive} are both true. The returned set is backed by this set, so changes in the returned set are reflected in this * set, and vice-versa. The returned set supports all optional set operations that this set supports. * * <p> * The returned set will throw an {@code IllegalArgumentException} on an attempt to insert an element outside its range. * * @param fromElement * low endpoint of the returned set * @param fromInclusive * {@code true} if the low endpoint is to be included in the returned view * @param toElement * high endpoint of the returned set * @param toInclusive * {@code true} if the high endpoint is to be included in the returned view * @return a view of the portion of this set whose elements range from {@code fromElement}, inclusive, to {@code toElement}, * exclusive * @throws ClassCastException * if {@code fromElement} and {@code toElement} cannot be compared to one another using this set's comparator (or, if * the set has no comparator, using natural ordering). Implementations may, but are not required to, throw this * exception if {@code fromElement} or {@code toElement} cannot be compared to elements currently in the set. * @throws NullPointerException * if {@code fromElement} or {@code toElement} is null and this set does not permit null elements * @throws IllegalArgumentException * if {@code fromElement} is greater than {@code toElement}; or if this set itself has a restricted range, and * {@code fromElement} or {@code toElement} lies outside the bounds of the range. */ ONavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive); /** * Returns a view of the portion of this set whose elements are less than (or equal to, if {@code inclusive} is true) * {@code toElement}. The returned set is backed by this set, so changes in the returned set are reflected in this set, and * vice-versa. The returned set supports all optional set operations that this set supports. * * <p> * The returned set will throw an {@code IllegalArgumentException} on an attempt to insert an element outside its range. * * @param toElement * high endpoint of the returned set * @param inclusive * {@code true} if the high endpoint is to be included in the returned view * @return a view of the portion of this set whose elements are less than (or equal to, if {@code inclusive} is true) * {@code toElement} * @throws ClassCastException * if {@code toElement} is not compatible with this set's comparator (or, if the set has no comparator, if * {@code toElement} does not implement {@link Comparable}). Implementations may, but are not required to, throw this * exception if {@code toElement} cannot be compared to elements currently in the set. * @throws NullPointerException * if {@code toElement} is null and this set does not permit null elements * @throws IllegalArgumentException * if this set itself has a restricted range, and {@code toElement} lies outside the bounds of the range */ ONavigableSet<E> headSet(E toElement, boolean inclusive); /** * Returns a view of the portion of this set whose elements are greater than (or equal to, if {@code inclusive} is true) * {@code fromElement}. The returned set is backed by this set, so changes in the returned set are reflected in this set, and * vice-versa. The returned set supports all optional set operations that this set supports. * * <p> * The returned set will throw an {@code IllegalArgumentException} on an attempt to insert an element outside its range. * * @param fromElement * low endpoint of the returned set * @param inclusive * {@code true} if the low endpoint is to be included in the returned view * @return a view of the portion of this set whose elements are greater than or equal to {@code fromElement} * @throws ClassCastException * if {@code fromElement} is not compatible with this set's comparator (or, if the set has no comparator, if * {@code fromElement} does not implement {@link Comparable}). Implementations may, but are not required to, throw this * exception if {@code fromElement} cannot be compared to elements currently in the set. * @throws NullPointerException * if {@code fromElement} is null and this set does not permit null elements * @throws IllegalArgumentException * if this set itself has a restricted range, and {@code fromElement} lies outside the bounds of the range */ ONavigableSet<E> tailSet(E fromElement, boolean inclusive); /** * {@inheritDoc} * * <p> * Equivalent to {@code subSet(fromElement, true, toElement, false)}. * * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * {@inheritDoc} * @throws IllegalArgumentException * {@inheritDoc} */ SortedSet<E> subSet(E fromElement, E toElement); /** * {@inheritDoc} * * <p> * Equivalent to {@code headSet(toElement, false)}. * * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * {@inheritDoc} * @throws IllegalArgumentException * {@inheritDoc} na */ SortedSet<E> headSet(E toElement); /** * {@inheritDoc} * * <p> * Equivalent to {@code tailSet(fromElement, true)}. * * @throws ClassCastException * {@inheritDoc} * @throws NullPointerException * {@inheritDoc} * @throws IllegalArgumentException * {@inheritDoc} */ SortedSet<E> tailSet(E fromElement); }
false
commons_src_main_java_com_orientechnologies_common_collection_ONavigableSet.java
44
public class OSimpleImmutableEntry<K, V> implements Entry<K, V>, java.io.Serializable { private static final long serialVersionUID = 7138329143949025153L; private final K key; private final V value; /** * Creates an entry representing a mapping from the specified key to the specified value. * * @param key * the key represented by this entry * @param value * the value represented by this entry */ public OSimpleImmutableEntry(final K key, final V value) { this.key = key; this.value = value; } /** * Creates an entry representing the same mapping as the specified entry. * * @param entry * the entry to copy */ public OSimpleImmutableEntry(final Entry<? extends K, ? extends V> entry) { this.key = entry.getKey(); this.value = entry.getValue(); } /** * Returns the key corresponding to this entry. * * @return the key corresponding to this entry */ public K getKey() { return key; } /** * Returns the value corresponding to this entry. * * @return the value corresponding to this entry */ public V getValue() { return value; } /** * Replaces the value corresponding to this entry with the specified value (optional operation). This implementation simply throws * <tt>UnsupportedOperationException</tt>, as this class implements an <i>immutable</i> map entry. * * @param value * new value to be stored in this entry * @return (Does not return) * @throws UnsupportedOperationException * always */ public V setValue(V value) { throw new UnsupportedOperationException(); } /** * Compares the specified object with this entry for equality. Returns {@code true} if the given object is also a map entry and * the two entries represent the same mapping. More formally, two entries {@code e1} and {@code e2} represent the same mapping if * * <pre> * (e1.getKey() == null ? e2.getKey() == null : e1.getKey().equals(e2.getKey())) * &amp;&amp; (e1.getValue() == null ? e2.getValue() == null : e1.getValue().equals(e2.getValue())) * </pre> * * This ensures that the {@code equals} method works properly across different implementations of the {@code Map.Entry} interface. * * @param o * object to be compared for equality with this map entry * @return {@code true} if the specified object is equal to this map entry * @see #hashCode */ @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?, ?> e = (Map.Entry<?, ?>) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } private boolean eq(final Object o1, final Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } /** * Returns the hash code value for this map entry. The hash code of a map entry {@code e} is defined to be: * * <pre> * (e.getKey() == null ? 0 : e.getKey().hashCode()) &circ; (e.getValue() == null ? 0 : e.getValue().hashCode()) * </pre> * * This ensures that {@code e1.equals(e2)} implies that {@code e1.hashCode()==e2.hashCode()} for any two Entries {@code e1} and * {@code e2}, as required by the general contract of {@link Object#hashCode}. * * @return the hash code value for this map entry * @see #equals */ @Override public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } /** * Returns a String representation of this map entry. This implementation returns the string representation of this entry's key * followed by the equals character ("<tt>=</tt>") followed by the string representation of this entry's value. * * @return a String representation of this map entry */ @Override public String toString() { return key + "=" + value; } }
false
commons_src_main_java_com_orientechnologies_common_collection_OSimpleImmutableEntry.java
45
public class OByteArrayComparator implements Comparator<byte[]> { public static final OByteArrayComparator INSTANCE = new OByteArrayComparator(); public int compare(final byte[] arrayOne, final byte[] arrayTwo) { final int lenDiff = arrayOne.length - arrayTwo.length; if (lenDiff != 0) return lenDiff; for (int i = 0; i < arrayOne.length; i++) { final int valOne = arrayOne[i] & 0xFF; final int valTwo = arrayTwo[i] & 0xFF; final int diff = valOne - valTwo; if (diff != 0) return diff; } return 0; } }
false
commons_src_main_java_com_orientechnologies_common_comparator_OByteArrayComparator.java
46
public class OCaseInsentiveComparator implements Comparator<String> { public int compare(final String stringOne, final String stringTwo) { return stringOne.compareToIgnoreCase(stringTwo); } }
false
commons_src_main_java_com_orientechnologies_common_comparator_OCaseInsentiveComparator.java
47
public class OComparatorFactory { public static final OComparatorFactory INSTANCE = new OComparatorFactory(); private static final boolean unsafeWasDetected; static { boolean unsafeDetected = false; try { Class<?> sunClass = Class.forName("sun.misc.Unsafe"); unsafeDetected = sunClass != null; } catch (ClassNotFoundException cnfe) { // Ignore } unsafeWasDetected = unsafeDetected; } /** * Returns {@link Comparator} instance if applicable one exist or <code>null</code> otherwise. * * @param clazz * Class of object that is going to be compared. * @param <T> * Class of object that is going to be compared. * @return {@link Comparator} instance if applicable one exist or <code>null</code> otherwise. */ @SuppressWarnings("unchecked") public <T> Comparator<T> getComparator(Class<T> clazz) { boolean useUnsafe = Boolean.valueOf(System.getProperty("memory.useUnsafe")); if (clazz.equals(byte[].class)) { if (useUnsafe && unsafeWasDetected) return (Comparator<T>) OUnsafeByteArrayComparator.INSTANCE; return (Comparator<T>) OByteArrayComparator.INSTANCE; } return null; } }
false
commons_src_main_java_com_orientechnologies_common_comparator_OComparatorFactory.java
48
public class ODefaultComparator implements Comparator<Object> { public static final ODefaultComparator INSTANCE = new ODefaultComparator(); @SuppressWarnings("unchecked") public int compare(final Object objectOne, final Object objectTwo) { if (objectOne instanceof Comparable) return ((Comparable<Object>) objectOne).compareTo(objectTwo); final Comparator<?> comparator = OComparatorFactory.INSTANCE.getComparator(objectOne.getClass()); if (comparator != null) return ((Comparator<Object>) comparator).compare(objectOne, objectTwo); throw new IllegalStateException("Object of class" + objectOne.getClass().getName() + " can not be compared"); } }
false
commons_src_main_java_com_orientechnologies_common_comparator_ODefaultComparator.java
49
@SuppressWarnings("restriction") public class OUnsafeByteArrayComparator implements Comparator<byte[]> { public static final OUnsafeByteArrayComparator INSTANCE = new OUnsafeByteArrayComparator(); private static final Unsafe unsafe; private static final int BYTE_ARRAY_OFFSET; private static final boolean littleEndian = ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN); private static final int LONG_SIZE = Long.SIZE / Byte.SIZE; static { unsafe = (Unsafe) AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return f.get(null); } catch (NoSuchFieldException e) { throw new Error(); } catch (IllegalAccessException e) { throw new Error(); } } }); BYTE_ARRAY_OFFSET = unsafe.arrayBaseOffset(byte[].class); final int byteArrayScale = unsafe.arrayIndexScale(byte[].class); if (byteArrayScale != 1) throw new Error(); } public int compare(byte[] arrayOne, byte[] arrayTwo) { if (arrayOne.length > arrayTwo.length) return 1; if (arrayOne.length < arrayTwo.length) return -1; final int WORDS = arrayOne.length / LONG_SIZE; for (int i = 0; i < WORDS * LONG_SIZE; i += LONG_SIZE) { final long index = i + BYTE_ARRAY_OFFSET; final long wOne = unsafe.getLong(arrayOne, index); final long wTwo = unsafe.getLong(arrayTwo, index); if (wOne == wTwo) continue; if (littleEndian) return lessThanUnsigned(Long.reverseBytes(wOne), Long.reverseBytes(wTwo)) ? -1 : 1; return lessThanUnsigned(wOne, wTwo) ? -1 : 1; } for (int i = WORDS * LONG_SIZE; i < arrayOne.length; i++) { int diff = compareUnsignedByte(arrayOne[i], arrayTwo[i]); if (diff != 0) return diff; } return 0; } private static boolean lessThanUnsigned(long longOne, long longTwo) { return (longOne + Long.MIN_VALUE) < (longTwo + Long.MIN_VALUE); } private static int compareUnsignedByte(byte byteOne, byte byteTwo) { final int valOne = byteOne & 0xFF; final int valTwo = byteTwo & 0xFF; return valOne - valTwo; } }
false
commons_src_main_java_com_orientechnologies_common_comparator_OUnsafeByteArrayComparator.java
50
@Test(enabled = false) public class UnsafeComparatorTest { public void testOneByteArray() { final byte[] keyOne = new byte[] { 1 }; final byte[] keyTwo = new byte[] { 2 }; Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyOne, keyTwo) < 0); Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyOne) > 0); Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyTwo) == 0); } public void testOneLongArray() { final byte[] keyOne = new byte[] { 0, 1, 0, 0, 0, 0, 0, 0 }; final byte[] keyTwo = new byte[] { 1, 0, 0, 0, 0, 0, 0, 0 }; Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyOne, keyTwo) < 0); Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyOne) > 0); Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyTwo) == 0); } public void testOneLongArrayAndByte() { final byte[] keyOne = new byte[] { 1, 1, 0, 0, 0, 0, 0, 0, 0 }; final byte[] keyTwo = new byte[] { 1, 1, 0, 0, 0, 0, 0, 0, 1 }; Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyOne, keyTwo) < 0); Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyOne) > 0); Assert.assertTrue(OUnsafeByteArrayComparator.INSTANCE.compare(keyTwo, keyTwo) == 0); } }
false
commons_src_test_java_com_orientechnologies_common_comparator_UnsafeComparatorTest.java
51
public abstract class ONeedRetryException extends OException { private static final long serialVersionUID = 1L; public ONeedRetryException() { super(); } public ONeedRetryException(String message, Throwable cause) { super(message, cause); } public ONeedRetryException(String message) { super(message); } public ONeedRetryException(Throwable cause) { super(cause); } }
false
commons_src_main_java_com_orientechnologies_common_concur_ONeedRetryException.java
52
public class OTimeoutException extends ONeedRetryException { private static final long serialVersionUID = 1L; public OTimeoutException() { super(); } public OTimeoutException(String message, Throwable cause) { super(message, cause); } public OTimeoutException(String message) { super(message); } public OTimeoutException(Throwable cause) { super(cause); } }
false
commons_src_main_java_com_orientechnologies_common_concur_OTimeoutException.java
53
public abstract class OAbstractLock implements OLock { @Override public <V> V callInLock(final Callable<V> iCallback) throws Exception { lock(); try { return iCallback.call(); } finally { unlock(); } } }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OAbstractLock.java
54
public class OAdaptiveLock extends OAbstractLock { private final ReentrantLock lock = new ReentrantLock(); private final boolean concurrent; private final int timeout; private final boolean ignoreThreadInterruption; public OAdaptiveLock() { this.concurrent = true; this.timeout = 0; this.ignoreThreadInterruption = false; } public OAdaptiveLock(final int iTimeout) { this.concurrent = true; this.timeout = iTimeout; this.ignoreThreadInterruption = false; } public OAdaptiveLock(final boolean iConcurrent) { this.concurrent = iConcurrent; this.timeout = 0; this.ignoreThreadInterruption = false; } public OAdaptiveLock(final boolean iConcurrent, final int iTimeout, boolean ignoreThreadInterruption) { this.concurrent = iConcurrent; this.timeout = iTimeout; this.ignoreThreadInterruption = ignoreThreadInterruption; } public void lock() { if (concurrent) if (timeout > 0) { try { if (lock.tryLock(timeout, TimeUnit.MILLISECONDS)) // OK return; } catch (InterruptedException e) { if (ignoreThreadInterruption) { // IGNORE THE THREAD IS INTERRUPTED: TRY TO RE-LOCK AGAIN try { if (lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { // OK, RESET THE INTERRUPTED STATE Thread.currentThread().interrupt(); return; } } catch (InterruptedException e2) { Thread.currentThread().interrupt(); } } throw new OLockException("Thread interrupted while waiting for resource of class '" + getClass() + "' with timeout=" + timeout); } throw new OTimeoutException("Timeout on acquiring lock against resource of class: " + getClass() + " with timeout=" + timeout); } else lock.lock(); } public boolean tryAcquireLock() { return tryAcquireLock(timeout, TimeUnit.MILLISECONDS); } public boolean tryAcquireLock(final long iTimeout, final TimeUnit iUnit) { if (concurrent) if (timeout > 0) try { return lock.tryLock(iTimeout, iUnit); } catch (InterruptedException e) { throw new OLockException("Thread interrupted while waiting for resource of class '" + getClass() + "' with timeout=" + timeout); } else return lock.tryLock(); return true; } public void unlock() { if (concurrent) lock.unlock(); } public boolean isConcurrent() { return concurrent; } public ReentrantLock getUnderlying() { return lock; } }
true
commons_src_main_java_com_orientechnologies_common_concur_lock_OAdaptiveLock.java
55
public class OExclusiveLock extends OAbstractLock { private final ReadWriteLock lock; public OExclusiveLock(final ReadWriteLock iLock) { lock = iLock; } public void lock() { lock.writeLock().lock(); } public void unlock() { lock.writeLock().unlock(); } }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OExclusiveLock.java
56
public interface OLock { public void lock(); public void unlock(); public <V> V callInLock(Callable<V> iCallback) throws Exception; }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OLock.java
57
public class OLockException extends OException { private static final long serialVersionUID = 2215169397325875189L; public OLockException(String iMessage) { super(iMessage); // OProfiler.getInstance().updateCounter("system.concurrency.OLockException", +1); } public OLockException(String iMessage, Exception iException) { super(iMessage, iException); // OProfiler.getInstance().updateCounter("system.concurrency.OLockException", +1); } }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OLockException.java
58
public class OLockManager<RESOURCE_TYPE, REQUESTER_TYPE> { public enum LOCK { SHARED, EXCLUSIVE } private static final int DEFAULT_CONCURRENCY_LEVEL = 16; protected long acquireTimeout; protected final ConcurrentHashMap<RESOURCE_TYPE, CountableLock> map; private final boolean enabled; private final int shift; private final int mask; private final Object[] locks; @SuppressWarnings("serial") protected static class CountableLock extends ReentrantReadWriteLock { protected int countLocks = 0; public CountableLock() { super(false); } } public OLockManager(final boolean iEnabled, final int iAcquireTimeout) { this(iEnabled, iAcquireTimeout, defaultConcurrency()); } public OLockManager(final boolean iEnabled, final int iAcquireTimeout, final int concurrencyLevel) { int cL = 1; int sh = 0; while (cL < concurrencyLevel) { cL <<= 1; sh++; } shift = 32 - sh; mask = cL - 1; map = new ConcurrentHashMap<RESOURCE_TYPE, CountableLock>(cL); locks = new Object[cL]; for (int i = 0; i < locks.length; i++) { locks[i] = new Object(); } acquireTimeout = iAcquireTimeout; enabled = iEnabled; } public void acquireLock(final REQUESTER_TYPE iRequester, final RESOURCE_TYPE iResourceId, final LOCK iLockType) { acquireLock(iRequester, iResourceId, iLockType, acquireTimeout); } public void acquireLock(final REQUESTER_TYPE iRequester, final RESOURCE_TYPE iResourceId, final LOCK iLockType, long iTimeout) { if (!enabled) return; CountableLock lock; final Object internalLock = internalLock(iResourceId); synchronized (internalLock) { lock = map.get(iResourceId); if (lock == null) { final CountableLock newLock = new CountableLock(); lock = map.putIfAbsent(getImmutableResourceId(iResourceId), newLock); if (lock == null) lock = newLock; } lock.countLocks++; } try { if (iTimeout <= 0) { if (iLockType == LOCK.SHARED) lock.readLock().lock(); else lock.writeLock().lock(); } else { try { if (iLockType == LOCK.SHARED) { if (!lock.readLock().tryLock(iTimeout, TimeUnit.MILLISECONDS)) throw new OLockException("Timeout on acquiring resource '" + iResourceId + "' because is locked from another thread"); } else { if (!lock.writeLock().tryLock(iTimeout, TimeUnit.MILLISECONDS)) throw new OLockException("Timeout on acquiring resource '" + iResourceId + "' because is locked from another thread"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new OLockException("Thread interrupted while waiting for resource '" + iResourceId + "'"); } } } catch (RuntimeException e) { synchronized (internalLock) { lock.countLocks--; if (lock.countLocks == 0) map.remove(iResourceId); } throw e; } } public boolean tryAcquireLock(final REQUESTER_TYPE iRequester, final RESOURCE_TYPE iResourceId, final LOCK iLockType) { if (!enabled) return true; CountableLock lock; final Object internalLock = internalLock(iResourceId); synchronized (internalLock) { lock = map.get(iResourceId); if (lock == null) { final CountableLock newLock = new CountableLock(); lock = map.putIfAbsent(getImmutableResourceId(iResourceId), newLock); if (lock == null) lock = newLock; } lock.countLocks++; } boolean result; try { if (iLockType == LOCK.SHARED) result = lock.readLock().tryLock(); else result = lock.writeLock().tryLock(); } catch (RuntimeException e) { synchronized (internalLock) { lock.countLocks--; if (lock.countLocks == 0) map.remove(iResourceId); } throw e; } if (!result) { synchronized (internalLock) { lock.countLocks--; if (lock.countLocks == 0) map.remove(iResourceId); } } return result; } public void releaseLock(final REQUESTER_TYPE iRequester, final RESOURCE_TYPE iResourceId, final LOCK iLockType) throws OLockException { if (!enabled) return; final CountableLock lock; final Object internalLock = internalLock(iResourceId); synchronized (internalLock) { lock = map.get(iResourceId); if (lock == null) throw new OLockException("Error on releasing a non acquired lock by the requester '" + iRequester + "' against the resource: '" + iResourceId + "'"); lock.countLocks--; if (lock.countLocks == 0) map.remove(iResourceId); } if (iLockType == LOCK.SHARED) lock.readLock().unlock(); else lock.writeLock().unlock(); } public void clear() { map.clear(); } // For tests purposes. public int getCountCurrentLocks() { return map.size(); } protected RESOURCE_TYPE getImmutableResourceId(final RESOURCE_TYPE iResourceId) { return iResourceId; } private Object internalLock(final RESOURCE_TYPE iResourceId) { final int hashCode = iResourceId.hashCode(); final int index = (hashCode >>> shift) & mask; return locks[index]; } private static int defaultConcurrency() { return Runtime.getRuntime().availableProcessors() > DEFAULT_CONCURRENCY_LEVEL ? Runtime.getRuntime().availableProcessors() : DEFAULT_CONCURRENCY_LEVEL; } }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OLockManager.java
59
@SuppressWarnings("serial") protected static class CountableLock extends ReentrantReadWriteLock { protected int countLocks = 0; public CountableLock() { super(false); } }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OLockManager.java
60
public enum LOCK { SHARED, EXCLUSIVE }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OLockManager.java
61
public class OModificationLock { private volatile boolean veto = false; private volatile boolean throwException = false; private final ConcurrentLinkedQueue<Thread> waiters = new ConcurrentLinkedQueue<Thread>(); private final ReadWriteLock lock = new ReentrantReadWriteLock(); /** * Tells the lock that thread is going to perform data modifications in storage. This method allows to perform several data * modifications in parallel. */ public void requestModificationLock() { lock.readLock().lock(); if (!veto) return; if (throwException) { lock.readLock().unlock(); throw new OModificationOperationProhibitedException("Modification requests are prohibited"); } boolean wasInterrupted = false; Thread thread = Thread.currentThread(); waiters.add(thread); while (veto) { LockSupport.park(this); if (Thread.interrupted()) wasInterrupted = true; } waiters.remove(thread); if (wasInterrupted) thread.interrupt(); } /** * Tells the lock that thread is finished to perform to perform modifications in storage. */ public void releaseModificationLock() { lock.readLock().unlock(); } /** * After this method finished it's execution, all threads that are going to perform data modifications in storage should wait till * {@link #allowModifications()} method will be called. This method will wait till all ongoing modifications will be finished. */ public void prohibitModifications() { lock.writeLock().lock(); try { throwException = false; veto = true; } finally { lock.writeLock().unlock(); } } /** * After this method finished it's execution, all threads that are going to perform data modifications in storage should wait till * {@link #allowModifications()} method will be called. This method will wait till all ongoing modifications will be finished. * * @param throwException * If <code>true</code> {@link OModificationOperationProhibitedException} exception will be thrown on * {@link #requestModificationLock()} call. */ public void prohibitModifications(boolean throwException) { lock.writeLock().lock(); try { this.throwException = throwException; veto = true; } finally { lock.writeLock().unlock(); } } /** * After this method finished execution all threads that are waiting to perform data modifications in storage will be awaken and * will be allowed to continue their execution. */ public void allowModifications() { veto = false; for (Thread thread : waiters) LockSupport.unpark(thread); } }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OModificationLock.java
62
public class OModificationOperationProhibitedException extends OException { private static final long serialVersionUID = 1L; public OModificationOperationProhibitedException() { } public OModificationOperationProhibitedException(String message) { super(message); } public OModificationOperationProhibitedException(Throwable cause) { super(cause); } public OModificationOperationProhibitedException(String message, Throwable cause) { super(message, cause); } }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OModificationOperationProhibitedException.java
63
public class ONoLock extends OAbstractLock { public void lock() { } public void unlock() { } }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_ONoLock.java
64
public class OSharedLock extends OAbstractLock { private final ReadWriteLock lock; public OSharedLock(final ReadWriteLock iLock) { lock = iLock; } public void lock() { lock.readLock().lock(); } public void unlock() { lock.readLock().unlock(); } }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OSharedLock.java
65
public class OSharedLockEntry<REQUESTER_TYPE> { /** The requester lock : generally {@link Thread} or {@link Runnable}. */ protected REQUESTER_TYPE requester; /** * Count shared locks held by this requester for the resource. * <p> * Used for reentrancy : when the same requester acquire a shared lock for the same resource in a nested code. */ protected int countSharedLocks; /** Next shared lock for the same resource by an other requester. */ protected OSharedLockEntry<REQUESTER_TYPE> nextSharedLock; protected OSharedLockEntry() { } public OSharedLockEntry(final REQUESTER_TYPE iRequester) { super(); requester = iRequester; countSharedLocks = 1; } }
false
commons_src_main_java_com_orientechnologies_common_concur_lock_OSharedLockEntry.java
66
public interface OCloseable { public void close(); }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OCloseable.java
67
public class ONotSharedResource { protected void acquireSharedLock() { } protected void releaseSharedLock() { } protected void acquireExclusiveLock() { } protected void releaseExclusiveLock() { } }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_ONotSharedResource.java
68
public class OResourcePool<K, V> { private final Semaphore sem; private final Queue<V> resources = new ConcurrentLinkedQueue<V>(); private final Collection<V> unmodifiableresources; private OResourcePoolListener<K, V> listener; public OResourcePool(final int iMaxResources, final OResourcePoolListener<K, V> iListener) { if (iMaxResources < 1) throw new IllegalArgumentException("iMaxResource must be major than 0"); listener = iListener; sem = new Semaphore(iMaxResources + 1, true); unmodifiableresources = Collections.unmodifiableCollection(resources); } public V getResource(K iKey, final long iMaxWaitMillis, Object... iAdditionalArgs) throws OLockException { // First, get permission to take or create a resource try { if (!sem.tryAcquire(iMaxWaitMillis, TimeUnit.MILLISECONDS)) throw new OLockException("Not more resources available in pool. Requested resource: " + iKey); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new OLockException("Not more resources available in pool. Requested resource: " + iKey, e); } V res; do { // POP A RESOURCE res = resources.poll(); if (res != null) { // TRY TO REUSE IT if (listener.reuseResource(iKey, iAdditionalArgs, res)) // OK: REUSE IT return res; // UNABLE TO REUSE IT: THE RESOURE WILL BE DISCARDED AND TRY WITH THE NEXT ONE, IF ANY } } while (!resources.isEmpty()); // NO AVAILABLE RESOURCES: CREATE A NEW ONE try { res = listener.createNewResource(iKey, iAdditionalArgs); return res; } catch (RuntimeException e) { sem.release(); // PROPAGATE IT throw e; } catch (Exception e) { sem.release(); throw new OLockException("Error on creation of the new resource in the pool", e); } } public void returnResource(final V res) { resources.add(res); sem.release(); } public Collection<V> getResources() { return unmodifiableresources; } public void close() { sem.drainPermits(); } public void remove(final V res) { this.resources.remove(res); } }
true
commons_src_main_java_com_orientechnologies_common_concur_resource_OResourcePool.java
69
public interface OResourcePoolListener<K, V> { /** * Creates a new resource to be used and to be pooled when the client finishes with it. * * @return The new resource */ public V createNewResource(K iKey, Object... iAdditionalArgs); /** * Reuses the pooled resource. * * @return true if can be reused, otherwise false. In this case the resource will be removed from the pool */ public boolean reuseResource(K iKey, Object[] iAdditionalArgs, V iValue); }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OResourcePoolListener.java
70
public interface OSharedContainer { public boolean existsResource(final String iName); public <T> T removeResource(final String iName); public <T> T getResource(final String iName, final Callable<T> iCallback); }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedContainer.java
71
@SuppressWarnings("unchecked") public class OSharedContainerImpl implements OSharedContainer { protected Map<String, Object> sharedResources = new HashMap<String, Object>(); public synchronized boolean existsResource(final String iName) { return sharedResources.containsKey(iName); } public synchronized <T> T removeResource(final String iName) { T resource = (T) sharedResources.remove(iName); if (resource instanceof OSharedResource) ((OSharedResource) resource).releaseExclusiveLock(); return resource; } public synchronized <T> T getResource(final String iName, final Callable<T> iCallback) { T value = (T) sharedResources.get(iName); if (value == null) { // CREATE IT try { value = iCallback.call(); } catch (Exception e) { throw new OException("Error on creation of shared resource", e); } if (value instanceof OSharedResource) ((OSharedResource) value).acquireExclusiveLock(); sharedResources.put(iName, value); } return value; } }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedContainerImpl.java
72
public interface OSharedResource { void acquireSharedLock(); void releaseSharedLock(); void acquireExclusiveLock(); void releaseExclusiveLock(); }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResource.java
73
public abstract class OSharedResourceAbstract { protected final ReadWriteLock lock = new ReentrantReadWriteLock(); protected void acquireSharedLock() { lock.readLock().lock(); } protected void releaseSharedLock() { lock.readLock().unlock(); } protected void acquireExclusiveLock() { lock.writeLock().lock(); } protected void releaseExclusiveLock() { lock.writeLock().unlock(); } }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceAbstract.java
74
public class OSharedResourceAdaptive { private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final AtomicInteger users = new AtomicInteger(0); private final boolean concurrent; private final int timeout; private final boolean ignoreThreadInterruption; protected OSharedResourceAdaptive() { this.concurrent = true; this.timeout = 0; this.ignoreThreadInterruption = false; } protected OSharedResourceAdaptive(final int iTimeout) { this.concurrent = true; this.timeout = iTimeout; this.ignoreThreadInterruption = false; } protected OSharedResourceAdaptive(final boolean iConcurrent) { this.concurrent = iConcurrent; this.timeout = 0; this.ignoreThreadInterruption = false; } protected OSharedResourceAdaptive(final boolean iConcurrent, final int iTimeout, boolean ignoreThreadInterruption) { this.concurrent = iConcurrent; this.timeout = iTimeout; this.ignoreThreadInterruption = ignoreThreadInterruption; } protected void acquireExclusiveLock() { if (concurrent) if (timeout > 0) { try { if (lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS)) // OK return; } catch (InterruptedException e) { if (ignoreThreadInterruption) { // IGNORE THE THREAD IS INTERRUPTED: TRY TO RE-LOCK AGAIN try { if (lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS)) { // OK, RESET THE INTERRUPTED STATE Thread.currentThread().interrupt(); return; } } catch (InterruptedException e2) { Thread.currentThread().interrupt(); } } throw new OLockException("Thread interrupted while waiting for resource of class '" + getClass() + "' with timeout=" + timeout); } throw new OTimeoutException("Timeout on acquiring exclusive lock against resource of class: " + getClass() + " with timeout=" + timeout); } else lock.writeLock().lock(); } protected boolean tryAcquireExclusiveLock() { return !concurrent || lock.writeLock().tryLock(); } protected void acquireSharedLock() { if (concurrent) if (timeout > 0) { try { if (lock.readLock().tryLock(timeout, TimeUnit.MILLISECONDS)) // OK return; } catch (InterruptedException e) { if (ignoreThreadInterruption) { // IGNORE THE THREAD IS INTERRUPTED: TRY TO RE-LOCK AGAIN try { if (lock.readLock().tryLock(timeout, TimeUnit.MILLISECONDS)) { // OK, RESET THE INTERRUPTED STATE Thread.currentThread().interrupt(); return; } } catch (InterruptedException e2) { Thread.currentThread().interrupt(); } } throw new OLockException("Thread interrupted while waiting for resource of class '" + getClass() + "' with timeout=" + timeout); } throw new OTimeoutException("Timeout on acquiring shared lock against resource of class : " + getClass() + " with timeout=" + timeout); } else lock.readLock().lock(); } protected boolean tryAcquireSharedLock() { return !concurrent || lock.readLock().tryLock(); } protected void releaseExclusiveLock() { if (concurrent) lock.writeLock().unlock(); } protected void releaseSharedLock() { if (concurrent) lock.readLock().unlock(); } public int getUsers() { return users.get(); } public int addUser() { return users.incrementAndGet(); } public int removeUser() { if (users.get() < 1) throw new IllegalStateException("Cannot remove user of the shared resource " + toString() + " because no user is using it"); return users.decrementAndGet(); } public boolean isConcurrent() { return concurrent; } /** To use in assert block. */ public boolean assertExclusiveLockHold() { return lock.getWriteHoldCount() > 0; } /** To use in assert block. */ public boolean assertSharedLockHold() { return lock.getReadHoldCount() > 0; } }
true
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceAdaptive.java
75
public class OSharedResourceAdaptiveExternal extends OSharedResourceAdaptive implements OSharedResource { public OSharedResourceAdaptiveExternal(final boolean iConcurrent, final int iTimeout, final boolean ignoreThreadInterruption) { super(iConcurrent, iTimeout, ignoreThreadInterruption); } @Override public void acquireExclusiveLock() { super.acquireExclusiveLock(); } public boolean tryAcquireExclusiveLock() { return super.tryAcquireExclusiveLock(); } @Override public void acquireSharedLock() { super.acquireSharedLock(); } public boolean tryAcquireSharedLock() { return super.tryAcquireSharedLock(); } @Override public void releaseExclusiveLock() { super.releaseExclusiveLock(); } @Override public void releaseSharedLock() { super.releaseSharedLock(); } }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceAdaptiveExternal.java
76
public class OSharedResourceExternal extends OSharedResourceAbstract implements OSharedResource { @Override public void acquireExclusiveLock() { super.acquireExclusiveLock(); } @Override public void acquireSharedLock() { super.acquireSharedLock(); } @Override public void releaseExclusiveLock() { super.releaseExclusiveLock(); } @Override public void releaseSharedLock() { super.releaseSharedLock(); } }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceExternal.java
77
public class OSharedResourceExternalTimeout extends OSharedResourceTimeout { public OSharedResourceExternalTimeout(final int timeout) { super(timeout); } @Override public void acquireExclusiveLock() throws OTimeoutException { super.acquireExclusiveLock(); } @Override public void acquireSharedLock() throws OTimeoutException { super.acquireSharedLock(); } @Override public void releaseExclusiveLock() { super.releaseExclusiveLock(); } @Override public void releaseSharedLock() { super.releaseSharedLock(); } }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceExternalTimeout.java
78
public class OSharedResourceIterator<T> implements Iterator<T>, OResettable { protected final OSharedResourceAdaptiveExternal resource; protected Iterator<?> iterator; public OSharedResourceIterator(final OSharedResourceAdaptiveExternal iResource, final Iterator<?> iIterator) { this.resource = iResource; this.iterator = iIterator; } @Override public boolean hasNext() { resource.acquireExclusiveLock(); try { return iterator.hasNext(); } finally { resource.releaseExclusiveLock(); } } @SuppressWarnings("unchecked") @Override public T next() { resource.acquireExclusiveLock(); try { return (T) iterator.next(); } finally { resource.releaseExclusiveLock(); } } @Override public void remove() { resource.acquireExclusiveLock(); try { iterator.remove(); } finally { resource.releaseExclusiveLock(); } } @Override public void reset() { if( !( iterator instanceof OResettable) ) return; resource.acquireExclusiveLock(); try { ((OResettable) iterator).reset(); } finally { resource.releaseExclusiveLock(); } } }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceIterator.java
79
public abstract class OSharedResourceTimeout { private final ReadWriteLock lock = new ReentrantReadWriteLock(); protected int timeout; public OSharedResourceTimeout(final int timeout) { this.timeout = timeout; } protected void acquireSharedLock() throws OTimeoutException { try { if (timeout == 0) { lock.readLock().lock(); return; } else if (lock.readLock().tryLock(timeout, TimeUnit.MILLISECONDS)) // OK return; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } throw new OTimeoutException("Timeout on acquiring shared lock against resource: " + this); } protected void releaseSharedLock() { lock.readLock().unlock(); } protected void acquireExclusiveLock() throws OTimeoutException { try { if (timeout == 0) { lock.writeLock().lock(); return; } else if (lock.writeLock().tryLock(timeout, TimeUnit.MILLISECONDS)) // OK return; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } throw new OTimeoutException("Timeout on acquiring exclusive lock against resource: " + this); } protected void releaseExclusiveLock() { lock.writeLock().unlock(); } }
false
commons_src_main_java_com_orientechnologies_common_concur_resource_OSharedResourceTimeout.java
80
public class DefaultConsoleReader implements OConsoleReader { final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public String readLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public OConsoleApplication getConsole() { return null; } public void setConsole(OConsoleApplication console) { } }
false
commons_src_main_java_com_orientechnologies_common_console_DefaultConsoleReader.java
81
public interface OCommandStream extends OCloseable { boolean hasNext(); String nextCommand(); }
false
commons_src_main_java_com_orientechnologies_common_console_OCommandStream.java
82
public class OConsoleApplication { protected enum RESULT { OK, ERROR, EXIT }; protected InputStream in = System.in; // System.in; protected PrintStream out = System.out; protected PrintStream err = System.err; protected String wordSeparator = " "; protected String[] helpCommands = { "help", "?" }; protected String[] exitCommands = { "exit", "bye", "quit" }; protected Map<String, String> properties = new HashMap<String, String>(); // protected OConsoleReader reader = new TTYConsoleReader(); protected OConsoleReader reader = new DefaultConsoleReader(); protected boolean interactiveMode; protected String[] args; protected static final String[] COMMENT_PREFIXS = new String[] { "#", "--", "//" }; public void setReader(OConsoleReader iReader) { this.reader = iReader; reader.setConsole(this); } public OConsoleApplication(String[] iArgs) { this.args = iArgs; } public int run() { interactiveMode = isInteractiveMode(args); onBefore(); int result = 0; if (interactiveMode) { // EXECUTE IN INTERACTIVE MODE // final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String consoleInput; while (true) { out.println(); out.print("orientdb> "); consoleInput = reader.readLine(); if (consoleInput == null || consoleInput.length() == 0) continue; if (!executeCommands(new ODFACommandStream(consoleInput), false)) break; } } else { // EXECUTE IN BATCH MODE result = executeBatch(getCommandLine(args)) ? 0 : 1; } onAfter(); return result; } protected boolean isInteractiveMode(String[] args) { return args.length == 0; } protected boolean executeBatch(final String commandLine) { final File commandFile = new File(commandLine); OCommandStream scanner; try { scanner = new ODFACommandStream(commandFile); } catch (FileNotFoundException e) { scanner = new ODFACommandStream(commandLine); } return executeCommands(scanner, true); } protected boolean executeCommands(final OCommandStream commandStream, final boolean iExitOnException) { final StringBuilder commandBuffer = new StringBuilder(); try { while (commandStream.hasNext()) { String commandLine = commandStream.nextCommand(); if (commandLine.isEmpty()) // EMPTY LINE continue; if (isComment(commandLine)) continue; // SCRIPT CASE: MANAGE ENSEMBLING ALL TOGETHER if (isCollectingCommands(commandLine)) { // BEGIN: START TO COLLECT commandBuffer.append(commandLine); commandLine = null; } else if (commandLine.startsWith("end") && commandBuffer.length() > 0) { // END: FLUSH IT commandLine = commandBuffer.toString(); commandBuffer.setLength(0); } else if (commandBuffer.length() > 0) { // BUFFER IT commandBuffer.append(';'); commandBuffer.append(commandLine); commandLine = null; } if (commandLine != null) { final RESULT status = execute(commandLine); commandLine = null; if (status == RESULT.EXIT || status == RESULT.ERROR && iExitOnException) return false; } } if (commandBuffer.length() > 0) { final RESULT status = execute(commandBuffer.toString()); if (status == RESULT.EXIT || status == RESULT.ERROR && iExitOnException) return false; } } finally { commandStream.close(); } return true; } protected boolean isComment(final String commandLine) { for (String comment : COMMENT_PREFIXS) if (commandLine.startsWith(comment)) return true; return false; } protected boolean isCollectingCommands(final String iLine) { return false; } protected RESULT execute(String iCommand) { iCommand = iCommand.trim(); if (iCommand.length() == 0) // NULL LINE: JUMP IT return RESULT.OK; if (isComment(iCommand)) // COMMENT: JUMP IT return RESULT.OK; String[] commandWords = OStringParser.getWords(iCommand, wordSeparator); for (String cmd : helpCommands) if (cmd.equals(commandWords[0])) { help(); return RESULT.OK; } for (String cmd : exitCommands) if (cmd.equals(commandWords[0])) { return RESULT.EXIT; } Method lastMethodInvoked = null; final StringBuilder lastCommandInvoked = new StringBuilder(); final String commandLowerCase = iCommand.toLowerCase(); for (Entry<Method, Object> entry : getConsoleMethods().entrySet()) { final Method m = entry.getKey(); final String methodName = m.getName(); final ConsoleCommand ann = m.getAnnotation(ConsoleCommand.class); final StringBuilder commandName = new StringBuilder(); char ch; int commandWordCount = 1; for (int i = 0; i < methodName.length(); ++i) { ch = methodName.charAt(i); if (Character.isUpperCase(ch)) { commandName.append(" "); ch = Character.toLowerCase(ch); commandWordCount++; } commandName.append(ch); } if (!commandLowerCase.equals(commandName.toString()) && !commandLowerCase.startsWith(commandName.toString() + " ")) { if (ann == null) continue; String[] aliases = ann.aliases(); if (aliases == null || aliases.length == 0) continue; boolean aliasMatch = false; for (String alias : aliases) { if (iCommand.startsWith(alias.split(" ")[0])) { aliasMatch = true; commandWordCount = 1; break; } } if (!aliasMatch) continue; } Object[] methodArgs; // BUILD PARAMETERS if (ann != null && !ann.splitInWords()) { methodArgs = new String[] { iCommand.substring(iCommand.indexOf(' ') + 1) }; } else { if (m.getParameterTypes().length > commandWords.length - commandWordCount) { // METHOD PARAMS AND USED PARAMS MISMATCH: CHECK FOR OPTIONALS for (int paramNum = m.getParameterAnnotations().length - 1; paramNum > -1; paramNum--) { final Annotation[] paramAnn = m.getParameterAnnotations()[paramNum]; if (paramAnn != null) for (int annNum = paramAnn.length - 1; annNum > -1; annNum--) { if (paramAnn[annNum] instanceof ConsoleParameter) { final ConsoleParameter annotation = (ConsoleParameter) paramAnn[annNum]; if (annotation.optional()) commandWords = OArrays.copyOf(commandWords, commandWords.length + 1); break; } } } } methodArgs = OArrays.copyOfRange(commandWords, commandWordCount, commandWords.length); } try { m.invoke(entry.getValue(), methodArgs); } catch (IllegalArgumentException e) { lastMethodInvoked = m; // GET THE COMMAND NAME lastCommandInvoked.setLength(0); for (int i = 0; i < commandWordCount; ++i) { if (lastCommandInvoked.length() > 0) lastCommandInvoked.append(" "); lastCommandInvoked.append(commandWords[i]); } continue; } catch (Exception e) { // e.printStackTrace(); // err.println(); if (e.getCause() != null) onException(e.getCause()); else e.printStackTrace(); return RESULT.ERROR; } return RESULT.OK; } if (lastMethodInvoked != null) syntaxError(lastCommandInvoked.toString(), lastMethodInvoked); error("\n!Unrecognized command: '%s'", iCommand); return RESULT.ERROR; } protected void syntaxError(String iCommand, Method m) { error( "\n!Wrong syntax. If you're using a file make sure all commands are delimited by semicolon (;) or a linefeed (\\n)\n\r\n\r Expected: %s ", iCommand); String paramName = null; String paramDescription = null; boolean paramOptional = false; StringBuilder buffer = new StringBuilder("\n\nWhere:\n\n"); for (Annotation[] annotations : m.getParameterAnnotations()) { for (Annotation ann : annotations) { if (ann instanceof com.orientechnologies.common.console.annotation.ConsoleParameter) { paramName = ((com.orientechnologies.common.console.annotation.ConsoleParameter) ann).name(); paramDescription = ((com.orientechnologies.common.console.annotation.ConsoleParameter) ann).description(); paramOptional = ((com.orientechnologies.common.console.annotation.ConsoleParameter) ann).optional(); break; } } if (paramName == null) paramName = "?"; if (paramOptional) message("[<%s>] ", paramName); else message("<%s> ", paramName); buffer.append("* "); buffer.append(String.format("%-15s", paramName)); if (paramDescription != null) buffer.append(String.format("%-15s", paramDescription)); buffer.append("\n"); } message(buffer.toString()); } /** * Returns a map of all console method and the object they can be called on. * * @return Map&lt;Method,Object&gt; */ protected Map<Method, Object> getConsoleMethods() { // search for declared command collections final Iterator<OConsoleCommandCollection> ite = ServiceRegistry.lookupProviders(OConsoleCommandCollection.class); final Collection<Object> candidates = new ArrayList<Object>(); candidates.add(this); while (ite.hasNext()) { try { // make a copy and set it's context final OConsoleCommandCollection cc = ite.next().getClass().newInstance(); cc.setContext(this); candidates.add(cc); } catch (InstantiationException ex) { Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage()); } catch (IllegalAccessException ex) { Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage()); } } final Map<Method, Object> consoleMethods = new TreeMap<Method, Object>(new Comparator<Method>() { public int compare(Method o1, Method o2) { int res = o1.getName().compareTo(o2.getName()); if (res == 0) res = o1.toString().compareTo(o2.toString()); return res; } }); for (final Object candidate : candidates) { final Method[] methods = candidate.getClass().getMethods(); for (Method m : methods) { if (Modifier.isAbstract(m.getModifiers()) || Modifier.isStatic(m.getModifiers()) || !Modifier.isPublic(m.getModifiers())) { continue; } if (m.getReturnType() != Void.TYPE) { continue; } consoleMethods.put(m, candidate); } } return consoleMethods; } protected Map<String, Object> addCommand(Map<String, Object> commandsTree, String commandLine) { return commandsTree; } protected void help() { message("\nAVAILABLE COMMANDS:\n"); for (Method m : getConsoleMethods().keySet()) { com.orientechnologies.common.console.annotation.ConsoleCommand annotation = m .getAnnotation(com.orientechnologies.common.console.annotation.ConsoleCommand.class); if (annotation == null) continue; message("* %-70s%s\n", getCorrectMethodName(m), annotation.description()); } message("* %-70s%s\n", getClearName("help"), "Print this help"); message("* %-70s%s\n", getClearName("exit"), "Close the console"); } public static String getCorrectMethodName(Method m) { StringBuilder buffer = new StringBuilder(); buffer.append(getClearName(m.getName())); for (int i = 0; i < m.getParameterAnnotations().length; i++) { for (int j = 0; j < m.getParameterAnnotations()[i].length; j++) { if (m.getParameterAnnotations()[i][j] instanceof com.orientechnologies.common.console.annotation.ConsoleParameter) { buffer .append(" <" + ((com.orientechnologies.common.console.annotation.ConsoleParameter) m.getParameterAnnotations()[i][j]).name() + ">"); } } } return buffer.toString(); } public static String getClearName(String iJavaName) { StringBuilder buffer = new StringBuilder(); char c; if (iJavaName != null) { buffer.append(iJavaName.charAt(0)); for (int i = 1; i < iJavaName.length(); ++i) { c = iJavaName.charAt(i); if (Character.isUpperCase(c)) { buffer.append(' '); } buffer.append(Character.toLowerCase(c)); } } return buffer.toString(); } protected String getCommandLine(String[] iArguments) { StringBuilder command = new StringBuilder(); for (int i = 0; i < iArguments.length; ++i) { if (i > 0) command.append(" "); command.append(iArguments[i]); } return command.toString(); } protected void onBefore() { } protected void onAfter() { } protected void onException(Throwable throwable) { throwable.printStackTrace(); } public void message(final String iMessage, final Object... iArgs) { final int verboseLevel = getVerboseLevel(); if (verboseLevel > 1) out.printf(iMessage, iArgs); } public void error(final String iMessage, final Object... iArgs) { final int verboseLevel = getVerboseLevel(); if (verboseLevel > 0) out.printf(iMessage, iArgs); } public int getVerboseLevel() { final String v = properties.get("verbose"); final int verboseLevel = v != null ? Integer.parseInt(v) : 2; return verboseLevel; } }
false
commons_src_main_java_com_orientechnologies_common_console_OConsoleApplication.java
83
final Map<Method, Object> consoleMethods = new TreeMap<Method, Object>(new Comparator<Method>() { public int compare(Method o1, Method o2) { int res = o1.getName().compareTo(o2.getName()); if (res == 0) res = o1.toString().compareTo(o2.toString()); return res; } });
false
commons_src_main_java_com_orientechnologies_common_console_OConsoleApplication.java
84
protected enum RESULT { OK, ERROR, EXIT };
false
commons_src_main_java_com_orientechnologies_common_console_OConsoleApplication.java
85
public abstract class OConsoleCommandCollection { protected OConsoleApplication context; void setContext(OConsoleApplication context){ this.context = context; } }
false
commons_src_main_java_com_orientechnologies_common_console_OConsoleCommandCollection.java
86
public interface OConsoleReader { public String readLine(); public void setConsole(OConsoleApplication console); public OConsoleApplication getConsole(); }
false
commons_src_main_java_com_orientechnologies_common_console_OConsoleReader.java
87
public class ODFACommandStream implements OCommandStream { public static final int BUFFER_SIZE = 1024; private Reader reader; private CharBuffer buffer; private final Set<Character> separators = new HashSet<Character>(Arrays.asList(';', '\n')); private int position; private int start; private int end; private StringBuilder partialResult; private State state; public ODFACommandStream(String commands) { reader = new StringReader(commands); init(); } public ODFACommandStream(File file) throws FileNotFoundException { reader = new BufferedReader(new FileReader(file)); init(); } private void init() { buffer = CharBuffer.allocate(BUFFER_SIZE); buffer.flip(); } @Override public boolean hasNext() { try { fillBuffer(); return buffer.hasRemaining(); } catch (IOException e) { throw new RuntimeException(e); } } private void fillBuffer() throws IOException { if (!buffer.hasRemaining()) { buffer.clear(); reader.read(buffer); buffer.flip(); } } @Override public String nextCommand() { try { fillBuffer(); partialResult = new StringBuilder(); state = State.S; start = 0; end = -1; position = 0; Symbol s = null; while (state != State.E) { s = nextSymbol(); final State newState = transition(state, s); if (state == State.S && newState != State.S) start = position; if (newState == State.A) end = position; if (newState == State.F) throw new IllegalStateException("Unexpected end of file"); state = newState; position++; } if (s == Symbol.EOF) { position--; if (end == -1) { start = 0; end = 0; } } final String result; if (partialResult.length() > 0) { if (end > 0) { result = partialResult.append(buffer.subSequence(start, end + 1).toString()).toString(); } else { partialResult.setLength(partialResult.length() + end + 1); result = partialResult.toString(); } } else { result = buffer.subSequence(start, end + 1).toString(); } buffer.position(buffer.position() + position); return result; } catch (IOException e) { throw new RuntimeException(e); } } private Symbol nextSymbol() throws IOException { Symbol s; if (buffer.position() + position < buffer.limit()) { s = symbol(buffer.charAt(position)); } else { buffer.compact(); int read = reader.read(buffer); buffer.flip(); if (read == 0) { // There is something in source, but buffer is full if (state != State.S) partialResult.append(buffer.subSequence(start, position).toString()); start = 0; end = end - position; buffer.clear(); read = reader.read(buffer); buffer.flip(); position = 0; } if (read == -1) { s = Symbol.EOF; } else { s = symbol(buffer.charAt(position)); } } return s; } private State transition(State s, Symbol c) { switch (s) { case S: switch (c) { case LATTER: return State.A; case WS: return State.S; case AP: return State.B; case QT: return State.C; case SEP: return State.S; case EOF: return State.E; } break; case A: case D: switch (c) { case LATTER: return State.A; case WS: return State.D; case AP: return State.B; case QT: return State.C; case SEP: return State.E; case EOF: return State.E; } break; case B: switch (c) { case LATTER: return State.B; case WS: return State.B; case AP: return State.A; case QT: return State.B; case SEP: return State.B; case EOF: return State.F; } break; case C: switch (c) { case LATTER: return State.C; case WS: return State.C; case AP: return State.C; case QT: return State.A; case SEP: return State.C; case EOF: return State.F; } break; case E: return State.E; case F: return State.F; } throw new IllegalStateException(); } @Override public void close() { try { reader.close(); } catch (IOException e) { throw new RuntimeException(e); } } public Symbol symbol(Character c) { if (c.equals('\'')) return Symbol.AP; if (c.equals('"')) return Symbol.QT; if (separators.contains(c)) return Symbol.SEP; if (Character.isWhitespace(c)) return Symbol.WS; return Symbol.LATTER; } private enum State { S, A, B, C, D, E, F } private enum Symbol { LATTER, WS, QT, AP, SEP, EOF } }
true
commons_src_main_java_com_orientechnologies_common_console_ODFACommandStream.java
88
private enum State { S, A, B, C, D, E, F }
false
commons_src_main_java_com_orientechnologies_common_console_ODFACommandStream.java
89
private enum Symbol { LATTER, WS, QT, AP, SEP, EOF }
false
commons_src_main_java_com_orientechnologies_common_console_ODFACommandStream.java
90
public class ODFACommandStreamTest { @Test public void testNextCommand() throws Exception { test("one;two", "one", "two"); } @Test public void testNextCommandQuotes() throws Exception { test("Select 'one;'; Select \"t;w;o\"", "Select 'one;'", "Select \"t;w;o\""); } @Test public void testNextCommandSeparatorAtTheEnd() throws Exception { test("one;two;", "one", "two"); } @Test public void testNextCommandWhitespaces() throws Exception { test("\tone ; two ", "one", "two"); } private void test(String source, String... expectedResults) { final ODFACommandStream stream = new ODFACommandStream(source); for (String expectedResult : expectedResults) { Assert.assertTrue(stream.hasNext()); String result = stream.nextCommand(); Assert.assertEquals(result, expectedResult); } Assert.assertFalse(stream.hasNext()); } }
false
commons_src_test_java_com_orientechnologies_common_console_ODFACommandStreamTest.java
91
public class OScannerCommandStream implements OCommandStream { private Scanner scanner; public OScannerCommandStream(String commands) { scanner = new Scanner(commands); init(); } public OScannerCommandStream(File file) throws FileNotFoundException { scanner = new Scanner(file); init(); } private void init() { scanner.useDelimiter(";(?=([^\"]*\"[^\"]*\")*[^\"]*$)(?=([^']*'[^']*')*[^']*$)|\n"); } @Override public boolean hasNext() { return scanner.hasNext(); } @Override public String nextCommand() { return scanner.next().trim(); } @Override public void close() { scanner.close(); } }
false
commons_src_main_java_com_orientechnologies_common_console_OScannerCommandStream.java
92
public class TTYConsoleReader implements OConsoleReader { private static final String HISTORY_FILE_NAME = ".orientdb_history"; private static int MAX_HISTORY_ENTRIES = 50; public static int END_CHAR = 70; public static int BEGIN_CHAR = 72; public static int DEL_CHAR = 126; public static int DOWN_CHAR = 66; public static int UP_CHAR = 65; public static int RIGHT_CHAR = 67; public static int LEFT_CHAR = 68; public static int HORIZONTAL_TAB_CHAR = 9; public static int VERTICAL_TAB_CHAR = 11; public static int BACKSPACE_CHAR = 127; public static int NEW_LINE_CHAR = 10; public static int UNIT_SEPARATOR_CHAR = 31; protected int currentPos = 0; protected List<String> history = new ArrayList<String>(); protected String historyBuffer; protected Reader inStream; protected PrintStream outStream; public TTYConsoleReader() { File file = getHistoryFile(true); BufferedReader reader; try { reader = new BufferedReader(new FileReader(file)); String historyEntry = reader.readLine(); while (historyEntry != null) { history.add(historyEntry); historyEntry = reader.readLine(); } if (System.getProperty("file.encoding") != null) { inStream = new InputStreamReader(System.in, System.getProperty("file.encoding")); outStream = new PrintStream(System.out, false, System.getProperty("file.encoding")); } else { inStream = new InputStreamReader(System.in); outStream = System.out; } } catch (FileNotFoundException fnfe) { OLogManager.instance().error(this, "History file not found", fnfe, ""); } catch (IOException ioe) { OLogManager.instance().error(this, "Error reading history file.", ioe, ""); } } protected OConsoleApplication console; public String readLine() { String consoleInput = ""; try { StringBuffer buffer = new StringBuffer(); currentPos = 0; historyBuffer = null; int historyNum = history.size(); boolean hintedHistory = false; while (true) { boolean escape = false; boolean ctrl = false; int next = inStream.read(); if (next == 27) { escape = true; inStream.read(); next = inStream.read(); } if (escape) { if (next == 49) { inStream.read(); next = inStream.read(); } if (next == 53) { ctrl = true; next = inStream.read(); } if (ctrl) { if (next == RIGHT_CHAR) { currentPos = buffer.indexOf(" ", currentPos) + 1; if (currentPos == 0) currentPos = buffer.length(); StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } rewriteConsole(cleaner, true); rewriteConsole(buffer, false); } else if (next == LEFT_CHAR) { if (currentPos > 1 && currentPos < buffer.length() && buffer.charAt(currentPos - 1) == ' ') { currentPos = buffer.lastIndexOf(" ", (currentPos - 2)) + 1; } else { currentPos = buffer.lastIndexOf(" ", currentPos) + 1; } if (currentPos < 0) currentPos = 0; StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } rewriteConsole(cleaner, true); rewriteConsole(buffer, false); } else { } } else { if (next == UP_CHAR && !history.isEmpty()) { if (history.size() > 0) { // UP StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } rewriteConsole(cleaner, true); if (!hintedHistory && (historyNum == history.size() || !buffer.toString().equals(history.get(historyNum)))) { if (buffer.length() > 0) { hintedHistory = true; historyBuffer = buffer.toString(); } else { historyBuffer = null; } } historyNum = getHintedHistoryIndexUp(historyNum); if (historyNum > -1) { buffer = new StringBuffer(history.get(historyNum)); } else { buffer = new StringBuffer(historyBuffer); } currentPos = buffer.length(); rewriteConsole(buffer, false); // writeHistory(historyNum); } } else if (next == DOWN_CHAR && !history.isEmpty()) { // DOWN if (history.size() > 0) { StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } rewriteConsole(cleaner, true); historyNum = getHintedHistoryIndexDown(historyNum); if (historyNum == history.size()) { if (historyBuffer != null) { buffer = new StringBuffer(historyBuffer); } else { buffer = new StringBuffer(""); } } else { buffer = new StringBuffer(history.get(historyNum)); } currentPos = buffer.length(); rewriteConsole(buffer, false); // writeHistory(historyNum); } } else if (next == RIGHT_CHAR) { if (currentPos < buffer.length()) { currentPos++; StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } rewriteConsole(cleaner, true); rewriteConsole(buffer, false); } } else if (next == LEFT_CHAR) { if (currentPos > 0) { currentPos--; StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } rewriteConsole(cleaner, true); rewriteConsole(buffer, false); } } else if (next == END_CHAR) { currentPos = buffer.length(); StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } rewriteConsole(cleaner, true); rewriteConsole(buffer, false); } else if (next == BEGIN_CHAR) { currentPos = 0; StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } rewriteConsole(cleaner, true); rewriteConsole(buffer, false); } else { } } } else { if (next == NEW_LINE_CHAR) { outStream.println(); break; } else if (next == BACKSPACE_CHAR) { if (buffer.length() > 0 && currentPos > 0) { StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } buffer.deleteCharAt(currentPos - 1); currentPos--; rewriteConsole(cleaner, true); rewriteConsole(buffer, false); } } else if (next == DEL_CHAR) { if (buffer.length() > 0 && currentPos >= 0 && currentPos < buffer.length()) { StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } buffer.deleteCharAt(currentPos); rewriteConsole(cleaner, true); rewriteConsole(buffer, false); } } else if (next == HORIZONTAL_TAB_CHAR) { StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } buffer = writeHint(buffer); rewriteConsole(cleaner, true); rewriteConsole(buffer, false); currentPos = buffer.length(); } else { if ((next > UNIT_SEPARATOR_CHAR && next < BACKSPACE_CHAR) || next > BACKSPACE_CHAR) { StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" "); } if (currentPos == buffer.length()) { buffer.append((char) next); } else { buffer.insert(currentPos, (char) next); } currentPos++; rewriteConsole(cleaner, true); rewriteConsole(buffer, false); } else { outStream.println(); outStream.print(buffer); } } historyNum = history.size(); hintedHistory = false; } } consoleInput = buffer.toString(); history.remove(consoleInput); history.add(consoleInput); historyNum = history.size(); writeHistory(historyNum); } catch (IOException e) { return null; } if (consoleInput.equals("clear")) { outStream.flush(); for (int i = 0; i < 150; i++) { outStream.println(); } outStream.print("\r"); outStream.print("orientdb> "); return readLine(); } else { return consoleInput; } } private void writeHistory(int historyNum) throws IOException { if (historyNum <= MAX_HISTORY_ENTRIES) { File historyFile = getHistoryFile(false); BufferedWriter writer = new BufferedWriter(new FileWriter(historyFile)); try { for (String historyEntry : history) { writer.write(historyEntry); writer.newLine(); } } finally { writer.flush(); writer.close(); } } else { File historyFile = getHistoryFile(false); BufferedWriter writer = new BufferedWriter(new FileWriter(historyFile)); try { for (String historyEntry : history.subList(historyNum - MAX_HISTORY_ENTRIES - 1, historyNum - 1)) { writer.write(historyEntry); writer.newLine(); } } finally { writer.flush(); writer.close(); } } } private StringBuffer writeHint(StringBuffer buffer) { List<String> suggestions = new ArrayList<String>(); for (Method method : console.getConsoleMethods().keySet()) { String command = OConsoleApplication.getClearName(method.getName()); if (command.startsWith(buffer.toString())) { suggestions.add(command); } } if (suggestions.size() > 1) { StringBuffer hintBuffer = new StringBuffer(); String[] bufferComponents = buffer.toString().split(" "); String[] suggestionComponents; Set<String> bufferPart = new HashSet<String>(); String suggestionPart = null; boolean appendSpace = true; for (String suggestion : suggestions) { suggestionComponents = suggestion.split(" "); hintBuffer.append("* " + suggestion + " "); hintBuffer.append("\n"); suggestionPart = ""; if (bufferComponents.length == 0 || buffer.length() == 0) { suggestionPart = null; } else if (bufferComponents.length == 1) { bufferPart.add(suggestionComponents[0]); if (bufferPart.size() > 1) { suggestionPart = bufferComponents[0]; appendSpace = false; } else { suggestionPart = suggestionComponents[0]; } } else { bufferPart.add(suggestionComponents[bufferComponents.length - 1]); if (bufferPart.size() > 1) { for (int i = 0; i < bufferComponents.length; i++) { suggestionPart += bufferComponents[i]; if (i < (bufferComponents.length - 1)) { suggestionPart += " "; } appendSpace = false; } } else { for (int i = 0; i < suggestionComponents.length; i++) { suggestionPart += suggestionComponents[i] + " "; } } } } if (suggestionPart != null) { buffer = new StringBuffer(); buffer.append(suggestionPart); if (appendSpace) { buffer.append(" "); } } hintBuffer.append("-----------------------------\n"); rewriteHintConsole(hintBuffer); } else if (suggestions.size() > 0) { buffer = new StringBuffer(); buffer.append(suggestions.get(0)); buffer.append(" "); } return buffer; } public void setConsole(OConsoleApplication iConsole) { console = iConsole; } public OConsoleApplication getConsole() { return console; } private void rewriteConsole(StringBuffer buffer, boolean cleaner) { outStream.print("\r"); outStream.print("orientdb> "); if (currentPos < buffer.length() && buffer.length() > 0 && !cleaner) { outStream.print("\033[0m" + buffer.substring(0, currentPos) + "\033[0;30;47m" + buffer.substring(currentPos, currentPos + 1) + "\033[0m" + buffer.substring(currentPos + 1) + "\033[0m"); } else { outStream.print(buffer); } } private void rewriteHintConsole(StringBuffer buffer) { outStream.print("\r"); outStream.print(buffer); } private int getHintedHistoryIndexUp(int historyNum) { if (historyBuffer != null && !historyBuffer.equals("")) { for (int i = (historyNum - 1); i >= 0; i--) { if (history.get(i).startsWith(historyBuffer)) { return i; } } return -1; } return historyNum > 0 ? (historyNum - 1) : 0; } private int getHintedHistoryIndexDown(int historyNum) throws IOException { if (historyBuffer != null && !historyBuffer.equals("")) { for (int i = historyNum + 1; i < history.size(); i++) { if (history.get(i).startsWith(historyBuffer)) { return i; } } return history.size(); } return historyNum < history.size() ? (historyNum + 1) : history.size(); } private File getHistoryFile(boolean read) { File file = new File(HISTORY_FILE_NAME); if (!file.exists()) { try { file.createNewFile(); } catch (IOException ioe) { OLogManager.instance().error(this, "Error creating history file.", ioe, ""); } } else if (!read) { file.delete(); try { file.createNewFile(); } catch (IOException ioe) { OLogManager.instance().error(this, "Error creating history file.", ioe, ""); } } return file; } }
false
commons_src_main_java_com_orientechnologies_common_console_TTYConsoleReader.java
93
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ConsoleCommand { String[] aliases() default {}; String description() default ""; boolean splitInWords() default true; }
false
commons_src_main_java_com_orientechnologies_common_console_annotation_ConsoleCommand.java
94
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface ConsoleParameter { String name() default ""; String description() default ""; boolean optional() default false; }
false
commons_src_main_java_com_orientechnologies_common_console_annotation_ConsoleParameter.java
95
public interface ODirectMemory { /** * Presentation of null pointer in given memory model. */ public long NULL_POINTER = 0; /** * Allocates amount of memory that is needed to write passed in byte array and writes it. * * @param bytes * Data that is needed to be written. * @return Pointer to the allocated piece of memory. */ long allocate(byte[] bytes); /** * Allocates given amount of memory (in bytes) from pool and returns pointer on allocated memory or {@link #NULL_POINTER} if there * is no enough memory in pool. * * @param size * Size that is needed to be allocated. * @return Pointer to the allocated memory. */ long allocate(long size); /** * Returns allocated memory back to the pool. * * @param pointer * Pointer to the allocated piece of memory. */ void free(long pointer); /** * Reads raw data from given piece of memory. * * * @param pointer * Memory pointer, returned by {@link #allocate(long)} method. * @param length * Size of data which should be returned. * @return Raw data from given piece of memory. */ byte[] get(long pointer, int length); void get(long pointer, byte[] array, int arrayOffset, int length); /** * Writes data to the given piece of memory. * * @param pointer * Memory pointer, returned by {@link #allocate(long)} method. * @param content * @param arrayOffset * @param length */ void set(long pointer, byte[] content, int arrayOffset, int length); /** * Return <code>int</code> value from given piece of memory. * * * @param pointer * Memory pointer, returned by {@link #allocate(long)} method. * @return Int value. */ int getInt(long pointer); /** * Write <code>int</code> value to given piece of memory. * * @param pointer * Memory pointer, returned by {@link #allocate(long)} method. * */ void setInt(long pointer, int value); void setShort(long pointer, short value); short getShort(long pointer); /** * Return <code>long</code> value from given piece of memory. * * * @param pointer * Memory pointer, returned by {@link #allocate(long)} method. * @return long value. */ long getLong(long pointer); /** * Write <code>long</code> value to given piece of memory. * * @param pointer * Memory pointer, returned by {@link #allocate(long)} method. * */ void setLong(long pointer, long value); /** * Return <code>byte</code> value from given piece of memory. * * * @param pointer * Memory pointer, returned by {@link #allocate(long)} method. * @return byte value. */ byte getByte(long pointer); /** * Write <code>byte</code> value to given piece of memory. * * @param pointer * Memory pointer, returned by {@link #allocate(long)} method. * */ void setByte(long pointer, byte value); void setChar(long pointer, char value); char getChar(long pointer); /** * Performs copying of raw data in memory from one position to another. * * @param srcPointer * Memory pointer, returned by {@link #allocate(long)} method, from which data will be copied. * @param destPointer * Memory pointer to which data will be copied. * @param len * Data length. */ void moveData(long srcPointer, long destPointer, long len); }
false
commons_src_main_java_com_orientechnologies_common_directmemory_ODirectMemory.java
96
class ODirectMemoryFactory { public static final ODirectMemoryFactory INSTANCE = new ODirectMemoryFactory(); private static final ODirectMemory directMemory; static { ODirectMemory localDirectMemory = null; try { final Class<?> jnaClass = Class.forName("com.orientechnologies.nio.OJNADirectMemory"); if (jnaClass == null) localDirectMemory = null; else localDirectMemory = (ODirectMemory) jnaClass.newInstance(); } catch (Exception e) { // ignore } if (localDirectMemory == null) { try { final Class<?> sunClass = Class.forName("sun.misc.Unsafe"); if (sunClass != null) { localDirectMemory = OUnsafeMemory.INSTANCE; OLogManager.instance().warn( ODirectMemoryFactory.class, "Sun Unsafe direct memory implementation is going to be used, " + "this implementation is not stable so please use JNA version instead."); } } catch (Exception e) { // ignore } } directMemory = localDirectMemory; } public ODirectMemory directMemory() { return directMemory; } }
true
commons_src_main_java_com_orientechnologies_common_directmemory_ODirectMemoryFactory.java
97
public class ODirectMemoryPointer { private final boolean SAFE_MODE = !Boolean.valueOf(System.getProperty("memory.directMemory.unsafeMode")); private final ODirectMemory directMemory = ODirectMemoryFactory.INSTANCE.directMemory(); private final long pageSize; private final long dataPointer; public ODirectMemoryPointer(long pageSize) { if (pageSize <= 0) throw new ODirectMemoryViolationException("Size of allocated area should be more than zero but " + pageSize + " was provided."); this.dataPointer = directMemory.allocate(pageSize); this.pageSize = pageSize; } public ODirectMemoryPointer(byte[] data) { if (data.length == 0) throw new ODirectMemoryViolationException("Size of allocated area should be more than zero but 0 was provided."); this.dataPointer = directMemory.allocate(data); this.pageSize = data.length; } public byte[] get(long offset, int length) { if (SAFE_MODE) rangeCheck(offset, length); return directMemory.get(dataPointer + offset, length); } public void get(long offset, byte[] array, int arrayOffset, int length) { if (SAFE_MODE) rangeCheck(offset, length); directMemory.get(dataPointer + offset, array, arrayOffset, length); } public void set(long offset, byte[] content, int arrayOffset, int length) { if (SAFE_MODE) rangeCheck(offset, length); directMemory.set(dataPointer + offset, content, arrayOffset, length); } public int getInt(long offset) { if (SAFE_MODE) rangeCheck(offset, OIntegerSerializer.INT_SIZE); return directMemory.getInt(dataPointer + offset); } public void setInt(long offset, int value) { if (SAFE_MODE) rangeCheck(offset, OIntegerSerializer.INT_SIZE); directMemory.setInt(dataPointer + offset, value); } public void setShort(long offset, short value) { if (SAFE_MODE) rangeCheck(offset, OShortSerializer.SHORT_SIZE); directMemory.setShort(dataPointer + offset, value); } public short getShort(long offset) { if (SAFE_MODE) rangeCheck(offset, OShortSerializer.SHORT_SIZE); return directMemory.getShort(dataPointer + offset); } public long getLong(long offset) { if (SAFE_MODE) rangeCheck(offset, OLongSerializer.LONG_SIZE); return directMemory.getLong(dataPointer + offset); } public void setLong(long offset, long value) { if (SAFE_MODE) rangeCheck(offset, OLongSerializer.LONG_SIZE); directMemory.setLong(dataPointer + offset, value); } public byte getByte(long offset) { if (SAFE_MODE) rangeCheck(offset, OByteSerializer.BYTE_SIZE); return directMemory.getByte(dataPointer + offset); } public void setByte(long offset, byte value) { if (SAFE_MODE) rangeCheck(offset, OByteSerializer.BYTE_SIZE); directMemory.setByte(dataPointer + offset, value); } public void setChar(long offset, char value) { if (SAFE_MODE) rangeCheck(offset, OCharSerializer.CHAR_SIZE); directMemory.setChar(dataPointer + offset, value); } public char getChar(long offset) { if (SAFE_MODE) rangeCheck(offset, OCharSerializer.CHAR_SIZE); return directMemory.getChar(dataPointer + offset); } public void moveData(long srcOffset, ODirectMemoryPointer destPointer, long destOffset, long len) { if (SAFE_MODE) { rangeCheck(srcOffset, len); rangeCheck(destOffset, len); } directMemory.moveData(dataPointer + srcOffset, destPointer.getDataPointer() + destOffset, len); } private void rangeCheck(long offset, long size) { if (offset < 0) throw new ODirectMemoryViolationException("Negative offset was provided"); if (size < 0) throw new ODirectMemoryViolationException("Negative size was provided"); if (offset > pageSize) throw new ODirectMemoryViolationException("Provided offset [" + offset + "] is more than size of allocated area [" + pageSize + "]"); if (offset + size > pageSize) throw new ODirectMemoryViolationException("Last position of provided data interval [" + (offset + size) + "] is more than size of allocated area [" + pageSize + "]"); } public long getDataPointer() { return dataPointer; } public void free() { directMemory.free(dataPointer); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ODirectMemoryPointer that = (ODirectMemoryPointer) o; if (dataPointer != that.dataPointer) return false; if (pageSize != that.pageSize) return false; return true; } @Override public int hashCode() { int result = (int) (pageSize ^ (pageSize >>> 32)); result = 31 * result + (int) (dataPointer ^ (dataPointer >>> 32)); return result; } }
false
commons_src_main_java_com_orientechnologies_common_directmemory_ODirectMemoryPointer.java
98
public class ODirectMemoryViolationException extends OException { public ODirectMemoryViolationException(String message) { super(message); } }
false
commons_src_main_java_com_orientechnologies_common_directmemory_ODirectMemoryViolationException.java
99
@SuppressWarnings("restriction") public class OUnsafeMemory implements ODirectMemory { public static final OUnsafeMemory INSTANCE; protected static final Unsafe unsafe; private static final boolean unaligned; private static final long UNSAFE_COPY_THRESHOLD = 1024L * 1024L; static { OUnsafeMemory futureInstance; unsafe = (Unsafe) AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return f.get(null); } catch (NoSuchFieldException e) { throw new Error(); } catch (IllegalAccessException e) { throw new Error(); } } }); try { unsafe.getClass().getDeclaredMethod("copyMemory", Object.class, long.class, Object.class, long.class, long.class); Class<?> unsafeMemoryJava7 = OUnsafeMemory.class.getClassLoader().loadClass( "com.orientechnologies.common.directmemory.OUnsafeMemoryJava7"); futureInstance = (OUnsafeMemory) unsafeMemoryJava7.newInstance(); } catch (Exception e) { futureInstance = new OUnsafeMemory(); } INSTANCE = futureInstance; String arch = System.getProperty("os.arch"); unaligned = arch.equals("i386") || arch.equals("x86") || arch.equals("amd64") || arch.equals("x86_64"); } @Override public long allocate(byte[] bytes) { final long pointer = unsafe.allocateMemory(bytes.length); set(pointer, bytes, 0, bytes.length); return pointer; } @Override public long allocate(long size) { return unsafe.allocateMemory(size); } @Override public void free(long pointer) { unsafe.freeMemory(pointer); } @Override public byte[] get(long pointer, final int length) { final byte[] result = new byte[length]; for (int i = 0; i < length; i++) result[i] = unsafe.getByte(pointer++); return result; } @Override public void get(long pointer, byte[] array, int arrayOffset, int length) { pointer += arrayOffset; for (int i = arrayOffset; i < length + arrayOffset; i++) array[i] = unsafe.getByte(pointer++); } @Override public void set(long pointer, byte[] content, int arrayOffset, int length) { for (int i = arrayOffset; i < length + arrayOffset; i++) unsafe.putByte(pointer++, content[i]); } @Override public int getInt(long pointer) { if (unaligned) return unsafe.getInt(pointer); return (0xFF & unsafe.getByte(pointer++)) << 24 | (0xFF & unsafe.getByte(pointer++)) << 16 | (0xFF & unsafe.getByte(pointer++)) << 8 | (0xFF & unsafe.getByte(pointer)); } @Override public void setInt(long pointer, int value) { if (unaligned) unsafe.putInt(pointer, value); else { unsafe.putByte(pointer++, (byte) (value >>> 24)); unsafe.putByte(pointer++, (byte) (value >>> 16)); unsafe.putByte(pointer++, (byte) (value >>> 8)); unsafe.putByte(pointer, (byte) (value)); } } @Override public void setShort(long pointer, short value) { if (unaligned) unsafe.putShort(pointer, value); else { unsafe.putByte(pointer++, (byte) (value >>> 8)); unsafe.putByte(pointer, (byte) value); } } @Override public short getShort(long pointer) { if (unaligned) return unsafe.getShort(pointer); return (short) (unsafe.getByte(pointer++) << 8 | (unsafe.getByte(pointer) & 0xff)); } @Override public void setChar(long pointer, char value) { if (unaligned) unsafe.putChar(pointer, value); else { unsafe.putByte(pointer++, (byte) (value >>> 8)); unsafe.putByte(pointer, (byte) (value)); } } @Override public char getChar(long pointer) { if (unaligned) return unsafe.getChar(pointer); return (char) ((unsafe.getByte(pointer++) << 8) | (unsafe.getByte(pointer) & 0xff)); } @Override public long getLong(long pointer) { if (unaligned) return unsafe.getLong(pointer); return (0xFFL & unsafe.getByte(pointer++)) << 56 | (0xFFL & unsafe.getByte(pointer++)) << 48 | (0xFFL & unsafe.getByte(pointer++)) << 40 | (0xFFL & unsafe.getByte(pointer++)) << 32 | (0xFFL & unsafe.getByte(pointer++)) << 24 | (0xFFL & unsafe.getByte(pointer++)) << 16 | (0xFFL & unsafe.getByte(pointer++)) << 8 | (0xFFL & unsafe.getByte(pointer)); } @Override public void setLong(long pointer, long value) { if (unaligned) unsafe.putLong(pointer, value); else { unsafe.putByte(pointer++, (byte) (value >>> 56)); unsafe.putByte(pointer++, (byte) (value >>> 48)); unsafe.putByte(pointer++, (byte) (value >>> 40)); unsafe.putByte(pointer++, (byte) (value >>> 32)); unsafe.putByte(pointer++, (byte) (value >>> 24)); unsafe.putByte(pointer++, (byte) (value >>> 16)); unsafe.putByte(pointer++, (byte) (value >>> 8)); unsafe.putByte(pointer, (byte) (value)); } } @Override public byte getByte(long pointer) { return unsafe.getByte(pointer); } @Override public void setByte(long pointer, byte value) { unsafe.putByte(pointer, value); } @Override public void moveData(long srcPointer, long destPointer, long len) { while (len > 0) { long size = (len > UNSAFE_COPY_THRESHOLD) ? UNSAFE_COPY_THRESHOLD : len; unsafe.copyMemory(srcPointer, destPointer, size); len -= size; srcPointer += size; destPointer += size; } } }
false
commons_src_main_java_com_orientechnologies_common_directmemory_OUnsafeMemory.java