Package org.jpox.sco.simple

Source Code of org.jpox.sco.simple.Set

/**********************************************************************
Copyright (c) 2007 Andy Jeffersonand 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:
    ...
**********************************************************************/
package org.jpox.sco.simple;

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

import org.jpox.ObjectManagerFactoryImpl;
import org.jpox.StateManager;
import org.jpox.metadata.AbstractMemberMetaData;
import org.jpox.sco.SCOCollection;
import org.jpox.sco.SCOCollectionIterator;
import org.jpox.sco.SCOMtoN;
import org.jpox.sco.SCOUtils;
import org.jpox.sco.exceptions.NullsNotAllowedException;
import org.jpox.state.FetchPlanState;
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 is the simplified form that intercepts mutators and marks the field as dirty.
*
* @version $Revision: 1.3 $
*/
public class Set extends AbstractSet
    implements SCOCollection, SCOMtoN, Cloneable, 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 boolean allowNulls;

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

    /**
     * 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
     */
    public Set(StateManager ownerSM, String fieldName, boolean allowsNulls, SetStore backingStore)
    {
        this.ownerSM = ownerSM;
        this.fieldName = fieldName;
        this.allowNulls = allowsNulls;
        if (ownerSM != null)
        {
            AbstractMemberMetaData fmd = ownerSM.getClassMetaData().getMetaDataForMember(fieldName);
            owner = ownerSM.getObject();
            fieldNumber = fmd.getAbsoluteFieldNumber();
            allowNulls = SCOUtils.allowNullsInContainer(allowNulls, fmd);
        }
    }

    /**
     * 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)
        {
            delegate = new java.util.HashSet(c); // Make copy of container rather than using same memory
        }
        else
        {
            delegate = new java.util.HashSet();
        }
        if (JPOXLogger.PERSISTENCE.isDebugEnabled())
        {
            JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023003",
                StringUtils.toJVMIDString(ownerSM.getObject()), fieldName, "" + size(),
                SCOUtils.getSCOWrapperOptionsMessage(true, false, allowNulls, false)));
        }
    }

    /**
     * Method to initialise the SCO for use.
     */
    public void initialise()
    {
        delegate = new java.util.HashSet();
        if (JPOXLogger.PERSISTENCE.isDebugEnabled())
        {
            JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023003",
                StringUtils.toJVMIDString(ownerSM.getObject()), fieldName, "" + size(),
                SCOUtils.getSCOWrapperOptionsMessage(true, false, allowNulls, false)));
        }
    }

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

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

    /**
     * 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()
    {
        // Always loaded
    }

    /**
     * Method to flush the changes to the datastore when operating in queued mode.
     * Does nothing in "direct" mode.
     */
    public void flush()
    {
        // Never queued
    }

    /**
     * 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)
    {
        // Embedded not supported so do nothing
    }

    /**
     * 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;
        }
    }

    /**
     * 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.makeDirty(fieldNumber);
        }
    }

    /**
     * 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);
    }

    // ---------------- 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()
    {
        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)
    {
        boolean success = delegate.contains(element);
        makeDirty();
        return success;
    }

    /**
     * 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)
    {
        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)
    {
        return delegate.equals(o);
    }

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

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

    /**
     * Accessor for an iterator for the Collection.
     * @return The iterator
     **/
    public synchronized Iterator iterator()
    {
        return new SCOCollectionIterator(this, ownerSM, delegate, null, true);
    }

    /**
     * Accessor for the size of the Collection.
     * @return The size
     **/
    public synchronized int size()
    {
        return delegate.size();
    }

    /**
     * Method to return the Collection as an array.
     * @return The array
     **/
    public synchronized Object[] toArray()
    {
        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[])
    {
        return delegate.toArray(a);
    }

    /**
     * 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);
        }

        boolean success = delegate.add(element);
        if (success)
        {
            makeDirty();
        }
        return success;
    }

    /**
     * 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)
    {
        boolean success = delegate.addAll(c);
        if (success)
        {
            makeDirty();
        }
        return success;
    }

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

    /**
     * Method to remove an element from the List
     * @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 List
     * @param element The Element to remove
     * @return Whether it was removed successfully.
     **/
    public synchronized boolean remove(Object element, boolean allowCascadeDelete)
    {
        boolean success = delegate.remove(element);
        if (success)
        {
            makeDirty();
        }
        return success;
    }

    /**
     * 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)
    {
        boolean success = delegate.removeAll(c);
        if (success)
        {
            makeDirty();
        }
        return success;
    }

    /**
     * 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)
    {
        boolean success = delegate.retainAll(c);
        if (success)
        {
            makeDirty();
        }
        return success;
    }

    /**
     * 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
    {
        return new java.util.HashSet(delegate);
    }
}
TOP

Related Classes of org.jpox.sco.simple.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.