Package org.jpox.metadata

Source Code of org.jpox.metadata.AbstractClassMetaData

/**********************************************************************
Copyright (c) 2005 Andy Jefferson 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:
    ...
**********************************************************************/
package org.jpox.metadata;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jpox.ClassLoaderResolver;
import org.jpox.ObjectManagerImpl;
import org.jpox.api.ApiAdapter;
import org.jpox.exceptions.ClassNotResolvedException;
import org.jpox.exceptions.JPOXException;
import org.jpox.exceptions.JPOXUserException;
import org.jpox.util.ClassUtils;
import org.jpox.util.JPOXLogger;
import org.jpox.util.Localiser;
import org.jpox.util.MacroString;
import org.jpox.util.StringUtils;
import org.jpox.util.ViewUtils;

/**
* Abstract representation of the MetaData of a class/interface.
* Has a parent PackageMetaData that can contain the metadata for several classes/interfaces.
* Is extended by ClassMetaData and InterfaceMetaData.
* Of the things that it contains the main one are the "members" which are the MetaData for
* all fields and properties that are persistable.
* @since 1.1
* @version $Revision: 1.98 $
*/
public abstract class AbstractClassMetaData extends MetaData
{
    protected static Localiser LOCALISER_API=Localiser.getInstance("org.jpox.Localisation",
        ObjectManagerImpl.class.getClassLoader());

    /** Class name */
    protected final String name;

    /** Entity name. Required by JPA1 �4.3.1 for accessing this class in queries. */
    protected String entityName;

    /** Identity-type tag value. */
    protected IdentityType identityType = IdentityType.DATASTORE;

    /** persistence-modifier tag value. */
    protected ClassPersistenceModifier persistenceModifier = null;

    /** persistence-capable-superclass tag value (deprecated). */
    protected String persistenceCapableSuperclass;

    /** objectid-class tag value. */
    protected String objectidClass;

    /** requires-extent tag value. */
    protected boolean requiresExtent = true;

    /** detachable tag value. */
    protected boolean detachable = false;

    /** embedded-only tag value. */
    protected boolean embeddedOnly = false;

    /** Catalog name (O/R mapping). */
    protected String catalog;

    /** Schema name (O/R mapping). */
    protected String schema;

    /** Table name (O/R mapping). This may be of the form "[database].[catalog].[schema].table" */
    protected String table;

    /** Full name (e.g org.jpox.MyClass) */
    protected final String fullName;

    /** Version MetaData */
    protected VersionMetaData versionMetaData;

    /** Identity MetaData */
    protected IdentityMetaData identityMetaData;

    /** Flag whether the identity was specified by the user. */
    protected boolean identitySpecified = false;

    /** Inheritance MetaData */
    protected InheritanceMetaData inheritanceMetaData;

    /** PrimaryKey MetaData */
    protected PrimaryKeyMetaData primaryKeyMetaData;

    /** EventListeners. Use a list to preserve ordering. */
    protected List listeners = null;

    /** Flag to exclude superclass listeners. */
    protected Boolean excludeSuperClassListeners = null;

    /** Flag to exclude default listeners. */
    protected Boolean excludeDefaultListeners = null;

    /** Fetch Groups for this class. Available to be used in queries and when detaching. */
    protected FetchGroupMetaData[] fetchGroupMetaData;

    /** Convenience lookup map of fetch group by the name. */
    protected Map fetchGroupMetaDataByName;

    /** Class MetaData for the Persistence-Capable superclass (if any) */
    protected AbstractClassMetaData pcSuperclassMetaData = null;

    /** Flag for whether the MetaData here is complete without annotations. Used by JPA. */
    protected boolean metaDataComplete = false;

    /** Named queries */
    protected Collection queries = null;

    /** List of query result MetaData defined for this file. */
    protected Collection queryResultMetaData = null;

    /** JoinMetaData */
    protected JoinMetaData[] joinMetaData;

    /** IndexMetaData */
    protected IndexMetaData[] indexMetaData;

    /** ForeignKeyMetaData */
    protected ForeignKeyMetaData[] foreignKeyMetaData;

    /** UniqueMetaData */
    protected UniqueMetaData[] uniqueMetaData;

    /** List of members (fields/properties). */
    protected List members = new ArrayList();

    /** The columns that are present in the datastore yet not mapped to fields in this class. */
    protected List unmappedColumns = null;

    // These fields are only used when the MetaData is read by the parser and elements are dynamically added to
    // the other elements. At initialise() they are cleared and nulled so shouldn't be used internally.

    /** List of joins */
    protected List joins = new ArrayList();

    /** List of foreign-key */
    protected List foreignKeys = new ArrayList();

    /** List of indexes */
    protected List indexes = new ArrayList();

    /** List of uniqueConstraints */
    protected List uniqueConstraints = new ArrayList();

    /** List of fetch-group */
    protected List fetchGroups = new ArrayList();

    // Fields below here are not represented in the output MetaData. They are for use internally in the operation of the system.
    // The majority are for convenience to save iterating through the fields since the fields are fixed once initialised.

    /**
     * Managed fields/properties of this class. Contains the same AbstractMemberMetaData objects as are in "members".
     * Doesnt include any overridden members which are stored separately. All fields will return true to
     * "fmd.isJdoField()".
     */
    protected AbstractMemberMetaData[] managedMembers;

    /** Fields/properties for superclasses that are overridden in this class. */
    protected AbstractMemberMetaData[] overriddenMembers;

    /** Position numbers of members mapped by the name of the field/property. */
    protected Map memberPositionsByName;

    /** Positions of all fields/properties (inc superclasses). */
    protected int[] allMemberPositions;

    /** Positions of the primary-key fields/properties (inc superclasses). */
    protected int[] pkMemberPositions;

    /** Positions of the non-primary-key fields/properties (inc superclasses). */
    protected int[] nonPkMemberPositions;

    /** Flags of the non-primary key fields/properties (inc superclasses). */
    protected boolean[] nonPkMemberFlags;

    /** Positions of the default-fetch-group fields/properties (inc superclasses). */
    protected int[] dfgMemberPositions;

    /** Flags of the default-fetch-group state for all fields/properties. */
    protected boolean[] dfgMemberFlags;

    /** Positions of the SCO mutable fields/properties (inc superclasses). */
    protected int[] scoMutableMemberPositions;

    /** Flags of the SCO mutable state for all fields/properties. */
    protected boolean[] scoMutableMemberFlags;

    /** Postions of the PersistenceCapable fields/properties (inc superclasses). */
    protected int[] persistenceCapableMemberPositions;   

    /** No of managed fields/properties in superclasses, that are inherited by this class. */
    protected int noOfInheritedManagedMembers = 0;

    /** if this PersistenceCapable class uses SingleFieldIdentity */
    protected boolean usesSingleFieldIdentityClass;

    /** number of managed fields/properties from this class plus inherited classes. */
    protected int memberCount;

    protected boolean implementationOfPersistentDefinition = false;

    // ----------------------------- Constructors ------------------------------
    /**
     * Constructor.
     * Takes the basic string information found in an XML MetaData file.
     * @param parent The package to which this class/interface belongs
     * @param name Name of class
     * @param identityType identity-type flag
     * @param objectidClass Primary key class name
     * @param requiresExtent Whether the class requires an extent
     * @param detachable Whether the class can be detached
     * @param embeddedOnly embedded-only tag
     * @param modifier persistence-modifier tag
     * @param catalog The catalog name default for this class
     * @param schema The schema name default for this class
     * @param table table to store the class in
     * @param entityName the entity name required by JPA �4.3.1
     */
    protected AbstractClassMetaData(final PackageMetaData parent,
                         final String name,
                         final String identityType,
                         final String objectidClass,
                         final String requiresExtent,
                         final String detachable,
                         final String embeddedOnly,
                         final String modifier,
                         final String persistenceCapableSuperclass,
                         final String catalog,
                         final String schema,
                         final String table,
                         final String entityName)
    {
        super(parent);

        if (name == null)
        {
            throw new JPOXUserException(LOCALISER.msg("044041","name",getPackageName(),"class"));
        }
        if (StringUtils.isWhitespace(name))
        {
            throw new InvalidMetaDataException(LOCALISER,
                "044061",parent.name);
        }

        this.name = name;
        this.fullName = ClassUtils.createFullClassName(parent.name, name);
        this.objectidClass = (StringUtils.isWhitespace(objectidClass) ? null : ClassUtils.createFullClassName(parent.name, objectidClass));
        this.identityType = IdentityType.getIdentityType(identityType);
        this.requiresExtent = (requiresExtent != null && requiresExtent.equalsIgnoreCase("false")) ? false : true;
        this.detachable = (detachable != null && detachable.equalsIgnoreCase("true")) ? true : false;
        this.embeddedOnly = (embeddedOnly != null && embeddedOnly.equalsIgnoreCase("true")) ? true : false;
        this.catalog = (StringUtils.isWhitespace(catalog) ? null : catalog);
        this.schema = (StringUtils.isWhitespace(schema) ? null : schema);
        this.table = (StringUtils.isWhitespace(table) ? null : table);
        this.persistenceModifier = ClassPersistenceModifier.getClassPersistenceModifier(modifier);
        this.entityName = (entityName != null ? entityName : null);
        this.persistenceCapableSuperclass = (StringUtils.isWhitespace(persistenceCapableSuperclass) ?
            null : ClassUtils.createFullClassName(parent.name, persistenceCapableSuperclass));
    }

    /** Implementation of "persistent-interface" needing table setting from superclass. */
    protected transient boolean persistentInterfaceImplNeedingTableFromSuperclass = false;

    /** Implementation of "persistent-interface" needing table setting from subclass. */
    protected transient boolean persistentInterfaceImplNeedingTableFromSubclass = false;

