Package org.jpox.sco

Source Code of org.jpox.sco.Set

/**********************************************************************
Copyright (c) 2003 Mike Martin and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Contributors:
2004 Andy Jefferson - rewritten to always have delegate present
2005 Andy Jefferson changed to not extend org.jpox.sco.Collection to handle nulls, dups correctly
    ...
**********************************************************************/
package org.jpox.sco;

import java.io.ObjectStreamException;
import java.util.AbstractSet;
import java.util.Iterator;

import org.jpox.ClassLoaderResolver;
import org.jpox.ObjectManager;
import org.jpox.ObjectManagerFactoryImpl;
import org.jpox.StateManager;
import org.jpox.exceptions.JPOXDataStoreException;
import org.jpox.metadata.AbstractMemberMetaData;
import org.jpox.metadata.FieldPersistenceModifier;
import org.jpox.sco.exceptions.NullsNotAllowedException;
import org.jpox.sco.exceptions.QueryUnownedSCOException;
import org.jpox.sco.queued.AddOperation;
import org.jpox.sco.queued.ClearOperation;
import org.jpox.sco.queued.QueuedOperation;
import org.jpox.sco.queued.RemoveOperation;
import org.jpox.state.FetchPlanState;
import org.jpox.state.StateManagerFactory;
import org.jpox.store.mapped.DatastoreIdentifier;
import org.jpox.store.mapped.expression.QueryExpression;
import org.jpox.store.mapped.query.Queryable;
import org.jpox.store.mapped.scostore.CollectionStoreQueryable;
import org.jpox.store.query.ResultObjectFactory;
import org.jpox.store.scostore.CollectionStore;
import org.jpox.store.scostore.SetStore;
import org.jpox.util.JPOXLogger;
import org.jpox.util.Localiser;
import org.jpox.util.StringUtils;

