Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*-
   * See the file LICENSE for redistribution information.
   *
   * Copyright (c) 2000, 2010 Oracle and/or its affiliates.  All rights reserved.
   *
   */
  
  package com.sleepycat.collections;
  
 import java.util.List;
 
 /* <!-- begin JE only --> */
 /* <!-- end JE only --> */
 /* <!-- begin JE only --> */
 /* <!-- end JE only --> */
A abstract base class for all stored collections. This class, and its base class StoredContainer, provide implementations of most methods in the java.util.Collection interface. Other methods, such as java.util.Collection.add(java.lang.Object) and java.util.Collection.remove(java.lang.Object), are provided by concrete classes that extend this class.

In addition, this class provides the following methods for stored collections only. Note that the use of these methods is not compatible with the standard Java collections interface.

Author(s):
Mark Hayes
 
 public abstract class StoredCollection<E> extends StoredContainer
     implements Collection<E> {

    
The default number of records read at one time by iterators.

 
     public static final int DEFAULT_ITERATOR_BLOCK_SIZE = 10;
 
 
     StoredCollection(DataView view) {
 
         super(view);
     }

    
Returns the number of records read at one time by iterators returned by the iterator() method. By default this value is DEFAULT_ITERATOR_BLOCK_SIZE.
 
     public int getIteratorBlockSize() {
 
         return ;
     }

    
Changes the number of records read at one time by iterators returned by the iterator() method. By default this value is DEFAULT_ITERATOR_BLOCK_SIZE.

Throws:
java.lang.IllegalArgumentException if the blockSize is less than two.
 
     public void setIteratorBlockSize(int blockSize) {
 
         if (blockSize < 2) {
             throw new IllegalArgumentException
                 ("blockSize is less than two: " + blockSize);
         }
 
          = blockSize;
     }
 
     final boolean add(Object keyObject value) {
 
         DataCursor cursor = null;
         boolean doAutoCommit = beginAutoCommit();
         try {
             cursor = new DataCursor(true);
             OperationStatus status =
                cursor.putNoDupData(keyvaluenullfalse);
            closeCursor(cursor);
            commitAutoCommit(doAutoCommit);
            return (status == .);
        } catch (Exception e) {
            closeCursor(cursor);
            throw handleException(edoAutoCommit);
        }
    }
        return new BlockIterator(thisisWriteAllowed(), );
    }

    
Returns an iterator over the elements in this collection. The iterator will be read-only if the collection is read-only. This method conforms to the java.util.Collection.iterator() interface.

The iterator returned by this method does not keep a database cursor open and therefore it does not need to be closed. It reads blocks of records as needed, opening and closing a cursor to read each block of records. The number of records per block is 10 by default and can be changed with setIteratorBlockSize(int).

Because this iterator does not keep a cursor open, if it is used without transactions, the iterator does not have cursor stability characteristics. In other words, the record at the current iterator position can be changed or deleted by another thread. To prevent this from happening, call this method within a transaction or use the storedIterator() method instead.

Returns:
a standard java.util.Iterator for this collection.
See also:
StoredContainer.isWriteAllowed()
    public Iterator<E> iterator() {
        return blockIterator();
    }

    
Returns an iterator over the elements in this collection. The iterator will be read-only if the collection is read-only. This method does not exist in the standard java.util.Collection interface.

If Iterator.set or Iterator.remove will be called and the underlying Database is transactional, then a transaction must be active when calling this method and must remain active while using the iterator.

Warning: The iterator returned must be explicitly closed using StoredIterator.close() or StoredIterator.close(java.util.Iterator) to release the underlying database cursor resources.

Returns:
a StoredIterator for this collection.
See also:
StoredContainer.isWriteAllowed()
    public StoredIterator<E> storedIterator() {
        return storedIterator(isWriteAllowed());
    }

    
Returns a read or read-write iterator over the elements in this collection. This method does not exist in the standard java.util.Collection interface.

If Iterator.set or Iterator.remove will be called and the underlying Database is transactional, then a transaction must be active when calling this method and must remain active while using the iterator.

Warning: The iterator returned must be explicitly closed using StoredIterator.close() or StoredIterator.close(java.util.Iterator) to release the underlying database cursor resources.