    /**
     * Constructor for creating the ClassMetaData for an implementation of a "persistent-interface".
     * @param imd MetaData for the "persistent-interface"
     * @param implClassName Name of the implementation class
     * @param copyMembers Whether to copy the fields/properties of the interface too
     */
    public AbstractClassMetaData(InterfaceMetaData imd, String implClassName, boolean copyMembers)
    {
        this((PackageMetaData)imd.parent, implClassName, imd.identityType.toString(), imd.objectidClass,
            imd.requiresExtent ? "true":"false",
            imd.detachable ? "true":"false",
            imd.embeddedOnly ? "true":"false",
            ClassPersistenceModifier.PERSISTENCE_CAPABLE.toString(),
            null, // Ignore class inheritance since we are just implementing this interface
            imd.catalog,
            imd.schema,
            imd.table,
            imd.entityName);
        implementationOfPersistentDefinition = true;

        if (copyMembers)
        {
            copyMembersFromInterface(imd);
        }

        setVersionMetaData(imd.versionMetaData);
        setIdentityMetaData(imd.identityMetaData);
        setPrimaryKeyMetaData(imd.primaryKeyMetaData);

        if (imd.inheritanceMetaData != null)
        {
            if (imd.inheritanceMetaData.getStrategyValue() == InheritanceStrategy.SUPERCLASS_TABLE)
            {
                // Flag the table as requiring setting based on the next superclass
                persistentInterfaceImplNeedingTableFromSuperclass = true;
            }
            else if (imd.getInheritanceMetaData().getStrategyValue() == InheritanceStrategy.SUBCLASS_TABLE)
            {
                // Flag the table as requiring setting based on the next subclass
                persistentInterfaceImplNeedingTableFromSubclass = true;
            }

            InheritanceMetaData inhmd = new InheritanceMetaData(this,InheritanceStrategy.NEW_TABLE.toString());
            if (imd.inheritanceMetaData.getStrategyValue() == InheritanceStrategy.SUPERCLASS_TABLE)
            {
                AbstractClassMetaData acmd = imd.getSuperAbstractClassMetaData();
                while (acmd != null)
                {
                    if (acmd.getInheritanceMetaData() != null)
                    {
                        if (acmd.getInheritanceMetaData().getStrategyValue()==InheritanceStrategy.NEW_TABLE)
                        {
                            if (acmd.getInheritanceMetaData().getDiscriminatorMetaData() != null)
                            {
                                inhmd.setDiscriminatorMetaData(new DiscriminatorMetaData(inhmd,acmd.getInheritanceMetaData().getDiscriminatorMetaData()));
                            }
                            inhmd.setJoinMetaData(acmd.getInheritanceMetaData().getJoinMetaData());
                            break;
                        }
                    }
                    acmd = acmd.getSuperAbstractClassMetaData();
                }
            }
            else if (imd.inheritanceMetaData.getStrategyValue() == InheritanceStrategy.NEW_TABLE)
            {
              if (imd.getInheritanceMetaData().getDiscriminatorMetaData() != null)
              {
                inhmd.setDiscriminatorMetaData(new DiscriminatorMetaData(inhmd,imd.getInheritanceMetaData().getDiscriminatorMetaData()));
              }
              inhmd.setJoinMetaData(imd.getInheritanceMetaData().getJoinMetaData());
            }
            setInheritanceMetaData(inhmd);
        }
       
        if (imd.joinMetaData != null)
        {
            for (int i=0;i<imd.joinMetaData.length;i++)
            {
                addJoin(imd.joinMetaData[i]);
            }
        }
        if (imd.foreignKeyMetaData != null)
        {
            for (int i=0;i<imd.foreignKeyMetaData.length;i++)
            {
                addForeignKey(imd.foreignKeyMetaData[i]);
            }
        }
        if (imd.indexMetaData != null)
        {
            for (int i=0;i<imd.indexMetaData.length;i++)
            {
                addIndex(imd.indexMetaData[i]);
            }
        }
        if (imd.uniqueMetaData != null)
        {
            for (int i=0;i<imd.uniqueMetaData.length;i++)
            {
                addUniqueConstraint(imd.uniqueMetaData[i]);
            }
        }
        if (imd.fetchGroupMetaData != null)
        {
            for (int i=0;i<imd.fetchGroupMetaData.length;i++)
            {
                addFetchGroup(imd.fetchGroupMetaData[i]);
            }
        }
        if (queries != null)
        {
            Iterator iter = queries.iterator();
            {
                addQuery((QueryMetaData)iter.next());
            }
        }

        if (imd.listeners != null)
        {
            if (listeners == null)
            {
                listeners = new ArrayList();
            }
            listeners.addAll(imd.listeners);
        }
    }

    /**
     * Constructor for creating the ClassMetaData for an implementation of a "persistent-abstract-class".
     * @param cmd MetaData for the implementation of the "persistent-abstract-class"
     * @param implClassName Name of the implementation class
     */
    public AbstractClassMetaData(ClassMetaData cmd, String implClassName)
    {
        this((PackageMetaData)cmd.parent, implClassName, null, null,
            cmd.requiresExtent ? "true":"false",
            cmd.detachable ? "true":"false",
            cmd.embeddedOnly ? "true":"false",
            ClassPersistenceModifier.PERSISTENCE_CAPABLE.toString(),
            cmd.getFullClassName(),
            cmd.catalog,
            cmd.schema,
            cmd.table,
            cmd.entityName);
        implementationOfPersistentDefinition = true;

        // Mark all artificial fields (added in implementing the abstract class) as non-persistent
        for (int i=0; i<cmd.getMemberCount(); i++)
        {
            FieldMetaData fmd = new FieldMetaData(this, cmd.getMetaDataForManagedMemberAtAbsolutePosition(i));
            fmd.persistenceModifier = FieldPersistenceModifier.NONE;
            fmd.primaryKey = Boolean.FALSE;
            fmd.defaultFetchGroup = Boolean.FALSE;
            addMember(fmd);
        }
    }

    /**
     * Return whether this MetaData is for an implementation of a persistent definition.
     * This could be an implementation of a persistent interface or a persistent abstract-class.
     * @return Whether this is an implementation
     */
    public boolean isImplementationOfPersistentDefinition()
    {
        return implementationOfPersistentDefinition;
    }

    /**
     * Convenience method to copy the properties from an existing interface.
     * Adds FieldMetaData for each PropertyMetaData on the persistent-interface.
     * @param imd The interface that we copy from
     */
    protected void copyMembersFromInterface(InterfaceMetaData imd)
    {
        for (int i=0; i<imd.getMemberCount(); i++)
        {
            // generate FieldMetaData out of PropertyMetaData
            FieldMetaData fmd = new FieldMetaData(this, imd.getMetaDataForManagedMemberAtAbsolutePosition(i));
            addMember(fmd);
        }
    }

    /**
     * Method to check whether the Meta-Data has been initialised.
     * @throws JDOFatalInternalException Thrown if the Meta-Data hasn't been initialised.
     **/
    protected void checkInitialised()
    {
        if (!isInitialised())
        {
            throw new JPOXException(LOCALISER.msg("044069",fullName)).setFatal();
        }
    }

    /**
     * Method to check whether the Meta-Data has been populated.
     * @throws JPOXException Thrown if the Meta-Data hasn't been populated.
     **/
    protected void checkPopulated()
    {
        if (!isPopulated() && !isInitialised())
        {
            throw new JPOXException(LOCALISER.msg("044070",fullName)).setFatal();
        }
    }

    /**
     * Load the persistent interface/class
     * @param clr the ClassLoader
     * @param primary the primary ClassLoader to use (or null)
     * @return the loaded class
     */
    protected Class loadClass(ClassLoaderResolver clr, ClassLoader primary)
    {
        // No class loader, so use default
        if (clr == null)
        {
            JPOXLogger.METADATA.warn(LOCALISER.msg("044067",fullName));
            clr = getMetaDataManager().getOMFContext().getClassLoaderResolver(null);
        }
   
        // Load the class we are modelling
        Class cls;
        try
        {
            cls = clr.classForName(fullName,primary,false);
        }
        catch (ClassNotResolvedException cnre)
        {
            JPOXLogger.METADATA.error(LOCALISER.msg("044080",fullName));
            throw new InvalidMetaDataException(LOCALISER,
                "044080",
                fullName);
        }
        if( cls == null )
        {
            JPOXLogger.METADATA.error(LOCALISER.msg("044080",fullName));
            throw new InvalidMetaDataException(LOCALISER,
                "044080",
                fullName);
        }
        return cls;
    }

    /**
     * Determines the identity based on MetaData defaults or user defined MetaData
     */
    protected void determineIdentity()
    {
        // Provide a default identity type if not supplied
        if (this.identityType == null)
        {
            if (objectidClass != null)
            {
                // PK provided so we use application-identity
                identityType = IdentityType.APPLICATION;
            }
            else
            {
                int noOfPkKeys = 0;
                Iterator memberIter = members.iterator();
                while (memberIter.hasNext())
                {
                    AbstractMemberMetaData mmd = (AbstractMemberMetaData)memberIter.next();
                    if (mmd.isPrimaryKey())
                    {
                        noOfPkKeys++;
                    }
                }
                if (noOfPkKeys == 1)
                {
                    // 1 PK so we use application-identity (SingleFieldIdentity)
                    identityType = IdentityType.APPLICATION; // SingleFieldIdentity
                }
                else
                {
                    // Use datastore-identity
                    identityType = IdentityType.DATASTORE;
                }
            }
        }
    }

    /**
     * Determine the super PersistenceCapable class.
     * The persistence-capable-superclass attribute is deprecated for JDO2.0.
     * The attribute will be ignored so metadata files from previous releases can be used.
     * The persistenceCapableSuperclass we use will be retrieved from the class itself.
     * @param clr The ClassLoaderResolver
     * @param cls This class
     * @throws InvalidMetaDataException if the declared <code>persistence-capable-superclass</code> super class
     *                                  cannot be loaded by the <code>clr</code>.
     * @throws InvalidMetaDataException if the declared <code>persistence-capable-superclass</code> has
     *                                  no reachable MetaData
     */
    protected void determineSuperClassName(ClassLoaderResolver clr, Class cls)
    {
        String realPcSuperclassName = null;

        Collection superclasses = null;
        if (cls.isInterface())
        {
            superclasses = ClassUtils.getSuperinterfaces(cls);
        }
        else
        {
            superclasses = ClassUtils.getSuperclasses(cls);
        }

        if (!superclasses.isEmpty())
        {
            Iterator superclassesIter = superclasses.iterator();
            while (superclassesIter.hasNext())
            {
                Class superclass = (Class) superclassesIter.next();
                AbstractClassMetaData superCmd = getMetaDataManager().getMetaDataForClassInternal(superclass, clr);
                if (superCmd != null && superCmd.getPersistenceModifier() == ClassPersistenceModifier.PERSISTENCE_CAPABLE)
                {
                    realPcSuperclassName = superclass.getName();
                    break;
                }
            }
        }

        if (persistenceCapableSuperclass != null && !persistenceCapableSuperclass.equals(realPcSuperclassName))
        {
            // Valifies the defined persistenceCapableSuperclass
            try
            {
                AbstractClassMetaData superCmd = getMetaDataManager().getMetaDataForClassInternal(clr.classForName(persistenceCapableSuperclass), clr);
                if (superCmd == null || superCmd.getPersistenceModifier() != ClassPersistenceModifier.PERSISTENCE_CAPABLE)
                {
                    throw new InvalidMetaDataException(LOCALISER, "044083", name,
                        persistenceCapableSuperclass);
                }
            }
            catch (ClassNotResolvedException cnre)
            {
                throw new InvalidMetaDataException(LOCALISER, "044088", name,
                    persistenceCapableSuperclass);
            }
            if (realPcSuperclassName != null)
            {
                throw new InvalidMetaDataException(LOCALISER, "044087", name, realPcSuperclassName,
                    persistenceCapableSuperclass);
            }
            else
            {
                // The defined persistenceCapableSuperclass could NOT have been a superclass
                // of this class, otherwise it would have been equal to the realPcSuperclassName.
                throw new InvalidMetaDataException(LOCALISER, "044082", name,
                    persistenceCapableSuperclass);
            }
        }
        if (persistenceCapableSuperclass == null && realPcSuperclassName != null)
        {
            persistenceCapableSuperclass = realPcSuperclassName;
            if (JPOXLogger.METADATA.isDebugEnabled())
            {
                JPOXLogger.METADATA.debug(LOCALISER.msg("044089", name, persistenceCapableSuperclass));
            }
        }
        validateSuperClass(clr, cls, superclasses);
    }