/**
* A mutable second-class Set object.
* This class extends Set, using that class to contain the current objects, and the backing SetStore
* to be the interface to the datastore. A "backing store" is not present for datastores that dont use
* DatastoreClass, or if the container is serialised or non-persistent.
*
* <H3>Modes of Operation</H3>
* The user can operate the list in 2 modes.
* The <B>cached</B> mode will use an internal cache of the elements (in the "delegate") reading them at
* the first opportunity and then using the cache thereafter.
* The <B>non-cached</B> mode will just go direct to the "backing store" each call.
*
* <H3>Mutators</H3>
* When the "backing store" is present any updates are passed direct to the datastore as well as to the "delegate".
* If the "backing store" isn't present the changes are made to the "delegate" only.
*
* <H3>Accessors</H3>
* When any accessor method is invoked, it typically checks whether the container has been loaded from its
* "backing store" (where present) and does this as necessary. Some methods (<B>size()</B>) just check if
* everything is loaded and use the delegate if possible, otherwise going direct to the datastore.
*
* @version $Revision: 1.68 $
*/
public class Set extends AbstractSet
    implements SCOCollection, SCOMtoN, Cloneable, Queryable, java.io.Serializable
{
    protected static final Localiser LOCALISER = Localiser.getInstance("org.jpox.Localisation",
        ObjectManagerFactoryImpl.class.getClassLoader());

    protected Object owner;
    protected StateManager ownerSM;
    protected String fieldName;
    protected int fieldNumber;
    protected Class elementType;
    protected boolean allowNulls;

    /** The "backing store" (for use when not serialised). */
    protected CollectionStore backingStore;

    /** The internal "delegate". */
    protected java.util.Collection delegate;

    /** Whether to use "delegate" caching. */
    protected boolean useCache=true;

    /** Status flag whether the collection is loaded into the cache. */
    protected boolean isCacheLoaded=false;

    /** Whether the SCO is in "direct" or "queued" mode. */
    boolean queued = false;

    /** Queued operations when using "queued" mode. */
    private java.util.ArrayList queuedOperations = null;

    /**
     * Constructor.
     * @param ownerSM The State Manager for this set.
     * @param fieldName Name of the field
     */
    public Set(StateManager ownerSM, String fieldName)
    {
        this(ownerSM, fieldName, false, null);
    }

    /**
     * Constructor allowing the specification of the backing store to be used.
     * @param ownerSM State Manager for the owning object
     * @param fieldName Name of the field
     * @param allowsNulls Whether nulls are allowed
     * @param backingStore The backing store
     */
    Set(StateManager ownerSM, String fieldName, boolean allowsNulls, SetStore backingStore)
    {
        this.ownerSM = ownerSM;
        this.fieldName = fieldName;
        this.allowNulls = allowsNulls;

        // Set up our delegate
        this.delegate = new java.util.HashSet();

        if (ownerSM != null)
        {
            AbstractMemberMetaData fmd = ownerSM.getClassMetaData().getMetaDataForMember(fieldName);
            owner = ownerSM.getObject();
            fieldNumber = fmd.getAbsoluteFieldNumber();
            allowNulls = SCOUtils.allowNullsInContainer(allowNulls, fmd);
            if (ownerSM.getStoreManager().getSupportedOptions().contains("ContainerQueueing"))
            {
                queued = SCOUtils.useContainerQueueing(ownerSM);
                useCache = SCOUtils.useContainerCache(ownerSM, fieldName);
            }

            ClassLoaderResolver clr = ownerSM.getObjectManager().getClassLoaderResolver();
            if (backingStore != null)
            {
                this.backingStore = backingStore;
                this.elementType = clr.classForName(backingStore.getElementType());
            }
            else if (!SCOUtils.collectionHasSerialisedElements(fmd) &&
                fmd.getPersistenceModifier() == FieldPersistenceModifier.PERSISTENT)
            {
                try
                {
                    this.backingStore = (CollectionStore)ownerSM.getStoreManager().getBackingStoreForField(clr,fmd,java.util.Set.class);
                    this.elementType = clr.classForName(this.backingStore.getElementType());
                }
                catch(UnsupportedOperationException ex)
                {
                    //some datastores do not support backingStores
                }
            }
            if (JPOXLogger.PERSISTENCE.isDebugEnabled())
            {
                JPOXLogger.PERSISTENCE.debug(SCOUtils.getContainerInfoMessage(ownerSM, fieldName, this,
                    useCache, queued, allowNulls, SCOUtils.useCachedLazyLoading(ownerSM, fieldName)));
            }
        }
    }

    /**
     * Method to initialise the SCO from an existing value.
     * @param o The object to set from
     * @param forInsert Whether the object needs inserting in the datastore with this value
     * @param forUpdate Whether to update the datastore with this value
     */
    public void initialise(Object o, boolean forInsert, boolean forUpdate)
    {
        java.util.Collection c = (java.util.Collection)o;
        if (c != null)
        {
            // Check for the case of serialised PC elements, and assign StateManagers to the elements without
            AbstractMemberMetaData fmd = ownerSM.getClassMetaData().getMetaDataForMember(fieldName);
            if (SCOUtils.collectionHasSerialisedElements(fmd) && fmd.getCollection().getElementClassMetaData() != null)
            {
                ObjectManager om = ownerSM.getObjectManager();
                Iterator iter = c.iterator();
                while (iter.hasNext())
                {
                    Object pc = iter.next();
                    StateManager objSM = om.findStateManager(pc);
                    if (objSM == null)
                    {
                        objSM = StateManagerFactory.newStateManagerForEmbedded(om, pc, false);
                        objSM.addEmbeddedOwner(ownerSM, fieldNumber);
                    }
                }
            }

            if (backingStore != null && useCache && !isCacheLoaded)
            {
                // Mark as loaded
                isCacheLoaded = true;
            }

            if (forInsert)
            {
                if (JPOXLogger.PERSISTENCE.isDebugEnabled())
                {
                    JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023007",
                        StringUtils.toJVMIDString(ownerSM.getObject()), fieldName, "" + c.size()));
                }
                addAll(c);
            }
            else if (forUpdate)
            {
                if (JPOXLogger.PERSISTENCE.isDebugEnabled())
                {
                    JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023008",
                        StringUtils.toJVMIDString(ownerSM.getObject()), fieldName, "" + c.size()));
                }
                clear();
                addAll(c);
            }
            else
            {
                if (JPOXLogger.PERSISTENCE.isDebugEnabled())
                {
                    JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023007",
                        StringUtils.toJVMIDString(ownerSM.getObject()), fieldName, "" + c.size()));
                }
                delegate.clear();
                delegate.addAll(c);
            }
        }
    }

    /**
     * Method to initialise the SCO for use.
     */
    public void initialise()
    {
        if (useCache && !SCOUtils.useCachedLazyLoading(ownerSM, fieldName))
        {
            // Load up the container now if not using lazy loading
            loadFromStore();
        }
    }

    // ----------------------- Implementation of SCO methods -------------------

    /**
     * Accessor for the unwrapped value that we are wrapping.
     * @return The unwrapped value
     */
    public Object getValue()
    {
        // TODO Cater for delegate not being used
        return delegate;
    }

    /**
     * Accessor for the element type.
     * @return the element type contained in the collection
     */
    public Class getElementType()
    {
        return elementType;
    }

    /**
     * Method to effect the load of the data in the SCO.
     * Used when the SCO supports lazy-loading to tell it to load all now.
     */
    public void load()
    {
        if (useCache)
        {
            loadFromStore();
        }
    }

    /**
     * Method to load all elements from the "backing store" where appropriate.
     */
    protected void loadFromStore()
    {
        if (backingStore != null && !isCacheLoaded)
        {
            if (JPOXLogger.PERSISTENCE.isDebugEnabled())
            {
                JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023006",
                    StringUtils.toJVMIDString(ownerSM.getObject()), fieldName));
            }
            delegate.clear();
            Iterator iter=backingStore.iterator(ownerSM);
            while (iter.hasNext())
            {
                delegate.add(iter.next());
            }

            isCacheLoaded = true;
        }
    }

    /**
     * Method to flush the changes to the datastore when operating in queued mode.
     * Does nothing in "direct" mode.
     */
    public void flush()
    {
        if (queued)
        {
            if (queuedOperations != null)
            {
                if (JPOXLogger.PERSISTENCE.isDebugEnabled())
                {
                    JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023005",
                        StringUtils.toJVMIDString(ownerSM.getObject()), fieldName));
                }
                Iterator iter = queuedOperations.iterator();
                while (iter.hasNext())
                {
                    QueuedOperation op = (QueuedOperation)iter.next();
                    op.perform(backingStore, ownerSM);
                }

                queuedOperations.clear();
                queuedOperations = null;
            }
        }
    }

    /**
     * Convenience method to add a queued operation to the operations we perform at commit.
     * @param op The operation
     */
    protected void addQueuedOperation(QueuedOperation op)
    {
        if (queuedOperations == null)
        {
            queuedOperations = new java.util.ArrayList();
        }
        queuedOperations.add(op);
    }

    /**
     * Method to update an embedded element in this collection.
     * @param element The element
     * @param fieldNumber Number of field in the element
     * @param value New value for this field
     */
    public void updateEmbeddedElement(Object element, int fieldNumber, Object value)
    {
        if (backingStore != null)
        {
            backingStore.updateEmbeddedElement(ownerSM, element, fieldNumber, value);
        }
    }

    /**
     * Accessor for the field name.
     * @return The field name
     */
    public String getFieldName()
    {
        return fieldName;
    }

    /**
     * Accessor for the owner object.
     * @return The owner object
     */
    public Object getOwner()
    {
        return owner;
    }

    /**
     * Method to unset the owner and field information.
     */
    public synchronized void unsetOwner()
    {
        if (ownerSM != null)
        {
            owner = null;
            ownerSM = null;
            fieldName = null;
            backingStore = null;
        }
    }

    /**
     * Utility to mark the object as dirty
     **/
    public void makeDirty()
    {
        /*
         * Although we are never really "dirty", the owning object must be
         * marked dirty so that the proper state change occurs and its
         * jdoPreStore() gets called properly.
         */
        if (ownerSM != null)
        {
            ownerSM.getObjectManager().getApiAdapter().makeFieldDirty(owner, fieldName);
        }
    }

    /**
     * Method to return a detached copy of the container.
     * Recurses through the elements so that they are likewise detached.
     * @param state State for detachment process
     * @return The detached container
     */
    public Object detachCopy(FetchPlanState state)
    {
        java.util.Collection detached = new java.util.HashSet();
        SCOUtils.detachCopyForCollection(ownerSM, toArray(), state, detached);
        return detached;
    }

    /**
     * Method to return an attached copy of the passed (detached) value. The returned attached copy
     * is a SCO wrapper. Goes through the existing elements in the store for this owner field and
     * removes ones no longer present, and adds new elements. All elements in the (detached)
     * value are attached.
     * @param value The new (collection) value
     */
    public void attachCopy(Object value)
    {
        java.util.Collection c = (java.util.Collection) value;

        // Attach all of the elements in the new collection
        AbstractMemberMetaData fmd = ownerSM.getClassMetaData().getMetaDataForMember(fieldName);
        boolean elementsWithoutIdentity = SCOUtils.collectionHasElementsWithoutIdentity(fmd);

        java.util.Collection attachedElements = new java.util.HashSet(c.size());
        SCOUtils.attachCopyForCollection(ownerSM, c.toArray(), attachedElements, elementsWithoutIdentity);

        // Update the attached collection with the detached elements
        SCOUtils.updateCollectionWithCollectionElements(this, attachedElements);
    }

    // ------------------------ Query Statement methods ------------------------

    /**
     * Method to generate a QueryStatement for the SCO.
     * @return The QueryStatement
     */
    public synchronized QueryExpression newQueryStatement()
    {
        return newQueryStatement(elementType, null);
    }

    /**
     * Method to return a QueryStatement, using the specified candidate class.
     * @param candidateClass the candidate class
     * @param candidateAlias Alias for the candidate
     * @return The QueryStatement
     */
    public synchronized QueryExpression newQueryStatement(Class candidateClass, DatastoreIdentifier candidateAlias)
    {
        if (backingStore == null)
        {
            throw new QueryUnownedSCOException();
        }

        return ((CollectionStoreQueryable)backingStore).newQueryStatement(ownerSM, candidateClass.getName(), candidateAlias);
    }

    /**
     * Method to return a ResultObjectFactory for the SCO.
     * @param stmt The QueryStatement
     * @param ignoreCache Whether to ignore the cache
     * @param resultClass Whether to create objects of a particular class
     * @param useFetchPlan whether to use the fetch plan to retrieve fields in the same query
     * @return The ResultObjectFactory
     */
    public synchronized ResultObjectFactory newResultObjectFactory(QueryExpression stmt,boolean ignoreCache, Class resultClass, boolean useFetchPlan)
    {
        if (backingStore == null)
        {
            throw new QueryUnownedSCOException();
        }

        return ((CollectionStoreQueryable)backingStore).newResultObjectFactory(ownerSM, stmt,ignoreCache,useFetchPlan);
    }

    // ---------------- Implementation of Collection methods -------------------
    /**
     * Creates and returns a copy of this object.
     * <P>
     * Mutable second-class Objects are required to provide a public
     * clone method in order to allow for copying PersistenceCapable
     * objects. In contrast to Object.clone(), this method must not throw a
     * CloneNotSupportedException.
     * @return A clone of the object
     */
    public Object clone()
    {
        if (useCache)
        {
            loadFromStore();
        }

        return ((java.util.HashSet)delegate).clone();
    }

    /**
     * Accessor for whether an element is contained in the Collection.
     * @param element The element
     * @return Whether the element is contained here
     **/
    public synchronized boolean contains(Object element)
    {
        if (useCache && isCacheLoaded)
        {
            // If the "delegate" is already loaded, use it
            return delegate.contains(element);
        }
        else if (backingStore != null)
        {
            return backingStore.contains(ownerSM,element);
        }

        return delegate.contains(element);
    }

    /**
     * Accessor for whether a collection of elements are contained here.
     * @param c The collection of elements.
     * @return Whether they are contained.
     **/
    public synchronized boolean containsAll(java.util.Collection c)
    {
        if (useCache)
        {
            loadFromStore();
        }
        else if (backingStore != null)
        {
            java.util.HashSet h=new java.util.HashSet(c);
            Iterator iter=iterator();
            while (iter.hasNext())
            {
                h.remove(iter.next());
            }

            return h.isEmpty();
        }

        return delegate.containsAll(c);
    }

    /**
     * Equality operator.
     * @param o The object to compare against.
     * @return Whether this object is the same.
     **/
    public synchronized boolean equals(Object o)
    {
        if (useCache)
        {
            loadFromStore();
        }

        if (o == this)
        {
            return true;
        }
        if (!(o instanceof java.util.Set))
        {
            return false;
        }
        java.util.Set c = (java.util.Set)o;

        return c.size() == size() && containsAll(c);
    }

    /**
     * Hashcode operator.
     * @return The Hash code.
     **/
    public synchronized int hashCode()
    {
        if (useCache)
        {
            loadFromStore();
        }
        return delegate.hashCode();
    }

    /**
     * Accessor for whether the Collection is empty.
     * @return Whether it is empty.
     **/
    public synchronized boolean isEmpty()
    {
        return (size() == 0);
    }

    /**
     * Accessor for an iterator for the Collection.
     * @return The iterator
     **/
    public synchronized Iterator iterator()
    {
        // Populate the cache if necessary
        if (useCache)
        {
            loadFromStore();
        }
        return new SCOCollectionIterator(this, ownerSM, delegate, backingStore, useCache);
    }

    /**
     * Accessor for the size of the Collection.
     * @return The size
     **/
    public synchronized int size()
    {
        if (useCache && isCacheLoaded)
        {
            // If the "delegate" is already loaded, use it
            return delegate.size();
        }
        else if (backingStore != null)
        {
            return backingStore.size(ownerSM);
        }

        return delegate.size();
    }

    /**
     * Method to return the Collection as an array.
     * @return The array
     **/
    public synchronized Object[] toArray()
    {
        if (useCache)
        {
            loadFromStore();
        }
        else if (backingStore != null)
        {
            return SCOUtils.toArray(backingStore,ownerSM);
       
        return delegate.toArray();
    }

    /**
     * Method to return the Collection as an array.
     * @param a The array to write the results to
     * @return The array
     **/
    public synchronized Object[] toArray(Object a[])
    {
        if (useCache)
        {
            loadFromStore();
        }
        else if (backingStore != null)
        {
            return SCOUtils.toArray(backingStore,ownerSM,a);
       
        return delegate.toArray(a);
    }

    /**
     * Method to return the Collection as a String.
     * @return The string form
     **/
    public String toString()
    {
        StringBuffer s = new StringBuffer("[");
        int i=0;
        Iterator iter=iterator();
        while (iter.hasNext())
        {
            if (i > 0)
            {
                s.append(',');
            }
            s.append(iter.next());
            i++;
        }
        s.append("]");

        return s.toString();
    }

    // ----------------------------- Mutator methods ---------------------------

    /**
     * Method to add an element to the Collection.
     * @param element The element to add
     * @return Whether it was added successfully.
     **/
    public synchronized boolean add(Object element)
    {
        // Reject inappropriate elements
        if (element == null && !allowNulls)
        {
            throw new NullsNotAllowedException(ownerSM, fieldName);
        }

        if (useCache)
        {
            loadFromStore();
        }

        boolean backingSuccess = true;
        if (backingStore != null)
        {
            if (ownerSM.getRelationshipManager() != null)
            {
                // Relationship management
                ownerSM.getRelationshipManager().relationAdd(fieldNumber, element);
            }
            if (queued && !ownerSM.getObjectManager().isFlushing())
            {
                addQueuedOperation(new AddOperation(element));
            }
            else
            {
                try
                {
                    backingSuccess = backingStore.add(ownerSM, element, (useCache ? delegate.size() : -1));
                }
                catch (JPOXDataStoreException dse)
                {
                    JPOXLogger.PERSISTENCE.warn(LOCALISER.msg("023013", "add", fieldName, dse));
                    backingSuccess = false;
                }
            }
        }

        // Only make it dirty after adding the field to the datastore so we give it time
        // to be inserted - otherwise jdoPreStore on this object would have been called before completing the addition
        makeDirty();

        boolean delegateSuccess = delegate.add(element);
        return (backingStore != null ? backingSuccess : delegateSuccess);
    }

    /**
     * Method to add a collection of elements.
     * @param c The collection of elements to add.
     * @return Whether they were added successfully.
     **/
    public synchronized boolean addAll(java.util.Collection c)
    {
        if (useCache)
        {
            loadFromStore();
        }

        boolean backingSuccess = true;
        if (backingStore != null)
        {
            if (ownerSM.getRelationshipManager() != null)
            {
                // Relationship management
                Iterator iter = c.iterator();
                while (iter.hasNext())
                {
                    ownerSM.getRelationshipManager().relationAdd(fieldNumber, iter.next());
                }
            }
            if (queued && !ownerSM.getObjectManager().isFlushing())
            {
                Iterator iter = c.iterator();
                while (iter.hasNext())
                {
                    addQueuedOperation(new AddOperation(iter.next()));
                }
            }
            else
            {
                try
                {
                    backingSuccess = backingStore.addAll(ownerSM, c, (useCache ? delegate.size() : -1));
                }
                catch (JPOXDataStoreException dse)
                {
                    JPOXLogger.PERSISTENCE.warn(LOCALISER.msg("023013", "addAll", fieldName, dse));
                    backingSuccess = false;
                }
            }
        }

        // Only make it dirty after adding the field to the datastore so we give it time
        // to be inserted - otherwise jdoPreStore on this object would have been called before completing the addition
        makeDirty();

        boolean delegateSuccess = delegate.addAll(c);
        return (backingStore != null ? backingSuccess : delegateSuccess);
    }

    /**
     * Method to clear the Collection.
     **/
    public synchronized void clear()
    {
        makeDirty();

        if (backingStore != null)
        {
            if (queued && !ownerSM.getObjectManager().isFlushing())
            {
                addQueuedOperation(new ClearOperation());
            }
            else
            {
                backingStore.clear(ownerSM);
            }
        }
        delegate.clear();
    }

    /**
     * Method to remove an element from the Collection.
     * @param element The Element to remove
     * @return Whether it was removed successfully.
     **/
    public synchronized boolean remove(Object element)
    {
        return remove(element, true);
    }

    /**
     * Method to remove an element from the collection, and observe the flag for whether to allow cascade delete.
     * @param element The element
     * @param allowCascadeDelete Whether to allow cascade delete
     */
    public boolean remove(Object element, boolean allowCascadeDelete)
    {
        makeDirty();

        if (useCache)
        {
            loadFromStore();
        }

        int size = (useCache ? delegate.size() : -1);
        boolean contained = delegate.contains(element);
        boolean delegateSuccess = delegate.remove(element);

        boolean backingSuccess = true;
        if (backingStore != null)
        {
            if (ownerSM.getRelationshipManager() != null)
            {
                ownerSM.getRelationshipManager().relationRemove(fieldNumber, element);
            }
            if (queued && !ownerSM.getObjectManager().isFlushing())
            {
                backingSuccess = contained;
                if (backingSuccess)
                {
                    addQueuedOperation(new RemoveOperation(element, allowCascadeDelete));
                }
            }
            else
            {
                try
                {
                    backingSuccess = backingStore.remove(ownerSM, element, size, allowCascadeDelete);
                }
                catch (JPOXDataStoreException dse)
                {
                    JPOXLogger.PERSISTENCE.warn(LOCALISER.msg("023013", "remove", fieldName, dse));
                    backingSuccess = false;
                }
            }
        }

        return (backingStore != null ? backingSuccess : delegateSuccess);
    }

    /**
     * Method to remove a Collection of elements.
     * @param c The collection to remove
     * @return Whether they were removed successfully.
     **/
    public synchronized boolean removeAll(java.util.Collection c)
    {
        makeDirty();
        if (useCache)
        {
            loadFromStore();
        }

        if (backingStore != null)
        {
            boolean backingSuccess = false;
            int size = (useCache ? delegate.size() : -1);

            if (ownerSM.getRelationshipManager() != null)
            {
                // Relationship management
                Iterator iter = c.iterator();
                while (iter.hasNext())
                {
                    ownerSM.getRelationshipManager().relationRemove(fieldNumber, iter.next());
                }
            }

            if (queued && !ownerSM.getObjectManager().isFlushing())
            {
                backingSuccess = false;
                Iterator iter = c.iterator();
                while (iter.hasNext())
                {
                    Object element = iter.next();
                    if (contains(element))
                    {
                        backingSuccess = true;
                        addQueuedOperation(new RemoveOperation(element));
                    }
                }
            }
            else
            {
                try
                {
                    backingSuccess = backingStore.removeAll(ownerSM, c, size);
                }
                catch (JPOXDataStoreException dse)
                {
                    JPOXLogger.PERSISTENCE.warn(LOCALISER.msg("023013", "removeAll", fieldName, dse));
                    backingSuccess = false;
                }
            }

            delegate.removeAll(c); // Remove from the delegate too
            return backingSuccess;
        }
        else
        {
            return delegate.removeAll(c);
        }
    }

    /**
     * Method to retain a Collection of elements (and remove all others).
     * @param c The collection to retain
     * @return Whether they were retained successfully.
     **/
    public synchronized boolean retainAll(java.util.Collection c)
    {
        makeDirty();

        if (useCache)
        {
            loadFromStore();
        }

        boolean modified = false;
        Iterator iter = iterator();
        while (iter.hasNext())
        {
            Object element = iter.next();
            if (!c.contains(element))
            {
                iter.remove();
                modified = true;
            }
        }
        return modified;
    }

    /**
     * The writeReplace method is called when ObjectOutputStream is preparing
     * to write the object to the stream. The ObjectOutputStream checks whether
     * the class defines the writeReplace method. If the method is defined, the
     * writeReplace method is called to allow the object to designate its
     * replacement in the stream. The object returned should be either of the
     * same type as the object passed in or an object that when read and
     * resolved will result in an object of a type that is compatible with all
     * references to the object.
     * @return the replaced object
     * @throws ObjectStreamException
     */
    protected Object writeReplace() throws ObjectStreamException
    {
        if (useCache)
        {
            loadFromStore();
            return new java.util.HashSet(delegate);
        }
        else
        {
            // TODO Cater for non-cached collection, load elements in a DB call.
            return new java.util.HashSet(delegate);
        }
    }
}
TOP

Related Classes of org.jpox.sco.Set

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.