Parameters:
writeAllowed is true to open a read-write iterator or false to open a read-only iterator. If the collection is read-only the iterator will always be read-only.
Returns:
a StoredIterator for this collection.
Throws:
java.lang.IllegalStateException if writeAllowed is true but the collection is read-only.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
See also:
StoredContainer.isWriteAllowed()
    public StoredIterator<E> storedIterator(boolean writeAllowed) {
        try {
            return new StoredIterator(thiswriteAllowed && isWriteAllowed(),
                                      null);
        } catch (Exception e) {
            throw StoredContainer.convertException(e);
        }
    }

    

Deprecated:
Please use storedIterator() or storedIterator(boolean) instead. Because the iterator returned must be closed, the method name iterator is confusing since standard Java iterators do not need to be closed.
    public StoredIterator<E> iterator(boolean writeAllowed) {
        return storedIterator(writeAllowed);
    }

    
Returns an array of all the elements in this collection. This method conforms to the java.util.Collection.toArray() interface.

Throws:
com.sleepycat.je.OperationFailureException if one of the Read Operation Failures occurs.
com.sleepycat.je.EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
    public Object[] toArray() {
        ArrayList<Objectlist = new ArrayList<Object>();
        StoredIterator i = null;
        try {
            i = storedIterator();
            while (i.hasNext()) {
                list.add(i.next());
            }
        } catch (Exception e) {
            throw StoredContainer.convertException(e);
        } finally {
            StoredIterator.close(i);
        }
        return list.toArray();
    }

    
Returns an array of all the elements in this collection whose runtime type is that of the specified array. This method conforms to the java.util.Collection.toArray(java.lang.Object[]) interface.

Throws:
com.sleepycat.je.OperationFailureException if one of the Read Operation Failures occurs.
com.sleepycat.je.EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
    public <T> T[] toArray(T[] a) {
        int j = 0;
        StoredIterator i = null;
        try {
            i = storedIterator();
            while (j < a.length && i.hasNext()) {
                a[j++] = (T) i.next();
            }
            if (j < a.length) {
                a[j] = null;
            } else if (i.hasNext()) {
                ArrayList<T> list = new ArrayList<T>(Arrays.asList(a));
                while (i.hasNext()) {
                    list.add((T) i.next());
                }
                a = list.toArray(a);
            }
        } catch (Exception e) {
            throw StoredContainer.convertException(e);
        } finally {
            StoredIterator.close(i);
        }
        return a;
    }

    
Returns true if this collection contains all of the elements in the specified collection. This method conforms to the java.util.Collection.containsAll(java.util.Collection) interface.