    /**
     * Check if the previously determined super class implements PersistenceCapable and has
     * reachable MetaData file. The super class MetaData is populated if not yet populated or initilised.
     * @param clr the ClassLoaderResolver
     * @param cls This class
     * @param superclasses A List of super classes of this class, starting from the least derived super class up to the root class
     * @throws InvalidMetaDataException if the super class cannot be loaded by the <code>clr</code>.
     * @throws InvalidMetaDataException if the declared <code>persistence-capable-superclass</code> is not
     *                                  actually assignable from <code>cls</code>
     * @throws InvalidMetaDataException if any of the super classes implements <code>PersistenceCapable</code> interface,
     *                                  but the MetaData says that class is not persistent.
     */
    private void validateSuperClass(ClassLoaderResolver clr, Class cls, Collection superclasses)
    {
        // "persistence-capable-superclass"
        // Check that the class can be loaded, and is a true superclass
        if (persistenceCapableSuperclass != null)
        {
            Class pcsc=null;
            try
            {
                // Load using same class loader resolver as this class
                pcsc = clr.classForName(persistenceCapableSuperclass);
            }
            catch (ClassNotResolvedException cnre)
            {
                throw new InvalidMetaDataException(LOCALISER,
                    "044081",
                    name,persistenceCapableSuperclass);
            }

            if (persistenceCapableSuperclass.equals(fullName) ||
                !(pcsc.isAssignableFrom(cls)))
            {
                throw new InvalidMetaDataException(LOCALISER,
                    "044082",
                    name,persistenceCapableSuperclass);
            }

            // Retrieve the Meta-Data for the superclass
            if (getMetaDataManager() != null)
            {
                // JPOX normal operation will have a MetaDataManager and so we
                // can ask that for the MetaData of the superclass.
                pcSuperclassMetaData = getMetaDataManager().getMetaDataForClassInternal(pcsc, clr);
                if (pcSuperclassMetaData == null)
                {
                    // Superclass isn't persistence capable since no MetaData
                    // could be found.
                    throw new InvalidMetaDataException(LOCALISER,
                        "044083",
                        name,persistenceCapableSuperclass);
                }
            }
            else
            {
                // The enhancer doesn't need MetaDataManager so we just
                // navigate up to the FileMetaData and find it.
                // NOTE : assumes that the class is specified in the same file
                String superclass_pkg_name=persistenceCapableSuperclass.substring(0,persistenceCapableSuperclass.lastIndexOf('.'));
                PackageMetaData pmd=getPackageMetaData().getFileMetaData().getPackage(superclass_pkg_name);
                if (pmd != null)
                {
                    String superclass_class_name=persistenceCapableSuperclass.substring(persistenceCapableSuperclass.lastIndexOf('.')+1);
                    pcSuperclassMetaData = pmd.getClass(superclass_class_name);
                }
            }
            if (pcSuperclassMetaData == null)
            {
                throw new InvalidMetaDataException(LOCALISER,
                    "044084",
                                        name, persistenceCapableSuperclass);
            }
            if (!pcSuperclassMetaData.isPopulated() &&
                !pcSuperclassMetaData.isInitialised())
            {
                // Populate the superclass since we will be needing it
                pcSuperclassMetaData.populate(clr,cls.getClassLoader());
            }
        }
        else
        {
            // Check that none of our real superclasses is PersistenceCapable since this
            // class hasn't declared a PC superclass
            if (!superclasses.isEmpty())
            {
                Iterator superclassesIter = superclasses.iterator();
                while (superclassesIter.hasNext())
                {
                    Class superclass = (Class)superclassesIter.next();
                    AbstractClassMetaData superCmd = getMetaDataManager().getMetaDataForClassInternal(superclass, clr);
                    if (superCmd != null && superCmd.getPersistenceModifier() == ClassPersistenceModifier.PERSISTENCE_CAPABLE)
                    {
                        throw new InvalidMetaDataException(LOCALISER, "044091",
                            fullName, superclass.getName());
                    }
                }
            }
        }
    }   
   
    /**
     * Check for conflicts on super class and this class MetaData identity
     * @throws InvalidMetaDataException if the user tries to overwrite a super class identity / strategy
     */
    protected void validateUserInputForIdentity()
    {
        // Check that the user isn't trying to override the datastore-identity strategy!
        if (pcSuperclassMetaData != null)
        {
            AbstractClassMetaData baseCmd = getBaseAbstractClassMetaData();
            IdentityMetaData imd = baseCmd.getIdentityMetaData();
            if (baseCmd.identitySpecified && identitySpecified &&
                imd != null && imd.getValueStrategy() != null &&
                identityMetaData != null && identityMetaData.getValueStrategy() != null &&
                identityMetaData.getValueStrategy() != imd.getValueStrategy())
            {
                throw new InvalidMetaDataException(LOCALISER,
                    "044094",
                    fullName, identityMetaData.getValueStrategy(), imd.getValueStrategy());
            }
        }
    }
   
    /**
     * Convenience accessor for the AbstractClassMetaData of the base object in this hierarchy.
     * @return The AbstractClassMetaData for the base object.
     */
    public AbstractClassMetaData getBaseAbstractClassMetaData()
    {
        if (pcSuperclassMetaData != null)
        {
            return pcSuperclassMetaData.getBaseAbstractClassMetaData();
        }
        else
        {
            return this;
        }
    }
   
    /**
     * Inherit detach settings from super classes. This class is forced to be detachable if the super classes is.
     */
    protected void inheritDetachableSettings()
    {
        // "persistence-capable-superclass"
        // Check that the class can be loaded, and is a true superclass
        if (persistenceCapableSuperclass != null)
        {
            if (!isDetachable() && pcSuperclassMetaData.isDetachable())
            {
                // If the superclass is detachable then we are by definition since we extend
                detachable = true;
            }
        }
    }
   
    /**
     * Inherit the identity definition from super classes.
     * @throws InvalidMetaDataException if the MetaData of this class conflicts with super classes definition
     */
    protected void inheritIdentity()
    {
        // "persistence-capable-superclass"
        // Check that the class can be loaded, and is a true superclass
        if (persistenceCapableSuperclass != null)
        {
            // Class has superclass, yet has objectid-class defined! ops, this might result in user errors
            if (objectidClass != null)
            {
                String superObjectIdClass = pcSuperclassMetaData.getObjectidClass();
                if (superObjectIdClass == null || !objectidClass.equals(superObjectIdClass))
                {
                    throw new InvalidMetaDataException(LOCALISER,
                      "044085",
                                        name, persistenceCapableSuperclass);
                }
                // by default users should only specify the object-id class in the root persistent class
                JPOXLogger.METADATA.warn(LOCALISER.msg("044086",
                    name, persistenceCapableSuperclass));
            }
            else
            {
                // get the objectid class from superclass
                this.objectidClass = pcSuperclassMetaData.getObjectidClass();
            }

            if (this.identityType == null)
            {
                this.identityType = pcSuperclassMetaData.getIdentityType();
            }

            // Superclass identityType must be the same as this classes identityType
            if (!this.identityType.equals(pcSuperclassMetaData.getIdentityType()))
            {
                // We can't change the identity type from what was specified in the base class
                throw new InvalidMetaDataException(LOCALISER,
                        "044093",
                        fullName);
            }
        }
    }   
   
    /**
     * Utility to add a defaulted PropertyMetaData to the class.
     * Provided as a method since then any derived classes can override it.
     * @param name name of property
     * @return the new PropertyMetaData
     */
    protected AbstractMemberMetaData newDefaultedProperty(String name)
    {
        return new PropertyMetaData(this, name);
    }

    /**
     * Check if the inheritance MetaData is credible.
     * @throws InvalidMetaDataException if the strategy is superclass-table, yet there are no super class
     * @throws InvalidMetaDataException if the strategy is superclass-table, yet the super class has not
     *                                  specified a discriminator
     * @throws InvalidMetaDataException if the strategy is superclass-table and discriminator is "value-map",
     *                                  yet no value for the discriminator has been specified
     */
    protected void validateUserInputForInheritanceMetaData()
    {
        // Check that the inheritance strategy is credible
        if (inheritanceMetaData != null)
        {
            // Check validity of inheritance strategy and discriminator
            if (inheritanceMetaData.getStrategyValue() == InheritanceStrategy.SUPERCLASS_TABLE)
            {
                AbstractClassMetaData superCmd = getClassManagingTableForClass(this);
                if (superCmd == null)
                {
                    // We need a superclass table yet there is no superclass with its own table!
                    throw new InvalidMetaDataException(LOCALISER, "044099", fullName);
                }

                DiscriminatorMetaData superDismd = superCmd.getInheritanceMetaData().getDiscriminatorMetaData();
                if (superDismd == null)
                {
                    // If we are using "superclass-table" then the superclass should have specified the discriminator.
                    throw new InvalidMetaDataException(LOCALISER, "044100",
                        fullName, superCmd.fullName);
                }

                DiscriminatorMetaData dismd = inheritanceMetaData.getDiscriminatorMetaData();
                if (superDismd.getStrategy() == DiscriminatorStrategy.VALUE_MAP &&
                    (dismd == null || dismd.getValue() == null))
                {
                    // If we are using "superclass-table" and the discriminator uses "value-map" then we must specify a value
                    throw new InvalidMetaDataException(LOCALISER, "044102",
                        fullName, superCmd.fullName, superDismd.getColumnName());
                }
            }
        }
    }

    /**
     * Convenience method to validate the specified "unmapped" columns.
     * @throws InvalidMetaDataException if a column is specified without its name.
     */
    protected void validateUnmappedColumns()
    {
        // Validate any unmapped columns
        if (unmappedColumns != null && unmappedColumns.size() > 0)
        {
            Iterator unmappedIter = unmappedColumns.iterator();
            while (unmappedIter.hasNext())
            {
                ColumnMetaData colmd = (ColumnMetaData)unmappedIter.next();
                if (colmd.getName() == null)
                {
                    throw new InvalidMetaDataException(LOCALISER, "044119",
                        getFullClassName());
                }
                if (colmd.getJdbcType() == null)
                {
                    throw new InvalidMetaDataException(LOCALISER, "044120",
                        colmd.getName(), getFullClassName());
                }
            }
        }
    }

    /**
     * Utility to navigate up to superclasses to find the next class with its own table.
     * @param cmd AbstractClassMetaData of the class
     * @return The AbstractClassMetaData of the class managing its own table
     */
    private static AbstractClassMetaData getClassManagingTableForClass(AbstractClassMetaData cmd)
    {
        if (cmd == null)
        {
            return null;
        }

        InheritanceMetaData imd = cmd.getInheritanceMetaData();
        if (imd == null)
        {
            return cmd;
        }
        else if (imd.getStrategyValue() == InheritanceStrategy.NEW_TABLE)
        {
            return cmd;
        }
        else if (imd.getStrategyValue() == InheritanceStrategy.SUPERCLASS_TABLE)
        {
            return getClassManagingTableForClass(cmd.getSuperAbstractClassMetaData());
        }
        return null;
    }   

    /**
     * Accessor for the Meta-Data for the superclass of this class.
     * @return MetaData of the superclass
     */
    public AbstractClassMetaData getSuperAbstractClassMetaData()
    {
        // checkInitialised();

        return pcSuperclassMetaData;
    }   
   
    /**
     * Convenience accessor for the discriminator strategy applying to this class.
     * This is specified on the class managing the table if at all.
     * @return The discriminator strategy
     */
    public final DiscriminatorStrategy getDiscriminatorStrategy()
    {
        if (inheritanceMetaData == null)
        {
            return null;
        }
        else if (inheritanceMetaData.getStrategyValue() == InheritanceStrategy.NEW_TABLE)
        {
            if (inheritanceMetaData.getDiscriminatorMetaData() != null)
            {
                return inheritanceMetaData.getDiscriminatorMetaData().getStrategy();
            }
            else
            {
                // Not specified.
                return null;
            }
        }
        else if (getSuperAbstractClassMetaData() != null)
        {
            return getSuperAbstractClassMetaData().getDiscriminatorStrategy();
        }
        else
        {
            // Unknown!
            return null;
        }
    }   

    /**
     * Determine the object id class
     * @param clr the ClassLoader
     * @throws InvalidMetaDataException if the class 0 or more that one primary key field and no <code>objectid-class</code>
     *                                  has been declared in the MetaData
     * @throws InvalidMetaDataException if the <code>objectid-class</code> has not been set and the primary key field does
     *                                  not match a supported SingleFieldIdentity
     * @throws InvalidMetaDataException if the identity type is APPLICATION but not primary key fields have been set
     * @throws InvalidMetaDataException if the <code>objectid-class</code> cannot be loaded by the <code>clr</code>                                                                    
     */
    protected void determineObjectIdClass(ClassLoaderResolver clr)
    {
        ApiAdapter api = getMetaDataManager().getApiAdapter();

        // Update "objectid-class" if required yet not specified
        if (objectidClass == null && persistenceCapableSuperclass == null && identityType == IdentityType.APPLICATION)
        {
            int no_of_pk_fields = 0;
            AbstractMemberMetaData fmd_pk = null;
            Iterator fields_pk_iter=members.iterator();
            while (fields_pk_iter.hasNext())
            {
                AbstractMemberMetaData fmd=(AbstractMemberMetaData)fields_pk_iter.next();
                if (fmd.isPrimaryKey())
                {
                    fmd_pk = fmd;
                    no_of_pk_fields++;
                }
            }

            // Check for more than 1 field
            if (no_of_pk_fields > 1 || no_of_pk_fields == 0)
            {
                JPOXLogger.METADATA.error(LOCALISER.msg("044065", fullName, "" + no_of_pk_fields));
                throw new InvalidMetaDataException(LOCALISER, "044065", fullName, "" + no_of_pk_fields);
            }

            // Assign associated SingleField identity class
            Class pk_type = fmd_pk.getType();
            if (Byte.class.isAssignableFrom(pk_type) ||
                byte.class.isAssignableFrom(pk_type))
            {
                objectidClass = api.getSingleFieldIdentityClassNameForByte();
            }
            else if (Character.class.isAssignableFrom(pk_type) ||
                     char.class.isAssignableFrom(pk_type))
            {
                objectidClass = api.getSingleFieldIdentityClassNameForChar();
            }
            else if (Integer.class.isAssignableFrom(pk_type) ||
                     int.class.isAssignableFrom(pk_type))
            {
                objectidClass = api.getSingleFieldIdentityClassNameForInt();
            }
            else if (Long.class.isAssignableFrom(pk_type) ||
                     long.class.isAssignableFrom(pk_type))
            {
                objectidClass = api.getSingleFieldIdentityClassNameForLong();
            }
            else if (Short.class.isAssignableFrom(pk_type) ||
                     short.class.isAssignableFrom(pk_type))
            {
                objectidClass = api.getSingleFieldIdentityClassNameForShort();
            }
            else if (String.class.isAssignableFrom(pk_type))
            {
                objectidClass = api.getSingleFieldIdentityClassNameForString();
            }
            else if (Object.class.isAssignableFrom(pk_type))
            {
                objectidClass = api.getSingleFieldIdentityClassNameForObject();
            }
            else
            {
                JPOXLogger.METADATA.error(LOCALISER.msg("044066", fullName, pk_type.getName()));
                throw new InvalidMetaDataException(LOCALISER, "044066", fullName, pk_type.getName());
            }
            JPOXLogger.METADATA.info(LOCALISER.msg("044064", fullName, objectidClass));
        }

        // Check no of primary key fields (inc superclass)
        int no_of_pk_fields = getNoOfPopulatedPKMembers();
        if (no_of_pk_fields == 0 && identityType == IdentityType.APPLICATION)
        {
            // No primary key fields found (even in superclasses)
            throw new InvalidMetaDataException(LOCALISER,
                "044077",
                fullName,objectidClass);
        }

        // Update "objectid-class" since has been specified.
        // Only check at the least derived pc class
        if (objectidClass != null && getPersistenceCapableSuperclass() == null)
        {
            Class obj_cls = null;
            try
            {
                // Load the class, using the same class loader resolver as this class
                obj_cls=clr.classForName(objectidClass);
            }
            catch (ClassNotResolvedException cnre)
            {
                // ObjectIdClass not found
                throw new InvalidMetaDataException(LOCALISER,
                    "044079",
                    fullName,objectidClass);
            }

            boolean validated = false;
            Set errors = new HashSet();
            try
            {
                // Check against the API Adapter in use for this MetaData
                if (api.isValidPrimaryKeyClass(obj_cls, this, clr, no_of_pk_fields))
                {
                    validated = true;
                }
            }
            catch (JPOXException ex)
            {
                errors.add(ex);
            }
            if (!validated)
            {
                // Why is this wrapping all exceptions into 1 single exception?
                // This needs coordinating with the test expectations in the enhancer unit tests.
                throw new JPOXUserException(LOCALISER_API.msg("019016", obj_cls.getName()),
                    (Throwable[]) errors.toArray(new Throwable[errors.size()]));
            }
        }
    }

    /**
     * Method to provide the details of the class being represented by this
     * MetaData. This can be used to firstly provide defaults for attributes
     * that aren't specified in the MetaData, and secondly to report any errors
     * with attributes that have been specifed that are inconsistent with the
     * class being represented.
     * <P>
     * This method must be invoked by subclasses during populate operations 
     * </P>
     * @param clr ClassLoaderResolver to use in loading any classes
     * @param primary the primary ClassLoader to use (or null)
     */
    abstract public void populate(ClassLoaderResolver clr,ClassLoader primary);

    /**
     * Method to initialise the sub-objects of this class metadata.
     * If populate() is going to be used it should be used BEFORE calling this method.
     * Subclasses must overwrite this method and invoke this
     */
    public abstract void initialise();

    /**
     * Impose a default inheritance strategy when one is not already specified.
     * Uses the PMF property for defaultInheritanceStrategy and works to the JDO2 spec etc.
     */
    protected void determineInheritanceMetaData()
    {
        if (inheritanceMetaData == null)
        {
            // User hasnt specified the <inheritance> for the class
            if (pcSuperclassMetaData != null)
            {
                AbstractClassMetaData baseCmd = getBaseAbstractClassMetaData();
                if (baseCmd.getInheritanceMetaData() != null &&
                    baseCmd.getInheritanceMetaData().getStrategyForTree() != null)
                {
                    // A strategy for the full inheritance tree is defined (like in JPA) so use that
                    String treeStrategy = baseCmd.getInheritanceMetaData().getStrategyForTree();
                    if (treeStrategy.equals("JOINED"))
                    {
                        inheritanceMetaData = new InheritanceMetaData(this,
                            InheritanceStrategy.NEW_TABLE.toString());
                        return;
                    }
                    else if (treeStrategy.equals("SINGLE_TABLE"))
                    {
                        inheritanceMetaData = new InheritanceMetaData(this,
                            InheritanceStrategy.SUPERCLASS_TABLE.toString());
                        return;
                    }
                    else if (treeStrategy.equals("TABLE_PER_CLASS"))
                    {
                        inheritanceMetaData = new InheritanceMetaData(this,
                            InheritanceStrategy.COMPLETE_TABLE.toString());
                        return;
                    }
                }

                if (baseCmd.getInheritanceMetaData() != null &&
                    baseCmd.getInheritanceMetaData().getStrategyValue() == InheritanceStrategy.COMPLETE_TABLE)
                {
                    // Root class in tree is set to use COMPLETE_TABLE so all subclasses have own table
                    inheritanceMetaData = new InheritanceMetaData(this, InheritanceStrategy.COMPLETE_TABLE.toString());
                }
                else if (pcSuperclassMetaData.getInheritanceMetaData() != null &&
                    pcSuperclassMetaData.getInheritanceMetaData().getStrategyValue() == InheritanceStrategy.SUBCLASS_TABLE)
                {
                    // Superclass exists but needs our table so have own table
                    inheritanceMetaData = new InheritanceMetaData(this, InheritanceStrategy.NEW_TABLE.toString());
                }
                else
                {
                    // Superclass exists and has a table or uses its superclass, so default based on that
                    if (getMetaDataManager().getOMFContext().getPersistenceConfiguration().getStringProperty("org.jpox.defaultInheritanceStrategy").equalsIgnoreCase("JPOX"))
                    {
                        // JPOX 1.0 behaviour
                        inheritanceMetaData = new InheritanceMetaData(this, InheritanceStrategy.NEW_TABLE.toString());
                    }
                    else
                    {
                        // JDO2 behaviour
                        inheritanceMetaData = new InheritanceMetaData(this, InheritanceStrategy.SUPERCLASS_TABLE.toString());
                    }
                }
            }
            else
            {
                inheritanceMetaData = new InheritanceMetaData(this,InheritanceStrategy.NEW_TABLE.toString());
            }
            return;
        }

        if (inheritanceMetaData.getStrategyValue() == null)
        {
            // User has included <inheritance> but not set the strategy, so populate it for them
            if (pcSuperclassMetaData != null)
            {
                AbstractClassMetaData baseCmd = getBaseAbstractClassMetaData();
                if (baseCmd.getInheritanceMetaData() != null &&
                    baseCmd.getInheritanceMetaData().getStrategyValue() == InheritanceStrategy.COMPLETE_TABLE)
                {
                    // Root class in tree is set to use COMPLETE_TABLE so all subclasses have own table
                    inheritanceMetaData.strategy = InheritanceStrategy.COMPLETE_TABLE;
                }
                if (pcSuperclassMetaData.getInheritanceMetaData() != null &&
                    pcSuperclassMetaData.getInheritanceMetaData().getStrategyValue() == InheritanceStrategy.SUBCLASS_TABLE)
                {
                    // Superclass exists but needs our table so have own table
                    inheritanceMetaData.strategy = InheritanceStrategy.NEW_TABLE;
                }
                else
                {
                    // Superclass exists and has a table or uses its superclass, so default based on that
                    if (getMetaDataManager().getOMFContext().getPersistenceConfiguration().getStringProperty("org.jpox.defaultInheritanceStrategy").equalsIgnoreCase("JPOX"))
                    {
                        // JPOX 1.0 behaviour
                        inheritanceMetaData.strategy = InheritanceStrategy.NEW_TABLE;
                    }
                    else
                    {
                        // JDO2 behaviour
                        inheritanceMetaData.strategy = InheritanceStrategy.SUPERCLASS_TABLE;
                    }
                }
            }
            else
            {
                inheritanceMetaData.strategy = InheritanceStrategy.NEW_TABLE;
            }
        }
    }

    /**
     * Check usage of deprecated MetaData
     * @throws InvalidMetaDataException if deprecated MetaData is used
     */
    protected void validateDeprecatedMetaData()
    {
        // "use-poid-generator" was used in JPOX 1.0, and 1.1 until beta-2. Now replaced by "value-strategy".
        if (hasExtension("use-poid-generator"))
        {
            throw new InvalidMetaDataException(LOCALISER, "044092", fullName);
        }
    }
   
    /**
     * Method to return the ClassMetaData records for classes referenced
     * by this object. This adds the entries to orderedCMDs ordered by
     * dependency, and to referencedCMDs for fast lookups.
     * <p>
     * Uses recursion to add all referenced ClassMetaData for any fields,
     * objectid classes, superclasses, and JPOX extension RDBMS "views".
     * </p>
     * <p>
     * This is the entry point for this process, and provides the core of the
     * "persistence-by-reachability" concept.
     * </p>
     * @param orderedCMDs List of ordered ClassMetaData objects (added to).
     * @param referencedCMDs Set of all ClassMetaData objects (added to).
     * @param dba_vendor_id Vendor ID of the DBA. Used for view addition.
     * @param clr the ClassLoaderResolver
     */
    void getReferencedClassMetaData(final List orderedCMDs,
                                    final Set referencedCMDs,
                                    final String dba_vendor_id,
                                    final ClassLoaderResolver clr)
    {
        Map viewReferences = new HashMap();
        getReferencedClassMetaData(orderedCMDs,referencedCMDs,dba_vendor_id,viewReferences,clr);
    }