Throws:
com.sleepycat.je.OperationFailureException if one of the Read Operation Failures occurs.
com.sleepycat.je.EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
    public boolean containsAll(Collection<?> coll) {
        Iterator<?> i = null;
        try {
            i = storedOrExternalIterator(coll);
            while (i.hasNext()) {
                if (!contains(i.next())) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            throw StoredContainer.convertException(e);
        } finally {
            StoredIterator.close(i);
        }
    }

    
Adds all of the elements in the specified collection to this collection (optional operation). This method calls the java.util.Collection.add(java.lang.Object) method of the concrete collection class, which may or may not be supported. This method conforms to the java.util.Collection.addAll(java.util.Collection) interface.

Throws:
com.sleepycat.je.OperationFailureException if one of the Write Operation Failures occurs.
com.sleepycat.je.EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.UnsupportedOperationException if the collection is read-only, or if the collection is indexed, or if the add method is not supported by the concrete collection.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
    public boolean addAll(Collection<? extends E> coll) {
        Iterator<? extends E> i = null;
        boolean doAutoCommit = beginAutoCommit();
        try {
            i = storedOrExternalIterator(coll);
            boolean changed = false;
            while (i.hasNext()) {
                if (add(i.next())) {
                    changed = true;
                }
            }
            StoredIterator.close(i);
            commitAutoCommit(doAutoCommit);
            return changed;
        } catch (Exception e) {
            StoredIterator.close(i);
            throw handleException(edoAutoCommit);
        }
    }

    
Removes all this collection's elements that are also contained in the specified collection (optional operation). This method conforms to the java.util.Collection.removeAll(java.util.Collection) interface.

Throws:
com.sleepycat.je.OperationFailureException if one of the Write Operation Failures occurs.
com.sleepycat.je.EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.UnsupportedOperationException if the collection is read-only.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
    public boolean removeAll(Collection<?> coll) {
        Iterator<? extends E> i = null;
        boolean doAutoCommit = beginAutoCommit();
        try {
            boolean changed = false;
            i = storedOrExternalIterator(coll);
            while (i.hasNext()) {
                if (remove(i.next())) {
                    changed = true;
                }
            }
            StoredIterator.close(i);
            commitAutoCommit(doAutoCommit);
            return changed;
        } catch (Exception e) {
            StoredIterator.close(i);
            throw handleException(edoAutoCommit);
        }
    }

    
Retains only the elements in this collection that are contained in the specified collection (optional operation). This method conforms to the java.util.Collection.removeAll(java.util.Collection) interface.

Throws:
com.sleepycat.je.OperationFailureException if one of the Write Operation Failures occurs.
com.sleepycat.je.EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.UnsupportedOperationException if the collection is read-only.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
    public boolean retainAll(Collection<?> coll) {
        StoredIterator i = null;
        boolean doAutoCommit = beginAutoCommit();
        try {
            boolean changed = false;
            i = storedIterator();
            while (i.hasNext()) {
                if (!coll.contains(i.next())) {
                    i.remove();
                    changed = true;
                }
            }
            StoredIterator.close(i);
            commitAutoCommit(doAutoCommit);
            return changed;
        } catch (Exception e) {
            StoredIterator.close(i);
            throw handleException(edoAutoCommit);
        }
    }

    
Compares the specified object with this collection for equality. A value comparison is performed by this method and the stored values are compared rather than calling the equals() method of each element. This method conforms to the java.util.Collection.equals(java.lang.Object) interface.

Throws:
com.sleepycat.je.OperationFailureException if one of the Read Operation Failures occurs.
com.sleepycat.je.EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
    public boolean equals(Object other) {
        if (other instanceof Collection) {
            Collection otherColl = StoredCollection.copyCollection(other);
            StoredIterator i = null;
            try {
                i = storedIterator();
                boolean otherHasAll = true;
                while (i.hasNext()) {
                    if (!otherColl.remove(i.next())) {
                        otherHasAll = false;
                        break;
                    }
                }
                return otherHasAll && otherColl.isEmpty();
            } catch (Exception e) {
                throw StoredContainer.convertException(e);
            } finally {
                StoredIterator.close(i);
            }
        } else {
            return false;
        }
    }
    /*
     * Add this in to keep FindBugs from whining at us about implementing
     * equals(), but not hashCode().
     */
    public int hashCode() {
        return super.hashCode();
    }

    
Returns a copy of this collection as an ArrayList. This is the same as toArray() but returns a collection instead of an array.

Returns:
an java.util.ArrayList containing a copy of all elements in this collection.
Throws:
com.sleepycat.je.OperationFailureException if one of the Read Operation Failures occurs.
com.sleepycat.je.EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
    public List<E> toList() {
        ArrayList<E> list = new ArrayList<E>();
        StoredIterator<E> i = null;
        try {
            i = storedIterator();
            while (i.hasNext()) {
                list.add(i.next());
            }
            return list;
        } catch (Exception e) {
            throw StoredContainer.convertException(e);
        } finally {
            StoredIterator.close(i);
        }
    }

    
Converts the collection to a string representation for debugging. WARNING: The returned string may be very large.

Returns:
the string representation.
Throws:
com.sleepycat.je.OperationFailureException if one of the Read Operation Failures occurs.
com.sleepycat.je.EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
    public String toString() {
        StringBuilder buf = new StringBuilder();
        buf.append("[");
        StoredIterator i = null;
        try {
            i = storedIterator();
            while (i.hasNext()) {
                if (buf.length() > 1) buf.append(',');
                buf.append(i.next().toString());
            }
            buf.append(']');
            return buf.toString();
        } catch (Exception e) {
            throw StoredContainer.convertException(e);
        } finally {
            StoredIterator.close(i);
        }
    }
    // Inherit javadoc
    public int size() {
        boolean countDups = iterateDuplicates();
        if (. && countDups && !..hasBound()) {
            try {
                return (int) DbCompat.getDatabaseCount(.);
            } catch (Exception e) {
                throw StoredContainer.convertException(e);
            }
        } else {
            int count = 0;
            CursorConfig cursorConfig = ..isLockingMode() ?
                . : null;
            DataCursor cursor = null;
            /* Auto-commit is not needed because ReadUncommitted is used. */
            try {
                cursor = new DataCursor(falsecursorConfig);
                OperationStatus status = cursor.getFirst(false);
                while (status == .) {
                    if (countDups) {
                        count += cursor.count();
                    } else {
                        count += 1;
                    }
                    status = cursor.getNextNoDup(false);
                }
            } catch (Exception e) {
                throw StoredContainer.convertException(e);
            } finally {
                closeCursor(cursor);
            }
            return count;
        }
    }

    
Returns an iterator representing an equality join of the indices and index key values specified. This method does not exist in the standard java.util.Collection interface.

Warning: The iterator returned must be explicitly closed using StoredIterator.close() or StoredIterator.close(java.util.Iterator) to release the underlying database cursor resources.

The returned iterator supports only the two methods: hasNext() and next(). All other methods will throw UnsupportedOperationException.

Parameters:
indices is an array of indices with elements corresponding to those in the indexKeys array.
indexKeys is an array of index key values identifying the elements to be selected.
joinConfig is the join configuration, or null to use the default configuration.
Returns:
an iterator over the elements in this collection that match all specified index key values.
Throws:
com.sleepycat.je.OperationFailureException if one of the Read Operation Failures occurs.
com.sleepycat.je.EnvironmentFailureException if an unexpected, internal or environment-wide failure occurs.
java.lang.IllegalArgumentException if this collection is indexed or if a given index does not have the same store as this collection.
com.sleepycat.util.RuntimeExceptionWrapper if a checked exception is thrown, including a DatabaseException on BDB (C Edition).
    public StoredIterator<E> join(StoredContainer[] indices,
                                  Object[] indexKeys,
                                  JoinConfig joinConfig) {
        try {
            DataView[] indexViews = new DataView[indices.length];
            for (int i = 0; i < indices.lengthi += 1) {
                indexViews[i] = indices[i].;
            }
            DataCursor cursor = .join(indexViewsindexKeysjoinConfig);
            return new StoredIterator<E>(thisfalsecursor);
        } catch (Exception e) {
            throw StoredContainer.convertException(e);
        }
    }
    final E getFirstOrLast(boolean doGetFirst) {
        DataCursor cursor = null;
        try {
            cursor = new DataCursor(false);
            OperationStatus status;
            if (doGetFirst) {
                status = cursor.getFirst(false);
            } else {
                status = cursor.getLast(false);
            }
            return (status == .) ?
                makeIteratorData(nullcursor) :
                null;
        } catch (Exception e) {
            throw StoredContainer.convertException(e);
        } finally {
            closeCursor(cursor);
        }
    }
    E makeIteratorData(BaseIterator iteratorDataCursor cursor) {
        return makeIteratorData(iterator,
                                cursor.getKeyThang(),
                                cursor.getPrimaryKeyThang(),
                                cursor.getValueThang());
    }
    abstract E makeIteratorData(BaseIterator iterator,
                                DatabaseEntry keyEntry,
                                DatabaseEntry priKeyEntry,
                                DatabaseEntry valueEntry);
    abstract boolean hasValues();
    boolean iterateDuplicates() {
        return true;
    }
    void checkIterAddAllowed()
        throws UnsupportedOperationException {
        if (!areDuplicatesAllowed()) {
            throw new UnsupportedOperationException("Duplicates required");
        }
    }
    int getIndexOffset() {
        return 0;
    }
    private static Collection copyCollection(Object other) {
        if (other instanceof StoredCollection) {
            return ((StoredCollectionother).toList();
        } else {
            return new ArrayList((Collectionother);
        }
    }
New to GrepCode? Check out our FAQ X