    /**
     * Method to return the ClassMetaData for classes referenced by this
     * object. This method does the actual work of addition.
     * @param orderedCMDs List of ordered ClassMetaData objects (added to).
     * @param referencedCMDs Set of all ClassMetaData objects (added to).
     * @param dba_vendor_id Vendor ID of the DBA. Used for view addition.
     * @param viewReferences Map, mapping class name to set of referenced class
     *                       for all views.
     * @param clr the ClassLoaderResolver
     */
    private void getReferencedClassMetaData(final List orderedCMDs,
                                            final Set referencedCMDs,
                                            final String dba_vendor_id,
                                            final Map viewReferences,
                                            final ClassLoaderResolver clr)
    {
        // Recursively call getReferencedClassMetaData(...) before adding them
        // to the orderedCmds and referenced. This will ensure that any
        // classes with dependencies on them are put in the orderedCmds List
        // in the correct order.
        if (!referencedCMDs.contains(this))
        {
            // Go ahead and add this class to the referenced Set, it will
            // get added to the orderedCMDs List after all classes that this
            // depends on have been added.
            referencedCMDs.add(this);

            for (int i=0;i<managedMembers.length;i++)
            {
                AbstractMemberMetaData fmd=managedMembers[i];
                fmd.getReferencedClassMetaData(orderedCMDs,referencedCMDs,dba_vendor_id,clr);
            }

            // Add on any superclass
            if (persistenceCapableSuperclass != null)
            {
                AbstractClassMetaData super_cmd=getSuperAbstractClassMetaData();
                super_cmd.getReferencedClassMetaData(orderedCMDs,referencedCMDs,dba_vendor_id,clr);
            }

            // Add on any objectid class
            if (objectidClass != null)
            {
                AbstractClassMetaData id_cmd=getMetaDataManager().getMetaDataForClass(objectidClass,clr);
                if (id_cmd != null)
                {
                    id_cmd.getReferencedClassMetaData(orderedCMDs,referencedCMDs,dba_vendor_id,clr);
                }
            }

            // Add on any views defined for this class
            String viewDefStr = getValueForExtension("view-definition-"+dba_vendor_id);
            if( viewDefStr == null )
            {
                viewDefStr = getValueForExtension("view-definition");
            }
            if( viewDefStr!= null )
            {
                MacroString viewDef = new MacroString(fullName,
                           getValueForExtension("view-imports"),
                           viewDefStr);
                viewDef.substituteMacros(new MacroString.MacroHandler()
                    {
                        public void onIdentifierMacro(MacroString.IdentifierMacro im)
                        {
                            if (!getFullClassName().equals(im.className)) //ignore itself
                            {
                                addViewReference(viewReferences,im.className);
                                AbstractClassMetaData view_cmd=getMetaDataManager().getMetaDataForClass(im.className,clr);
                                view_cmd.getReferencedClassMetaData(orderedCMDs,referencedCMDs,dba_vendor_id,viewReferences,clr);
                            }
                        }

                        public void onParameterMacro(MacroString.ParameterMacro pm)
                        {
                            throw new JPOXUserException("Parameter macros not allowed in view definitions: " + pm);
                        }
                    },clr);
            }

            orderedCMDs.add(this);
        }
    }

    /**
     * Method to add a reference for views. Check the view references for circular
     * dependencies. If there are any circular dependencies, throw a JPOXUserException.
     * @param viewReferences The Map of classname to Set of referenced Classes to add the reference to.
     * @param referenced_name Class name of the referenced class
     * @throws JPOXUserException Thrown if a circular reference is found
     */
    private void addViewReference(Map viewReferences,String referenced_name)
    {
        if (fullName.equals(referenced_name))
        {
            // Add this reference to the Map.
            Set referencedSet = (Set)viewReferences.get(referenced_name);
            if (referencedSet == null)
            {
                referencedSet = new HashSet();
                viewReferences.put(fullName,referencedSet);
            }
            referencedSet.add(referenced_name);

            // Check to see if there is a circular dependency.  This will
            // be true if the referenced class references this class.
            ViewUtils.checkForCircularViewReferences(viewReferences,fullName,referenced_name,null);
        }
    }
   
    // ------------------------------ Accessors --------------------------------

    /**
     * Accessor for the number of named queries.
     * @return no of named queries
     */
    public int getNoOfQueries()
    {
        return queries.size();
    }

    /**
     * Accessor for the metadata of the named queries.
     * @return Meta-Data for the named queries.
     */
    public QueryMetaData[] getQueries()
    {
        return (queries == null ? null : ((QueryMetaData[])queries.toArray(new QueryMetaData[queries.size()])));
    }

    /**
     * Get the query result MetaData registered for this class.
     * @return Query Result MetaData defined for this class
     */
    public QueryResultMetaData[] getQueryResultMetaData()
    {
        if (queryResultMetaData == null)
        {
            return null;
        }
        return (QueryResultMetaData[])queryResultMetaData.toArray(new QueryResultMetaData[queryResultMetaData.size()]);
    }

    /**
     * Accessor for Version MetaData for objects stored in this table
     * @return Returns the versionMetaData.
     */
    public final VersionMetaData getVersionMetaData()
    {
        return versionMetaData;
    }

    /**
     * Convenience method to find the version MetaData defining versioning for the same table
     * as this class is using. Traverses up the inheritance tree to find the highest class that uses
     * "subclass-table" that has version metadata defined, and returns the MetaData.
     * @return Version MetaData for the highest class in this tree using subclass-table
     */
    public final VersionMetaData getVersionMetaDataForTable()
    {
        if (pcSuperclassMetaData != null &&
            pcSuperclassMetaData.getInheritanceMetaData().getStrategyValue() == InheritanceStrategy.SUBCLASS_TABLE)
        {
            VersionMetaData vermd = pcSuperclassMetaData.getVersionMetaDataForTable();
            if (vermd != null)
            {
                // Superclass has versioning info so return that
                return vermd;
            }
        }

        // Nothing in superclasses sharing our table so return ours
        return versionMetaData;
    }

    /**
     * Convenience method to find the discriminator MetaData defining the discrim for the same table
     * as this class is using. Traverses up the inheritance tree to find the highest class that uses
     * "subclass-table" that has discriminator metadata defined, and returns the MetaData.
     * @return DiscriminatorMetaData for the highest class in this tree using subclass-table
     */
    public final DiscriminatorMetaData getDiscriminatorMetaDataForTable()
    {
        if (pcSuperclassMetaData != null &&
            pcSuperclassMetaData.getInheritanceMetaData().getStrategyValue() == InheritanceStrategy.SUBCLASS_TABLE)
        {
            if (pcSuperclassMetaData.getInheritanceMetaData() != null)
            {
                DiscriminatorMetaData dismd = pcSuperclassMetaData.getInheritanceMetaData().getDiscriminatorMetaData();
                if (dismd != null)
                {
                    // Superclass has discriminator info so return that
                    return dismd;
                }
            }
        }

        // Nothing in superclasses sharing our table so return ours
        return (inheritanceMetaData != null ? inheritanceMetaData.getDiscriminatorMetaData() : null);
    }

    /**
     * Accessor for joinMetaData
     * @return Returns the joinMetaData.
     */
    public final JoinMetaData[] getJoinMetaData()
    {
        return joinMetaData;
    }

    /**
     * Accessor for all MetaData defined for fetch groups for this class.
     * This doesn't include superclasses.
     * @return Returns the fetchGroupMetaData.
     */
    public final FetchGroupMetaData[] getFetchGroupMetaData()
    {
        return fetchGroupMetaData;
    }

    /**
     * Accessor for fetch group metadata for the specified groups (if present).
     * The returned metadata is what is defined for this class that matches any of the names in the input set.
     * @param groupNames Names of the fetch groups
     * @return MetaData for the groups
     */
    public FetchGroupMetaData[] getFetchGroupMetaData(Collection groupNames)
    {
        Collection results = new HashSet();
        for (Iterator iter = groupNames.iterator(); iter.hasNext();)
        {
            String groupname = (String) iter.next();
            FetchGroupMetaData fgmd = getFetchGroupMetaData(groupname);
            if (fgmd != null)
            {
                results.add(fgmd);
            }
        }
        FetchGroupMetaData[] result = new FetchGroupMetaData[results.size()];
        results.toArray(result);
        return result;
    }

    /**
     * Accessor for the fetch group metadata for the group specified.
     * @param groupname Name of the fetch group
     * @return MetaData for this group
     */
    public FetchGroupMetaData getFetchGroupMetaData(String groupname)
    {
        FetchGroupMetaData fgmd = (FetchGroupMetaData) fetchGroupMetaDataByName.get(groupname);
        if (fgmd == null && pcSuperclassMetaData != null)
        {
            return pcSuperclassMetaData.getFetchGroupMetaData(groupname);
        }
        return fgmd;
    }

    /**
     * Accessor for the identity-type.
     * @return identity-type tag value
     */
    public IdentityType getIdentityType()
    {
        return identityType;
    }

    /**
     * Accessor for indexMetaData
     * @return Returns the indexMetaData.
     */
    public final IndexMetaData[] getIndexMetaData()
    {
        return indexMetaData;
    }

    /**
     * Accessor for foreignKeyMetaData
     * @return Returns the foreignKeyMetaData.
     */
    public final ForeignKeyMetaData[] getForeignKeyMetaData()
    {
        return foreignKeyMetaData;
    }

    /**
     * Accessor for UniqueMetaData
     * @return Returns the UniqueMetaData.
     */
    public final UniqueMetaData[] getUniqueMetaData()
    {
        return uniqueMetaData;
    }

    /**
     * Accessor for the unmapped columns require for the datastore table.
     * @return The list of unmapped columns
     */
    public final List getUnmappedColumns()
    {
        return unmappedColumns;
    }

    /**
     * Accessor for the class name.
     * @return class name
     */
    public String getName()
    {
        return name;
    }

    /**
     * Accessor for the full class name.
     * @return full class name.
     */
    public String getFullClassName()
    {
        return fullName;
    }

    /**
     * Accessor for the class name.
     * @return class name
     */
    public String getEntityName()
    {
        return entityName;
    }
   
    /**
     * Accessor for the objectid-class tag value.
     * @return the fully qualified objectid class name
     */
    public String getObjectidClass()
    {
        return objectidClass;
    }

    /**
     * Accessor for the catalog name.
     * @return catalog name
     */
    public String getCatalog()
    {
        if (this.catalog == null)
        {
            // Nothing defined here for catalog, so get from package
            return ((PackageMetaData)parent).getCatalog();
        }
      
        return catalog;
    }

    /**
     * Accessor for the schema name.
     * @return schema name
     */
    public String getSchema()
    {
        if (this.schema == null)
        {
            // Nothing defined here for schema, so get from package
            return ((PackageMetaData)parent).getSchema();
        }

        return schema;
    }

    /**
     * Accessor for the table name.
     * @return table name
     */
    public String getTable()
    {
        return table;
    }

    /**
     * Accessor for the requires-extent tag value.
     * @return requires-extent tag value
     */
    public boolean isRequiresExtent()
    {
        return requiresExtent;
    }

    /**
     * Accessor for the detachable tag value.
     * @return detachable tag value
     */
    public boolean isDetachable()
    {
        return detachable;
    }


    /**
     * Accessor for the embedded-only tag value.
     * @return embedded-only tag value
     */
    public boolean isEmbeddedOnly()
    {
        return embeddedOnly;
    }

    /**
     * Convenience method to make this class available for storing only when embedded in another object.
     */
    public void setEmbeddedOnly()
    {
        embeddedOnly = true;
    }

    /**
     * Accessor for identityMetaData
     * @return Returns the identityMetaData.
     */
    public final IdentityMetaData getIdentityMetaData()
    {
        return identityMetaData;
    }

    /**
     * Accessor for inheritanceMetaData
     * @return Returns the inheritanceMetaData.
     */
    public final InheritanceMetaData getInheritanceMetaData()
    {
        return inheritanceMetaData;
    }

    /**
     * Accessor for primaryKeyMetaData
     * @return Returns the primaryKey MetaData.
     */
    public final PrimaryKeyMetaData getPrimaryKeyMetaData()
    {
        return primaryKeyMetaData;
    }

    /**
     * Convenience accessor for the MetaData Manager in use.
     * @return MetaDataManager.
     */
    public MetaDataManager getMetaDataManager()
    {
        if (parent != null && parent.getParent() != null)
        {
            return getPackageMetaData().getFileMetaData().getMetaDataManager();
        }
        return null;
    }

    /**
     * Convenience accessor for the parent Package MetaData.
     * @return MetaData for parent package.
     */
    public PackageMetaData getPackageMetaData()
    {
        if (parent != null)
        {
            return (PackageMetaData)parent;
        }
        return null;
    }

    /**
     * Convenience accessor for the package name.
     * @return package name.
     */
    public String getPackageName()
    {
        return getPackageMetaData().getName();
    }

    /**
     * Accessor for the number of fields/properties.
     * This is the total number of fields/properties (inc static, final etc) in this class
     * @return no of fields/properties.
     */
    public int getNoOfMembers()
    {
        return members.size();
    }

    /**
     * Accessor for the metadata of a field/property. Does not include superclasses
     * @param index field index relative to this class only starting from 0
     * @return Meta-Data for the field/property
     */
    public AbstractMemberMetaData getMetaDataForMemberAtRelativePosition(int index)
    {
        if (index < 0 || index >= members.size())
        {
            return null;
        }
        return (AbstractMemberMetaData)members.get(index);
    }

    /**
     * Accessor for the persistence-modifier of the class.
     * @return persistence-modifier tag value
     */
    public ClassPersistenceModifier getPersistenceModifier()
    {
        return persistenceModifier;
    }

    /**
     * Accessor for the persistence-capable-superclass tag value.
     * @return persistence-capable-superclass tag value
     */
    public String getPersistenceCapableSuperclass()
    {
        return persistenceCapableSuperclass;
    }

    /**
     * Check if the argument cmd is the same as this or a descedent.
     * @param cmd the AbstractClassMetaData to be verify if this is an ancestor
     * @return true if the argument is a child or same as this
     */
    public boolean isSameOrAncestorOf(AbstractClassMetaData cmd)
    {
        checkInitialised();
       
        if (cmd == null)
        {
            return false;
        }
       
        if (fullName.equals(cmd.fullName))
        {
            return true;
        }
       
        AbstractClassMetaData parent = cmd.getSuperAbstractClassMetaData();
        while( parent != null )
        {
            if (fullName.equals(parent.fullName))
            {
                return true;
            }
            parent = parent.getSuperAbstractClassMetaData();
        }
        return false;
    }

    /**
     * Accessor for the names of the primary key fields/properties. Only valid after being populated.
     * Provided as a convenience where we need to get the names of the PK members but cant wait til initialisation.
     * @return names of the PK fields/properties
     */
    public String[] getPrimaryKeyMemberNames()
    {
        if (identityType != IdentityType.APPLICATION)
        {
            return null;
        }

        HashSet memberNames = new HashSet();
        Iterator iter = members.iterator();
        while (iter.hasNext())
        {
            AbstractMemberMetaData mmd = (AbstractMemberMetaData)iter.next();
            if (mmd.primaryKey == Boolean.TRUE)
            {
                memberNames.add(mmd.name);
            }
        }

        if (memberNames.size() > 0)
        {
            return (String[])memberNames.toArray(new String[memberNames.size()]);
        }
        memberNames = null;
        return pcSuperclassMetaData.getPrimaryKeyMemberNames();
    }

    /**
     * Method to check if a field/property exists in this classes definition.
     * @param memberName Name of field/property
     * @return return true if exists.
     */
    public boolean hasMember(String memberName)
    {
        Iterator iter = members.iterator();
        while (iter.hasNext())
        {
            AbstractMemberMetaData mmd = (AbstractMemberMetaData)iter.next();
            if (mmd.getName().equals(memberName))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * Accessor for the Meta-Data for a field/property. Include superclasses.
     * @param name the name of the field/property
     * @return Meta-Data for the field.
     */
    public AbstractMemberMetaData getMetaDataForMember(String name)
    {
        if (name == null)
        {
            return null;
        }

        Iterator iter = members.iterator();
        while (iter.hasNext())
        {
            AbstractMemberMetaData mmd = (AbstractMemberMetaData)iter.next();
            if (mmd.getName().equals(name))
            {
                return mmd;
            }
        }

        // Check superclass for the field/property with this name
        if (pcSuperclassMetaData != null)
        {
            return pcSuperclassMetaData.getMetaDataForMember(name);
        }
        return null;
    }

    /**
     * Accessor for the number of managed fields/properties (this class only).
     * @return no of managed fields/properties in this class
     */
    public int getNoOfManagedMembers()
    {
        // checkInitialised();

        if (managedMembers == null)
        {
            return 0;
        }
        return managedMembers.length;
    }

    /**
     * Accessor for the managed fields/properties in this class (not including superclass, but including overridden).
     * @return MetaData for the managed fields/properties in this class
     */
    public AbstractMemberMetaData[] getManagedMembers()
    {
        checkInitialised();

        return managedMembers;
    }

    /**
     * Accessor for MetaData for a managed field/property in this class. The position is relative to
     * the first field in this class (ignores superclasses).
     * @param position The position of the managed field. 0 = first in the class
     * @return The JDO managed field at that position
     */
    public AbstractMemberMetaData getMetaDataForManagedMemberAtPosition(int position)
    {
        checkInitialised();

        if (managedMembers == null)
        {
            return null;
        }
        if (position < 0 || position >= managedMembers.length)
        {
            return null;
        }

        return managedMembers[position];
    }

    /**
     * Accessor for the number of overridden fields/properties (this class only).
     * @return no of overridden fields/properties in this class
     */
    public int getNoOfOverriddenMembers()
    {
        if (overriddenMembers == null)
        {
            return 0;
        }
        return overriddenMembers.length;
    }

    /**
     * Accessor for the overridden fields/properties in this class.
     * @return The overridden fields/properties in this class
     */
    public AbstractMemberMetaData[] getOverriddenMembers()
    {
        checkInitialised();

        return overriddenMembers;
    }

    /**
     * Accessor for MetaData for an overridden field/property in this class.
     * @param position The position of the overridden field/property.
     * @return MetaData for the field/property at that position
     */
    public AbstractMemberMetaData getOverriddenMember(int position)
    {
        checkInitialised();

        if (overriddenMembers == null)
        {
            return null;
        }
        if (position < 0 || position >= overriddenMembers.length)
        {
            return null;
        }

        return overriddenMembers[position];
    }

    /**
     * Accessor for an overridden field/property with the specified name.
     * @param name Name of the field/property
     * @return The MetaData for the field/property
     */
    public AbstractMemberMetaData getOverriddenMember(String name)
    {
        checkInitialised();

        if (overriddenMembers == null)
        {
            return null;
        }
        for (int i=0;i<overriddenMembers.length;i++)
        {
            if (overriddenMembers[i].getName().equals(name))
            {
                return overriddenMembers[i];
            }
        }
        return null;
    }

    /**
     * Convenience method that navigates up a MetaData inheritance tree until it finds the base field/property definition.
     * @param name Name of the field/property we require
     * @return The AbstractMemberMetaData
     */
    protected AbstractMemberMetaData getMemberBeingOverridden(String name)
    {
        Iterator iter = members.iterator();
        while(iter.hasNext())
        {
            AbstractMemberMetaData apmd = (AbstractMemberMetaData)iter.next();
            if (apmd.name.equals(name) && apmd.fieldBelongsToClass())
            {
                return apmd;
            }
        }
        if (pcSuperclassMetaData != null)
        {
            return pcSuperclassMetaData.getMemberBeingOverridden(name);
        }
        return null;
    }

    /**
     * Accessor for the number of inherited managed fields/properties in superclasses.
     * @return No of inherited managed fields/properties in superclasses.
     */
    public int getNoOfInheritedManagedMembers()
    {
        checkInitialised();

        return noOfInheritedManagedMembers;
    }
   
    /**
     * Accessor for the number of managed fields/properties from this class plus inherited classes.
     * @return The number of managed fields/properties from this class plus inherited classes.
     */
    public int getMemberCount()
    {
        // we assume this
//      checkInitialised();
       
        return memberCount;
    }

    /**
     * Accessor for a managed field/property including superclass fields.
     * @param abs_position The position of the managed member including the
     * superclass. Fields are numbered from 0 in the root superclass.
     * @return The managed field/property at this "absolute" position.
     */
    public AbstractMemberMetaData getMetaDataForManagedMemberAtAbsolutePosition(int abs_position)
    {
        checkInitialised();

        return getMetaDataForManagedMemberAtAbsolutePositionInternal(abs_position);
    }

    /**
     * Internal method to get the field/property for an absolute field number.
     * If the field for that absolute field position is overridden by a field in this class
     * then this field/property will be returned.
     * @param abs_position The position of the managed field including the
     * superclass. Fields are numbered from 0 in the root superclass.
     * @return The managed field at this "absolute" position.
     */
    protected AbstractMemberMetaData getMetaDataForManagedMemberAtAbsolutePositionInternal(int abs_position)
    {
        // If the field is in a superclass, go there
        if (abs_position < noOfInheritedManagedMembers)
        {
            if (pcSuperclassMetaData == null)
            {
                return null;
            }
            else
            {
                AbstractMemberMetaData fmd = pcSuperclassMetaData.getMetaDataForManagedMemberAtAbsolutePositionInternal(abs_position);
                if (fmd != null)
                {
                    for (int i=0;i<overriddenMembers.length;i++)
                    {
                        if (overriddenMembers[i].getName().equals(fmd.getName()) &&
                            overriddenMembers[i].getClassName().equals(fmd.getClassName()))
                        {
                            // Return the overriding field if we have one (class and field name is the safest comparison)
                            return overriddenMembers[i];
                        }
                    }
                   
                    return fmd;
                }
                return null;
            }
        }
        // If the field is in this class, return it
        else if (abs_position - noOfInheritedManagedMembers >= managedMembers.length)
        {
            return null;
        }
        else
        {
            return managedMembers[abs_position - noOfInheritedManagedMembers];
        }
    }
   
    /**
     * Accessor for the absolute position for a relative position.
     * @param relativePosition The relative field number
     * @return The absolute position
     */
    public int getAbsoluteMemberPositionForRelativePosition(int relativePosition)
    {
        return noOfInheritedManagedMembers + relativePosition;
    }

    /**
     * Accessor for the position of the field/property with the specified name.
     * The returned position is relative to this class only.
     * @param memberName Name of the field/property
     * @return Position of the field/property in this class.
     */
    public int getRelativePositionOfMember(String memberName)
    {
        checkInitialised();

        if (memberName == null)
        {
            return -1;
        }

        Integer i=(Integer)memberPositionsByName.get(memberName);

        return i == null ? -1 : i.intValue();
    }

    /**
     * Accessor for the absolute position of the field/property with the specified name.
     * The absolute position has origin of the root superclass, starting at 0.
     * @param memberName Name of the field/property
     * @return Absolute position of the field/property.
     */
    public int getAbsolutePositionOfMember(String memberName)
    {
        checkInitialised();

        if (memberName == null)
        {
            return -1;
        }

        int i = getRelativePositionOfMember(memberName);
        if (i < 0)
        {
            if (pcSuperclassMetaData != null)
            {
                i = pcSuperclassMetaData.getAbsolutePositionOfMember(memberName);
            }
        }
        else
        {
            i += noOfInheritedManagedMembers;
        }

        return i;
    }

    /**
     * Accessor for the absolute position of the field/property with the specified name.
     * The absolute position has origin of the root superclass, starting at 0.
     * Will only retrieve the absolute field number if the <code>field_name</code>
     * is of type given by <code>class_name</code>.
     * @param className Name of the class
     * @param memberName Name of the field/property
     * @return Absolute position of the field/property.
     */
    public int getAbsolutePositionOfMember(String className, String memberName)
    {
        checkInitialised();

        if (memberName == null)
        {
            return -1;
        }
       
        int i=-1;
        if (className.equals(getFullClassName()))
        {
            i=getRelativePositionOfMember(memberName);
        }
        if (i < 0)
        {
            if (pcSuperclassMetaData != null)
            {
                i = pcSuperclassMetaData.getAbsolutePositionOfMember(className,memberName);
            }
        }
        else
        {
            i += noOfInheritedManagedMembers;
        }

        return i;
    }
   
    /**
     * Convenience method to check the number of fields/properties in this class that have been populated and
     * that are primary key members. This is only ever called during populate() since the accessor
     * for PK members cant be used yet due to lack of initialisation.
     * Recurses to its superclass if it has a superclass.
     * @return The number of PK members
     */
    private int getNoOfPopulatedPKMembers()
    {
        if (pcSuperclassMetaData != null)
        {
            return pcSuperclassMetaData.getNoOfPopulatedPKMembers();
        }

        Iterator fields_iter = members.iterator();
        int noOfPks = 0;
        while (fields_iter.hasNext())
        {
            AbstractMemberMetaData fmd = (AbstractMemberMetaData)fields_iter.next();
            if (fmd.isPrimaryKey())
            {
                noOfPks++;
            }
        }
        return noOfPks;
    }

    /**
     * Accessor for the number of primary key fields/properties.
     * @return no of primary key fields/properties
     */
    public int getNoOfPrimaryKeyMembers()
    {
        if (pkMemberPositions == null)
        {
            return 0;
        }
        else
        {
            return pkMemberPositions.length;
        }
    }

    /**
     * Accessor for all field/property positions.
     * These are absolute numbers and include superclasses and are really just 0, 1, 2, ... n.
     * @return The positions of all (managed) fields/properties.
     */
    public int[] getAllMemberPositions()
    {
        checkInitialised();
        return allMemberPositions;
    }
    /**
     * Accessor for the field numbers of the primary key fields/properties.
     * These are absolute numbers (including superclasses).
     * @return The positions of the primary key fields/properties.
     */
    public int[] getPKMemberPositions()
    {
        checkInitialised();
        return pkMemberPositions;
    }
    /**
     * Accessor for the positions of the non primary key fields/properties (inc superclass fields).
     * @return The member positions
     */
    public int[] getNonPKMemberPositions()
    {
        checkInitialised();
        return nonPkMemberPositions;
    }

    /**
     * Accessor for the flags of the non primary key fields/properties (inc superclass members).
     * @return The flags whether the field/property is non primary key
     */
    public boolean[] getNonPKMemberFlags()
    {
        checkInitialised();
        return nonPkMemberFlags;
    }

    /**
     * Accessor for the absolute positions of the default fetch group fields/properties (inc superclasses).
     * @return The positions of the DFG fields/properties (inc superclasses).
     */
    public int[] getDFGMemberPositions()
    {
        checkInitialised();
        return dfgMemberPositions;
    }

    /**
     * Accessor for the flags of the DFG fields/properties (inc superclass).
     * @return The flags whether the field/property is in the DFG
     **/
    public boolean[] getDFGMemberFlags()
    {
        checkInitialised();
        return dfgMemberFlags;
    }

    /**
     * Accessor for the absolute positions of the second class mutable fields/properties.
     * @return The field numbers of the second class mutable fields (inc superclasses).
     */
    public int[] getSCOMutableMemberPositions()
    {
        checkInitialised();
        return scoMutableMemberPositions;
    }

    /** Field numbers of all SCO fields/properties that arent containers. */
    protected int[] scoNonContainerMemberPositions = null;

    /**
     * Accessor for the absolute positions of all SCO fields/properties that are NOT containers (e.g Dates, Points, etc)
     * @return Field numbers of all SCO non-container fields/properties
     */
    public int[] getSCONonContainerMemberPositions()
    {
        checkInitialised();
        if (scoNonContainerMemberPositions == null)
        {
            int[] noncontainerMemberPositions;
            int numberNonContainerSCOFields = 0;
            for (int i=0;i<scoMutableMemberPositions.length;i++)
            {
                AbstractMemberMetaData fmd = getMetaDataForManagedMemberAtAbsolutePosition(scoMutableMemberPositions[i]);
                if (!(java.util.Collection.class.isAssignableFrom(fmd.getType())) &&
                    !(java.util.Map.class.isAssignableFrom(fmd.getType())))
                {
                    numberNonContainerSCOFields++;
                }
            }

            noncontainerMemberPositions = new int[numberNonContainerSCOFields];
            int nonContNum = 0;
            for (int i=0;i<scoMutableMemberPositions.length;i++)
            {
                AbstractMemberMetaData fmd = getMetaDataForManagedMemberAtAbsolutePosition(scoMutableMemberPositions[i]);
                if (!(java.util.Collection.class.isAssignableFrom(fmd.getType())) &&
                    !(java.util.Map.class.isAssignableFrom(fmd.getType())))
                {
                    noncontainerMemberPositions[nonContNum++] = scoMutableMemberPositions[i];
                }
            }

            scoNonContainerMemberPositions = noncontainerMemberPositions;
        }
        return scoNonContainerMemberPositions;
    }

    /** Positions of all SCO fields/properties that are containers. */
    protected int[] secondClassContainerMemberPositions = null;

    /**
     * Accessor for the absolute positions of all SCO fields/properties that are containers.
     * @return Positions of all SCO container fields/properties.
     */
    public int[] getSCOContainerMemberPositions()
    {
        checkInitialised();
        if (secondClassContainerMemberPositions == null)
        {
            int[] containerMemberPositions;
            int numberContainerSCOFields = 0;
            for (int i=0;i<scoMutableMemberPositions.length;i++)
            {
                AbstractMemberMetaData fmd = getMetaDataForManagedMemberAtAbsolutePosition(scoMutableMemberPositions[i]);
                if (java.util.Collection.class.isAssignableFrom(fmd.getType()) ||
                    java.util.Map.class.isAssignableFrom(fmd.getType()))
                {
                    numberContainerSCOFields++;
                }
            }

            containerMemberPositions = new int[numberContainerSCOFields];
            int contNum = 0;
            for (int i=0;i<scoMutableMemberPositions.length;i++)
            {
                AbstractMemberMetaData fmd = getMetaDataForManagedMemberAtAbsolutePosition(scoMutableMemberPositions[i]);
                if (java.util.Collection.class.isAssignableFrom(fmd.getType()) ||
                    java.util.Map.class.isAssignableFrom(fmd.getType()))
                {
                    containerMemberPositions[contNum++] = scoMutableMemberPositions[i];
                }
            }

            secondClassContainerMemberPositions = containerMemberPositions;
        }
        return secondClassContainerMemberPositions;
    }

    /**
     * Accessor for the absolute positions of the PersistenceCapable fields/properties.
     * @return The positions of the PersistenceCapable fields/properties (inc superclasses).
     */
    public int[] getPersistenceCapableMemberPositions()
    {
        checkInitialised();
        return persistenceCapableMemberPositions;
    }

    /**
     * Accessor for the flags of the SCO mutable fields (inc superclass fields).
     * @return The flags whether the field is second class mutable
     */
    public boolean[] getSCOMutableMemberFlags()
    {
        checkInitialised();
        return scoMutableMemberFlags;
    }

    /**
     * Whether this PersistenceCapable class uses SingleFieldIdentity
     * @return true if using SingleFieldIdentity as objectid class
     */
    public boolean usesSingleFieldIdentityClass()
    {
        return usesSingleFieldIdentityClass;
    }

    /**
     * Accessor for whether this class is fully specified by this metadata and that any
     * annotations should be ignored.
     * @return Whether we should ignore any annotations
     */
    public boolean isMetaDataComplete()
    {
        return metaDataComplete;
    }

    /** Absolute positions of the fields/properties that have relations. */
    int[] relationPositions = null;

    /**
     * Convenience method to return if the class has relations to other objects. Includes superclasses.
     * @return Whether the class has any relations (that it knows about)
     */
    public boolean hasRelations(ClassLoaderResolver clr)
    {
        if (relationPositions == null)
        {
            // Relations not yet calculated so do it now
            getRelationMemberPositions(clr);
        }
        return (relationPositions.length > 0);
    }

    /**
     * Convenience method to return the absolute positions of all fields/properties that have relations.
     * @param clr ClassLoader resolver
     * @return The absolute positions of all fields/properties that have relations
     */
    public int[] getRelationMemberPositions(ClassLoaderResolver clr)
    {
        if (relationPositions == null)
        {
            int[] superclassRelationPositions = null;
            if (pcSuperclassMetaData != null)
            {
                superclassRelationPositions = pcSuperclassMetaData.getRelationMemberPositions(clr);
            }

            int numRelationsSuperclass =
                (superclassRelationPositions != null ? superclassRelationPositions.length : 0);
            int numRelations = numRelationsSuperclass;
            for (int i=0;i<managedMembers.length;i++)
            {
                if (managedMembers[i].getRelationType(clr) != Relation.NONE)
                {
                    numRelations++;
                }
            }

            relationPositions = new int[numRelations];
            int num = 0;
            if (numRelationsSuperclass > 0)
            {
                for (int i=0;i<superclassRelationPositions.length;i++)
                {
                    relationPositions[num++] = superclassRelationPositions[i];
                }
            }
            if (numRelations > numRelationsSuperclass)
            {
                for (int i=0;i<managedMembers.length;i++)
                {
                    if (managedMembers[i].getRelationType(clr) != Relation.NONE)
                    {
                        relationPositions[num++] = managedMembers[i].getAbsoluteFieldNumber();
                    }
                }
            }
        }
        return relationPositions;
    }

    /**
     * Convenience method to return the absolute positions of fields/properties that have bidirectional
     * relations.
     * @param clr ClassLoader resolver
     * @return Absolute positions of bidirectional relation fields/properties
     */
    public int[] getBidirectionalRelationMemberPositions(ClassLoaderResolver clr)
    {
        if (relationPositions == null)
        {
            getRelationMemberPositions(clr);
        }

        int numBidirs = 0;
        for (int i=0;i<relationPositions.length;i++)
        {
            AbstractMemberMetaData mmd = getMetaDataForManagedMemberAtAbsolutePosition(relationPositions[i]);
            int relationType = mmd.getRelationType(clr);
            if (relationType == Relation.ONE_TO_ONE_BI || relationType == Relation.ONE_TO_MANY_BI ||
                relationType == Relation.MANY_TO_ONE_BI || relationType == Relation.MANY_TO_MANY_BI)
            {
                numBidirs++;
            }
        }

        int[] bidirRelations = new int[numBidirs];
        numBidirs = 0;
        for (int i=0;i<relationPositions.length;i++)
        {
            AbstractMemberMetaData mmd = getMetaDataForManagedMemberAtAbsolutePosition(relationPositions[i]);
            int relationType = mmd.getRelationType(clr);
            if (relationType == Relation.ONE_TO_ONE_BI || relationType == Relation.ONE_TO_MANY_BI ||
                relationType == Relation.MANY_TO_ONE_BI || relationType == Relation.MANY_TO_MANY_BI)
            {
                bidirRelations[numBidirs] = mmd.getAbsoluteFieldNumber();
            }
        }
        return bidirRelations;
    }

    // ------------------------------- Mutators --------------------------------

    /**
     * Cinvenience method for updating the identity type when not set correctly during construction.
     * This is needed where we have annotations and the user hasnt defined "APPLICATION", and we find a field
     * defined as @PrimaryKey so we set it to APPLICATION at that point.
     * @param type The Identity type to use
     */
    public void setIdentityType(IdentityType type)
    {
        if (isPopulated() || isInitialised())
        {
            throw new JPOXUserException("Already populated/initialised");
        }

        this.identityType = type;
    }

    /**
     * Method to set that this class is "metadata complete" (see JPA spec).
     * Means that any annotations will be ignored.
     */
    public void setMetaDataComplete()
    {
        metaDataComplete = true;
    }

    /**
     * Method to add a named query to this class. Rejects the addition of
     * duplicate named queries.
     * @param qmd Meta-Data for the query.
     */
    public void addQuery(QueryMetaData qmd)
    {
        if (qmd == null)
        {
            return;
        }
        if (queries == null)
        {
            queries = new HashSet();
        }

        queries.add(qmd);
        qmd.parent = this;
    }

    /**
     * Method to register a query-result MetaData.
     * @param resultMetaData Query-Result MetaData to register
     */
    public void addQueryResultMetaData(QueryResultMetaData resultMetaData)
    {
        if (queryResultMetaData == null)
        {
            queryResultMetaData = new HashSet();
        }
        if (!queryResultMetaData.contains(resultMetaData))
        {
            queryResultMetaData.add(resultMetaData);
        }
    }

    /**
     * Method to add an index to this class.
     * @param idxmd Meta-Data for the index.
     */
    public void addIndex(IndexMetaData idxmd)
    {
        if (idxmd == null)
        {
            return;
        }

        if (isInitialised())
        {
            throw new JPOXUserException("Already initialised");
        }
        indexes.add(idxmd);
    }

    /**
     * Method to add an foreign-key to this class.
     * @param fkmd Meta-Data for the foreign-key.
     */
    public void addForeignKey(ForeignKeyMetaData fkmd)
    {
        if (fkmd == null)
        {
            return;
        }

        if (isInitialised())
        {
            throw new JPOXUserException("Already initialised");
        }
        foreignKeys.add(fkmd);
    }

    /**
     * Method to add a unique constraint to this class.
     * @param unimd Meta-Data for the unique constraint.
     */
    public void addUniqueConstraint(UniqueMetaData unimd)
    {
        if (unimd == null)
        {
            return;
        }

        if (isInitialised())
        {
            throw new JPOXUserException("Already initialised");
        }
        uniqueConstraints.add(unimd);
    }

    /**
     * Method to add an unmapped column.
     * @param colmd The metadata for the unmapped column
     */
    public final void addUnmappedColumn(ColumnMetaData colmd)
    {
        if (unmappedColumns == null)
        {
            unmappedColumns = new ArrayList();
        }
        unmappedColumns.add(colmd);
    }

    /**
     * Method to add a field/property to this interface.
     * Rejects the addition of duplicate named fields/properties.
     * @param mmd Field/Property MetaData
     */
    public void addMember(AbstractMemberMetaData mmd)
    {
        if (mmd == null)
        {
            return;
        }
        if (isInitialised())
        {
            // TODO Localise this message
            throw new JPOXUserException("adding field/property " + mmd.getName() + " when already initialised!");
        }

        // Check for conflicting fields/properties
        Iterator iter = members.iterator();
        while (iter.hasNext())
        {
            AbstractMemberMetaData md = (AbstractMemberMetaData)iter.next();
            if (mmd.getName().equals(md.getName()))
            {
                if ((mmd instanceof PropertyMetaData && md instanceof PropertyMetaData) ||
                    (mmd instanceof FieldMetaData && md instanceof FieldMetaData))
                {
                    // Duplicate entry for the same field or property
                    throw new JPOXUserException(LOCALISER.msg("044090", fullName, mmd.getName()));
                }
            }

            String existingName = md.getName();
            boolean existingIsProperty = (md instanceof PropertyMetaData);
            if (existingIsProperty)
            {
                existingName = ((PropertyMetaData)md).getFieldName();
                if (existingName == null)
                {
                    // "fieldName" not specified so default to the property name
                    existingName = md.getName();
                }
            }
            String newName = mmd.getName();
            boolean newIsProperty = (mmd instanceof PropertyMetaData);
            if (newIsProperty)
            {
                newName = ((PropertyMetaData)mmd).getFieldName();
                if (newName == null)
                {
                    // "fieldName" not specified so default to the property name
                    newName = mmd.getName();
                }
            }

            if (existingName.equals(newName))
            {
                if (existingIsProperty && newIsProperty)
                {
                    // Duplicate entry for the same field or property
                    throw new JPOXUserException(LOCALISER.msg("044090", fullName, mmd.getName()));
                }
                else if (existingIsProperty && !newIsProperty)
                {
                    // We have the property and this is a field so ignore it
                    // TODO Check if one is not persistent before discarding
                    JPOXLogger.JDO.info("Ignoring metadata for field " + mmd.getFullFieldName() +
                        " since we already have MetaData for the property " + md.getFullFieldName());
                    return;
                }
                else if (!existingIsProperty && newIsProperty)
                {
                    // We have the field and this is property so replace the field with it
                    // TODO Check if one is not persistent before discarding
                    JPOXLogger.JDO.info("Ignoring existing metadata for field " + md.getFullFieldName() +
                        " since now we have MetaData for the property " + mmd.getFullFieldName());
                    iter.remove();
                }
            }
        }

        mmd.parent = this;
        members.add(mmd);
    }

    /**
     * Method to add a fetch-group to this class.
     * @param fgmd Meta-Data for the fetch-group.
     */
    public void addFetchGroup(FetchGroupMetaData fgmd)
    {
        if (fgmd == null)
        {
            return;
        }

        if (isInitialised())
        {
            throw new JPOXUserException("Already initialised");
        }
        fetchGroups.add(fgmd);
        fgmd.parent = this;
    }

    /**
     * Method to add a join to this class.
     * Rejects the addition of duplicate named fields.
     * @param jnmd Meta-Data for the join.
     */
    public void addJoin(JoinMetaData jnmd)
    {
        if (jnmd == null)
        {
            return;
        }

        if (isInitialised())
        {
            throw new JPOXUserException("Already initialised");
        }
        joins.add(jnmd);
    }

    /**
     * Add a listener class name
     * @param listener the listener metadata. Duplicated classes are ignored
     */
    public void addListener(EventListenerMetaData listener)
    {
        if (listeners == null)
        {
            listeners = new ArrayList();
        }
        if (!listeners.contains(listener))
        {
            listeners.add(listener);
        }
    }

    /**
     * Accessor for the EventListener info for an EventListener class name
     * @param className Name of the event listener class
     * @return EventListener info for this class (or null if the class isnt an EventListener)
     */
    public EventListenerMetaData getListenerForClass(String className)
    {
        if (listeners == null)
        {
            return null;
        }

        for (int i=0;i<listeners.size();i++)
        {
            EventListenerMetaData elmd = (EventListenerMetaData)listeners.get(i);
            if (elmd.getClassName().equals(className))
            {
                return elmd;
            }
        }

        return null;
    }

    /**
     * Get the event listeners
     * @return the event listeners
     */
    public List getListeners()
    {
        return listeners;
    }

    /**
     * Toogle exclude super class listeners
     */
    public void excludeSuperClassListeners()
    {
        this.excludeSuperClassListeners = Boolean.TRUE;
    }
   
    /**
     * Whether super classes listeners are not going to be invoked
     * @return true if super class listeners are not invoked
     */
    public boolean isExcludeSuperClassListeners()
    {
        if (excludeSuperClassListeners != null && excludeSuperClassListeners == Boolean.TRUE)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * Method to exclude default listeners.
     */
    public void excludeDefaultListeners()
    {
        this.excludeDefaultListeners = Boolean.TRUE;
    }

    /**
     * Whether default listeners are not going to be invoked
     * @return true if default listeners are not invoked
     */
    public boolean isExcludeDefaultListeners()
    {
        if (excludeDefaultListeners != null && excludeDefaultListeners == Boolean.TRUE)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * Mutator for the Version MetaData.
     * @param versionMetaData The versionMetaData to set.
     */
    public final void setVersionMetaData(VersionMetaData versionMetaData)
    {
        this.versionMetaData = versionMetaData;
        if (this.versionMetaData != null)
        {
            this.versionMetaData.parent = this;
        }
    }

    /**
     * Mutator for the identity MetaData.
     * @param identityMetaData The identityMetaData to set.
     */
    public final void setIdentityMetaData(IdentityMetaData identityMetaData)
    {
        this.identityMetaData = identityMetaData;
        if (this.identityMetaData != null)
        {
            this.identityMetaData.parent = this;
        }
        identitySpecified = true;
    }

    /**
     * Mutator for the inheritance MetaData.
     * @param inheritanceMetaData The inheritanceMetaData to set.
     */
    public final void setInheritanceMetaData(InheritanceMetaData inheritanceMetaData)
    {
        this.inheritanceMetaData = inheritanceMetaData;
        if (this.inheritanceMetaData != null)
        {
            this.inheritanceMetaData.parent = this;
        }
    }

    /**
     * Mutator for the PrimaryKey MetaData.
     * @param primaryKeyMetaData The PrimaryKey MetaData to set.
     */
    public final void setPrimaryKeyMetaData(PrimaryKeyMetaData primaryKeyMetaData)
    {
        this.primaryKeyMetaData = primaryKeyMetaData;
        if (this.primaryKeyMetaData != null)
        {
            this.primaryKeyMetaData.parent = this;
        }
    }

    /**
     * Mutator for the table name.
     * @param table Name of the table
     */
    public final void setTable(String table)
    {
        this.table = (StringUtils.isWhitespace(table) ? this.table : table);
    }

    /**
     * Mutator for the catalog name.
     * @param catalog Name of the catalog
     */
    public final void setCatalog(String catalog)
    {
        this.catalog = (StringUtils.isWhitespace(catalog) ? this.catalog : catalog);
    }

    /**
     * Mutator for the schema name.
     * @param schema Name of the schema
     */
    public final void setSchema(String schema)
    {
        this.schema = (StringUtils.isWhitespace(schema) ? this.schema : schema);
    }
   
    /**
     * Mutator for the object id class name.
     * @param objectidClass Name of the id class
     */
    public final void setObjectIdClass(String objectidClass)
    {
        this.objectidClass = (StringUtils.isWhitespace(objectidClass) ? this.objectidClass : objectidClass);
    }
}
TOP

Related Classes of org.jpox.metadata.AbstractClassMetaData

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.