/*
 * IMPORTANT!!!! XSL Autogenerated class, DO NOT EDIT!!!!!
 * Template: Infrastructure8.2 rev3 [oneit.objstore.BusinessObjectTemplate.xsl]
 *
 *   Version: 1.0
 *   Vendor: Apache Software Foundation (Xalan XSLTC)
 *   Vendor URL: http://xml.apache.org/xalan-j
 */


    package performa.orm;

import java.io.*;
import java.util.*;
import oneit.appservices.config.*;
import oneit.logging.*;
import oneit.objstore.*;
import oneit.objstore.assocs.*;
import oneit.objstore.attributes.*;
import oneit.objstore.rdbms.filters.*;
import oneit.objstore.parser.*;
import oneit.objstore.validator.*;
import oneit.objstore.utils.*;
import oneit.utils.*;
import oneit.utils.filter.Filter;
import oneit.utils.transform.*;
import oneit.utils.parsers.FieldException;

import oneit.security.*;



public abstract class BaseCandidate extends SecUserExtension
{
    // Reference instance for the object
    public static final Candidate REFERENCE_Candidate = new Candidate ();

    // Reference instance for the object
    public static final Candidate DUMMY_Candidate = new DummyCandidate ();

    // Static constants corresponding to field names
    
    public static final String FIELD_Phone = "Phone";
    public static final String SINGLEREFERENCE_TestInput = "TestInput";
    public static final String BACKREF_TestInput = "";
    public static final String MULTIPLEREFERENCE_TestAnalysises = "TestAnalysises";
    public static final String BACKREF_TestAnalysises = "";
    public static final String MULTIPLEREFERENCE_JobApplications = "JobApplications";
    public static final String BACKREF_JobApplications = "";

    // Static constants corresponding to searches
    

    // Static constants corresponding to attribute helpers
    private static final DefaultAttributeHelper<Candidate> HELPER_Phone = DefaultAttributeHelper.INSTANCE;
    

    // Private attributes corresponding to business object data
    private String _Phone;
    

    // Private attributes corresponding to single references
    private SingleAssociation<Candidate, TestInput> _TestInput;
    

    // Private attributes corresponding to multiple references
    private MultipleAssociation<Candidate, TestAnalysis> _TestAnalysises;
    private MultipleAssociation<Candidate, JobApplication> _JobApplications;
    

    // Map of maps of metadata
    private static final Map ATTRIBUTES_METADATA_Candidate = new HashMap ();

    // Arrays of validators for each attribute
    private static final AttributeValidator[] FIELD_Phone_Validators;
    

    // Arrays of behaviour decorators
    private static final CandidateBehaviourDecorator[] Candidate_BehaviourDecorators;
    
    static
    {
        try
        {
            
            String tmp_TestAnalysises = TestAnalysis.BACKREF_Candidate;
            String tmp_JobApplications = JobApplication.BACKREF_Candidate;
            String tmp_TestInput = TestInput.BACKREF_Candidates;
            
            Map  validatorMapping = ((Map)ConfigMgr.getConfigObject ("CONFIG.ORMVALIDATOR", "ValidatorMapping"));

            setupAssocMetaData_TestAnalysises();
            setupAssocMetaData_JobApplications();
            setupAssocMetaData_TestInput();
            FIELD_Phone_Validators = (AttributeValidator[])setupAttribMetaData_Phone(validatorMapping).toArray (new AttributeValidator[0]);
            

            REFERENCE_Candidate.initialiseReference ();
            DUMMY_Candidate.initialiseReference ();
            Candidate_BehaviourDecorators = BaseBusinessClass.getBBCBehaviours(Candidate.class).toArray(new CandidateBehaviourDecorator[0]);
        }
        catch (RuntimeException e)
        {
            LogMgr.log (BUSINESS_OBJECTS, LogLevel.SYSTEMERROR1, e, "Error initialising");
            throw e;
        }
    }

    
    // Meta Info setup
    private static void setupAssocMetaData_TestAnalysises()
    {
        Map metaInfo = new HashMap ();

        metaInfo.put ("backreferenceName", "Candidate");
        metaInfo.put ("name", "TestAnalysises");
        metaInfo.put ("type", "TestAnalysis");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Candidate.TestAnalysises:", metaInfo);
        ATTRIBUTES_METADATA_Candidate.put (MULTIPLEREFERENCE_TestAnalysises, Collections.unmodifiableMap (metaInfo));
    }
    
    
    // Meta Info setup
    private static void setupAssocMetaData_JobApplications()
    {
        Map metaInfo = new HashMap ();

        metaInfo.put ("backreferenceName", "Candidate");
        metaInfo.put ("name", "JobApplications");
        metaInfo.put ("type", "JobApplication");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Candidate.JobApplications:", metaInfo);
        ATTRIBUTES_METADATA_Candidate.put (MULTIPLEREFERENCE_JobApplications, Collections.unmodifiableMap (metaInfo));
    }
    
    
    // Meta Info setup
    private static void setupAssocMetaData_TestInput()
    {
        Map metaInfo = new HashMap ();

        metaInfo.put ("backreferenceName", "Candidates");
        metaInfo.put ("dbcol", "test_input_id");
        metaInfo.put ("name", "TestInput");
        metaInfo.put ("type", "TestInput");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Candidate.TestInput:", metaInfo);
        ATTRIBUTES_METADATA_Candidate.put (SINGLEREFERENCE_TestInput, Collections.unmodifiableMap (metaInfo));
    }
    
    
    // Meta Info setup
    private static List setupAttribMetaData_Phone(Map validatorMapping)
    {
        Map  metaInfo   = new HashMap ();

        metaInfo.put ("dbcol", "phone");
        metaInfo.put ("length", "30");
        metaInfo.put ("name", "Phone");
        metaInfo.put ("type", "String");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Candidate.Phone:", metaInfo);
        ATTRIBUTES_METADATA_Candidate.put (FIELD_Phone, Collections.unmodifiableMap (metaInfo));

        List validators = BaseBusinessClass.getAttribValidators(Candidate.class, "Phone", metaInfo, validatorMapping);
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG1, "Validators for Candidate.Phone:", validators);        

        return validators;
    }
    
    // END OF STATIC METADATA DEFINITION    
    
    
    
    // This constructor should not be called
    protected BaseCandidate ()
    {
    }


    protected BBCBehaviourDecorator[] getBehaviours()
    {
        return Candidate_BehaviourDecorators;
    }
    
    


    


    // Initialise the attributes
    protected void _initialiseNewObjAttributes (ObjectTransaction transaction) throws StorageException
    {
        super._initialiseNewObjAttributes (transaction);

        
        _Phone = (String)(HELPER_Phone.initialise (_Phone));
    }


    // Initialise the associations
    protected void _initialiseAssociations ()
    {
        super._initialiseAssociations ();

        _TestInput = new SingleAssociation<Candidate, TestInput> (this, SINGLEREFERENCE_TestInput, TestInput.MULTIPLEREFERENCE_Candidates, TestInput.REFERENCE_TestInput, "oneit_sec_user_extension");
        _TestAnalysises = new MultipleAssociation<Candidate, TestAnalysis> (this, MULTIPLEREFERENCE_TestAnalysises, TestAnalysis.SINGLEREFERENCE_Candidate, TestAnalysis.REFERENCE_TestAnalysis);
        _JobApplications = new MultipleAssociation<Candidate, JobApplication> (this, MULTIPLEREFERENCE_JobApplications, JobApplication.SINGLEREFERENCE_Candidate, JobApplication.REFERENCE_JobApplication);
        
    }


    // Initialise the associations
    protected BaseBusinessClass initialiseReference ()
    {
        super.initialiseReference ();
        
        _TestInput = new SingleAssociation<Candidate, TestInput> (this, SINGLEREFERENCE_TestInput, TestInput.MULTIPLEREFERENCE_Candidates, TestInput.REFERENCE_TestInput, "oneit_sec_user_extension");
        _TestAnalysises = new MultipleAssociation<Candidate, TestAnalysis> (this, MULTIPLEREFERENCE_TestAnalysises, TestAnalysis.SINGLEREFERENCE_Candidate, TestAnalysis.REFERENCE_TestAnalysis);
        _JobApplications = new MultipleAssociation<Candidate, JobApplication> (this, MULTIPLEREFERENCE_JobApplications, JobApplication.SINGLEREFERENCE_Candidate, JobApplication.REFERENCE_JobApplication);
        
        
        return this;
    }

    

    /**
     * Get the attribute Phone
     */
    public String getPhone ()
    {
        assertValid();
        String valToReturn = _Phone;

            for (CandidateBehaviourDecorator bhd : Candidate_BehaviourDecorators)
            {
                valToReturn = bhd.getPhone ((Candidate)this, valToReturn);
            }
            
            return valToReturn;
        
    }


    /**
     * Called prior to the attribute changing.  Subclasses need not call super.  If a field exception
     * is thrown, the attribute change will fail.  The new value is different to the old value.
     */
    protected void prePhoneChange (String newPhone) throws FieldException
    {
    }


    /**
     * Called after the attribute changes.
     * If a field exception is thrown, the value is still changed, however it 
     * may lead to the TX being rolled back
     */
    protected void postPhoneChange () throws FieldException
    {
    }

    
    public FieldWriteability getWriteability_Phone ()
    {
        return getFieldWritabilityUtil (FieldWriteability.TRUE);
    }

    /**
     * Set the attribute Phone.  Checks to ensure a new value
     * has been supplied.  If so, marks the field as altered and sets the attribute.
     */
    public void setPhone (String newPhone) throws FieldException
    {
        boolean oldAndNewIdentical = HELPER_Phone.compare (_Phone, newPhone);
        
        try
        {
            for (CandidateBehaviourDecorator bhd : Candidate_BehaviourDecorators)
            {
                newPhone = bhd.setPhone ((Candidate)this, newPhone);
                oldAndNewIdentical = HELPER_Phone.compare (_Phone, newPhone);
            }

            

            if (FIELD_Phone_Validators.length > 0)
            {
                Object newPhoneObj = HELPER_Phone.toObject (newPhone);

                if (newPhoneObj != null)
                {
                    int     loopMax = FIELD_Phone_Validators.length;
                    Map     metadata = (Map)ATTRIBUTES_METADATA_Candidate.get (FIELD_Phone);

                    for (int v = 0 ; v < loopMax ; ++v)
                    {
                        FIELD_Phone_Validators[v].checkAttribute (this, FIELD_Phone, metadata, newPhoneObj);
                    }
                }
            }
        }
        catch (FieldException e)
        {
            if (!oldAndNewIdentical)
            {
                e.setWouldModify ();
            }
            
            throw e;
        }

        if (!oldAndNewIdentical)
        {
            assertValid();
            Debug.assertion (getWriteability_Phone () != FieldWriteability.FALSE, "Field  Phone is not writeable");
            prePhoneChange (newPhone);
            markFieldChange (FIELD_Phone);
            _Phone = newPhone;            
            postFieldChange (FIELD_Phone);
            postPhoneChange ();
        }
    }



    /**
     * A list of multi assoc names e.g. list of strings.
     */
    public List<String> getSingleAssocs()
    {
        List result = super.getSingleAssocs ();

        
        result.add("TestInput");
        

        return result;
    }
    
    
    public BaseBusinessClass getSingleAssocReferenceInstance (String assocName)
    {
        if (assocName == null)
        {
            throw new RuntimeException ("Game over == null!");
        }
        else if (assocName.equals (SINGLEREFERENCE_TestInput))
        {
            return _TestInput.getReferencedType ();
        }
        else
        {
            return super.getSingleAssocReferenceInstance (assocName);
        }
    }


    public String getSingleAssocBackReference(String assocName)
    {
        if (assocName == null)
        {
            throw new RuntimeException ("Game over == null!");
        }
        else if (assocName.equals (SINGLEREFERENCE_TestInput))
        {
            return TestInput.MULTIPLEREFERENCE_Candidates ;
        }
        else
        {
            return super.getSingleAssocBackReference (assocName);
        }
    }
    
    
    public BaseBusinessClass getSingleAssoc (String assocName) throws StorageException
    {
        if (assocName == null)
        {
            throw new RuntimeException ("Game over == null!");
        }
        else if (assocName.equals (SINGLEREFERENCE_TestInput))
        {
            return getTestInput ();
        }
        else
        {
            return super.getSingleAssoc (assocName);
        }
    }


    public BaseBusinessClass getSingleAssoc (String assocName, Get getType) throws StorageException
    {
        if (assocName == null)
        {
            throw new RuntimeException ("Game over == null!");
        }
        else if (assocName.equals (SINGLEREFERENCE_TestInput))
        {
            return getTestInput (getType);
        }
        else
        {
            return super.getSingleAssoc (assocName, getType);
        }
    }


    public Long getSingleAssocID (String assocName) throws StorageException
    {
        if (assocName == null)
        {
            throw new RuntimeException ("Game over == null!");
        }
        else if (assocName.equals (SINGLEREFERENCE_TestInput))
        {
            return getTestInputID ();
        }
        else
        {
            return super.getSingleAssocID (assocName);
        }
    }


    public void setSingleAssoc (String assocName, BaseBusinessClass newValue) throws StorageException, FieldException
    {
        if (assocName == null)
        {
            throw new RuntimeException ("Game over == null!");
        }
        else if (assocName.equals (SINGLEREFERENCE_TestInput))
        {
            setTestInput ((TestInput)(newValue));
        }
        else
        {
            super.setSingleAssoc (assocName, newValue);
        }
    }



    /**
     * Get the reference TestInput
     */
    public TestInput getTestInput () throws StorageException
    {
        assertValid();
        
        try
        {
            return (TestInput)(_TestInput.get ());
        }
        catch (ClassCastException e)
        {
            LogMgr.log (BUSINESS_OBJECTS, LogLevel.SYSTEMERROR2, "Cache collision in Candidate:", this.getObjectID (), ", was trying to get TestInput:",  getTestInputID ());
            LogMgr.log (BUSINESS_OBJECTS, LogLevel.SYSTEMERROR2, "Instead I got:", _TestInput.get ().getClass ());
            throw e;
        }
    }


    /**
     * Get the object id for the referenced object.  Does not force a DB access.
     */
    public TestInput getTestInput (Get getType) throws StorageException
    {
        assertValid();
        return _TestInput.get(getType);
    }


    /**
     * Get the object id for the referenced object.  Does not force a DB access.
     */
    public Long getTestInputID ()
    {
        assertValid();
        
        if (_TestInput == null)
        {
            return null;
        }
        else
        {
            return _TestInput.getID ();
        }
    }

    /**
     * Called prior to the assoc changing.  Subclasses need not call super.  If a field exception
     * is thrown, the attribute change will fail.  The new value is different to the old value.
     */
    protected void preTestInputChange (TestInput newTestInput) throws FieldException
    {
    }


    /**
     * Called after the assoc changes.
     * If a field exception is thrown, the value is still changed, however it 
     * may lead to the TX being rolled back
     */
    protected void postTestInputChange () throws FieldException
    {
    }



    
    public FieldWriteability getWriteability_TestInput ()
    {
        return getFieldWritabilityUtil (FieldWriteability.TRUE);
    }
    
    
    /**
     * Set the reference TestInput.  Checks to ensure a new value
     * has been supplied.  If so, marks the reference as altered and sets it.
     */
    public void setTestInput (TestInput newTestInput) throws StorageException, FieldException
    {
        

        if (_TestInput.wouldReferencedChange (newTestInput))
        {
            assertValid();
            Debug.assertion (getWriteability_TestInput () != FieldWriteability.FALSE, "Assoc TestInput is not writeable");
            preTestInputChange (newTestInput);
            TestInput oldTestInput = getTestInput ();

                    if (oldTestInput != null)
                    {
                        // This is to stop validation from triggering when we are removed
                        _TestInput.set (null);
                        oldTestInput.removeFromCandidates ((Candidate)(this));
                    }

                    _TestInput.set (newTestInput);

                    if (newTestInput != null)
                    {
                        newTestInput.addToCandidates ((Candidate)(this));
                    }
                
            postTestInputChange ();
        }
    }

    /**
     * A list of multi assoc names e.g. list of strings.
     */
    public List<String> getMultiAssocs()
    {
        List result = super.getMultiAssocs ();

        
        result.add("TestAnalysises");
        
        result.add("JobApplications");
        

        return result;
    }


    /**
     * Get the reference instance for the multi assoc name.
     */
    public BaseBusinessClass getMultiAssocReferenceInstance(String attribName)
    {
        
        if (MULTIPLEREFERENCE_TestAnalysises.equals(attribName))
        {
            return TestAnalysis.REFERENCE_TestAnalysis ;
        }
        
        if (MULTIPLEREFERENCE_JobApplications.equals(attribName))
        {
            return JobApplication.REFERENCE_JobApplication ;
        }
        

        return super.getMultiAssocReferenceInstance(attribName);
    }


    public String getMultiAssocBackReference(String attribName)
    {
        
        if (MULTIPLEREFERENCE_TestAnalysises.equals(attribName))
        {
            return TestAnalysis.SINGLEREFERENCE_Candidate ;
        }
        
        if (MULTIPLEREFERENCE_JobApplications.equals(attribName))
        {
            return JobApplication.SINGLEREFERENCE_Candidate ;
        }
        

        return super.getMultiAssocBackReference(attribName);
    }


    /**
     * Get the assoc count for the multi assoc name.
     */
    public int getMultiAssocCount(String attribName) throws StorageException
    {
        
        if (MULTIPLEREFERENCE_TestAnalysises.equals(attribName))
        {
            return this.getTestAnalysisesCount();
        }
        
        if (MULTIPLEREFERENCE_JobApplications.equals(attribName))
        {
            return this.getJobApplicationsCount();
        }
        

        return super.getMultiAssocCount(attribName);
    }


    /**
     * Get the assoc at a particular index
     */
    public BaseBusinessClass getMultiAssocAt(String attribName, int index) throws StorageException
    {
        
        if (MULTIPLEREFERENCE_TestAnalysises.equals(attribName))
        {
            return this.getTestAnalysisesAt(index);
        }
        
        if (MULTIPLEREFERENCE_JobApplications.equals(attribName))
        {
            return this.getJobApplicationsAt(index);
        }
        

        return super.getMultiAssocAt(attribName, index);
    }


    /**
     * Add to a multi assoc by attribute name
     */
    public void addToMultiAssoc(String attribName, BaseBusinessClass newElement) throws StorageException
    {
        
        if (MULTIPLEREFERENCE_TestAnalysises.equals(attribName))
        {
            addToTestAnalysises((TestAnalysis)newElement);

            return;
        }
        
        if (MULTIPLEREFERENCE_JobApplications.equals(attribName))
        {
            addToJobApplications((JobApplication)newElement);

            return;
        }
        

        super.addToMultiAssoc(attribName, newElement);
    }

    /**
     * Remove from a multi assoc by attribute name
     */
    public void removeFromMultiAssoc(String attribName, BaseBusinessClass oldElement) throws StorageException
    {
        
        if (MULTIPLEREFERENCE_TestAnalysises.equals(attribName))
        {
            removeFromTestAnalysises((TestAnalysis)oldElement);

            return;
        }
        
        if (MULTIPLEREFERENCE_JobApplications.equals(attribName))
        {
            removeFromJobApplications((JobApplication)oldElement);

            return;
        }
        

        super.removeFromMultiAssoc(attribName, oldElement);
    }


    protected void __loadMultiAssoc (String attribName, BaseBusinessClass[] elements)
    {
        
        if (MULTIPLEREFERENCE_TestAnalysises.equals(attribName))
        {
            _TestAnalysises.__loadAssociation (elements);
            return;
        }
        
        if (MULTIPLEREFERENCE_JobApplications.equals(attribName))
        {
            _JobApplications.__loadAssociation (elements);
            return;
        }
        

        super.__loadMultiAssoc(attribName, elements);
    }


    protected boolean __isMultiAssocLoaded (String attribName)
    {
        
        if (MULTIPLEREFERENCE_TestAnalysises.equals(attribName))
        {
            return _TestAnalysises.isLoaded ();
        }
        
        if (MULTIPLEREFERENCE_JobApplications.equals(attribName))
        {
            return _JobApplications.isLoaded ();
        }
        

        return super.__isMultiAssocLoaded(attribName);
    }

    

    public FieldWriteability getWriteability_TestAnalysises ()
    {
        return getFieldWritabilityUtil (FieldWriteability.TRUE);
    }
    
    
    public int getTestAnalysisesCount () throws StorageException
    {
        assertValid();
        return _TestAnalysises.getReferencedObjectsCount ();
    }


    public void addToTestAnalysises (TestAnalysis newElement) throws StorageException
    {
        if (_TestAnalysises.wouldAddChange (newElement))
        {
            assertValid();
            Debug.assertion (getWriteability_TestAnalysises () != FieldWriteability.FALSE, "MultiAssoc TestAnalysises is not writeable (add)");
            _TestAnalysises.appendElement (newElement);

            try
            {
                if (newElement.getCandidate () != this)
                {
                    newElement.setCandidate ((Candidate)(this));
                }
            }
            catch (Exception e)
            {
                throw NestedException.wrap(e);
            }
        }
    }


    public void removeFromTestAnalysises (TestAnalysis elementToRemove) throws StorageException
    {
        if (_TestAnalysises.wouldRemoveChange (elementToRemove))
        {
            assertValid();
            Debug.assertion (getWriteability_TestAnalysises () != FieldWriteability.FALSE, "MultiAssoc TestAnalysises is not writeable (remove)");
            _TestAnalysises.removeElement (elementToRemove);
            try
            {
                if (elementToRemove.getCandidate () != null)
                {
                    elementToRemove.setCandidate (null);
                }
            }
            catch (Exception e)
            {
                throw NestedException.wrap(e);
            }
        }
    }


    public TestAnalysis getTestAnalysisesAt (int index) throws StorageException
    {
        return (TestAnalysis)(_TestAnalysises.getElementAt (index));
    }


    public SortedSet<TestAnalysis> getTestAnalysisesSet () throws StorageException
    {
        return _TestAnalysises.getSet ();
    }

    public FieldWriteability getWriteability_JobApplications ()
    {
        return getFieldWritabilityUtil (FieldWriteability.TRUE);
    }
    
    
    public int getJobApplicationsCount () throws StorageException
    {
        assertValid();
        return _JobApplications.getReferencedObjectsCount ();
    }


    public void addToJobApplications (JobApplication newElement) throws StorageException
    {
        if (_JobApplications.wouldAddChange (newElement))
        {
            assertValid();
            Debug.assertion (getWriteability_JobApplications () != FieldWriteability.FALSE, "MultiAssoc JobApplications is not writeable (add)");
            _JobApplications.appendElement (newElement);

            try
            {
                if (newElement.getCandidate () != this)
                {
                    newElement.setCandidate ((Candidate)(this));
                }
            }
            catch (Exception e)
            {
                throw NestedException.wrap(e);
            }
        }
    }


    public void removeFromJobApplications (JobApplication elementToRemove) throws StorageException
    {
        if (_JobApplications.wouldRemoveChange (elementToRemove))
        {
            assertValid();
            Debug.assertion (getWriteability_JobApplications () != FieldWriteability.FALSE, "MultiAssoc JobApplications is not writeable (remove)");
            _JobApplications.removeElement (elementToRemove);
            try
            {
                if (elementToRemove.getCandidate () != null)
                {
                    elementToRemove.setCandidate (null);
                }
            }
            catch (Exception e)
            {
                throw NestedException.wrap(e);
            }
        }
    }


    public JobApplication getJobApplicationsAt (int index) throws StorageException
    {
        return (JobApplication)(_JobApplications.getElementAt (index));
    }


    public SortedSet<JobApplication> getJobApplicationsSet () throws StorageException
    {
        return _JobApplications.getSet ();
    }



    public void onDelete ()
    {
        try 
        {
            // Ensure we are removed from any loaded multi-associations that aren't mandatory
            if (_TestInput.isLoaded () || getTransaction ().isObjectLoaded (_TestInput.getReferencedType (), getTestInputID ()))
            {
                TestInput  referenced = getTestInput ();

                if (referenced != null)
                {
                    // Stop the callback
                    LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG1, "Setting backreference to null Candidates from ", getObjectID (), " to ", referenced.getObjectID ());
                    _TestInput.set (null);
                    referenced.removeFromCandidates ((Candidate)this);
                }
            }
        
            for(TestAnalysis referenced : CollectionUtils.reverse(getTestAnalysisesSet()))
            { 
                LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG1, "Setting backreference to null Candidate from ", getObjectID (), " to ", referenced.getObjectID ());
                referenced.setCandidate(null);
            }

            for(JobApplication referenced : CollectionUtils.reverse(getJobApplicationsSet()))
            { 
                LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG1, "Setting backreference to null Candidate from ", getObjectID (), " to ", referenced.getObjectID ());
                referenced.setCandidate(null);
            }

        }
        catch (Exception e)
        {
            throw NestedException.wrap(e);
        }

        super.onDelete ();
    }


    public Candidate newInstance ()
    {
        return new Candidate ();
    }


    public Candidate referenceInstance ()
    {
        return REFERENCE_Candidate;
    }


    public Candidate getInTransaction (ObjectTransaction t) throws StorageException
    {
        return getCandidateByID (t, getObjectID());
    }
    
    
    public BaseBusinessClass dummyInstance ()
    {
        return DUMMY_Candidate;
    }


    public String getBaseSetName ()
    {
        return "oneit_sec_user_extension";
    }





    /**
     * This is where an object returns the Persistent sets that will
     * store it into the database.
     * The should be entered into allSets
     */
    public void getPersistentSets (PersistentSetCollection allSets)
    {
        ObjectStatus        myStatus = getStatus ();
        PersistentSetStatus myPSetStatus = myStatus.getPSetStatus();
        ObjectID            myID = getID();

        super.getPersistentSets (allSets);

        
        PersistentSet   oneit_sec_user_extensionPSet = allSets.getPersistentSet (myID, "oneit_sec_user_extension", myPSetStatus);

        oneit_sec_user_extensionPSet.setAttrib (FIELD_ObjectID, myID);
        oneit_sec_user_extensionPSet.setAttrib (FIELD_Phone, HELPER_Phone.toObject (_Phone)); //
        _TestInput.getPersistentSets (allSets);
        
    }


    /**
     * Sets the objects state based on Persistent sets.
     */
    public void setFromPersistentSets (ObjectID objectID, PersistentSetCollection allSets)
    {
        super.setFromPersistentSets (objectID, allSets);

        
        PersistentSet   oneit_sec_user_extensionPSet = allSets.getPersistentSet (objectID, "oneit_sec_user_extension");

        _Phone = (String)(HELPER_Phone.fromObject (_Phone, oneit_sec_user_extensionPSet.getAttrib (FIELD_Phone))); //
        _TestInput.setFromPersistentSets (objectID, allSets);
        
    }





    public void setAttributesFrom (BaseBusinessClass other, MultiException e)
    {
        super.setAttributesFrom (other, e);

        if (other instanceof Candidate)
        {
            Candidate otherCandidate = (Candidate)other;
            
            try
            {
                setPhone (otherCandidate.getPhone ());
            }
            catch (FieldException ex)
            {
                e.addException (ex);
            }
            
        }
    }


    /**
     * Set the attributes in this to copies of the attributes in source.
     */
    public void copyAttributesFrom (BaseBusinessClass source)
    {
        super.copyAttributesFrom (source);

        if (source instanceof BaseCandidate)
        {
            BaseCandidate sourceCandidate = (BaseCandidate)(source);

            _Phone = sourceCandidate._Phone;
            
        }
    }


    /**
     * Set the associations in this to copies of the attributes in source.
     */
    public void copySingleAssociationsFrom (BaseBusinessClass source, boolean linkToGhosts)
    {
        super.copySingleAssociationsFrom (source, linkToGhosts);

        if (source instanceof BaseCandidate)
        {
            BaseCandidate sourceCandidate = (BaseCandidate)(source);

            _TestInput.copyFrom (sourceCandidate._TestInput, linkToGhosts);
            
        }
    }


    /**
     * Set the associations in this to copies of the attributes in source.
     */
    public void copyAssociationsFrom (BaseBusinessClass source, boolean linkToGhosts)
    {
        super.copyAssociationsFrom (source, linkToGhosts);

        if (source instanceof BaseCandidate)
        {
            BaseCandidate sourceCandidate = (BaseCandidate)(source);

            _TestAnalysises.copyFrom (sourceCandidate._TestAnalysises, linkToGhosts);
            _JobApplications.copyFrom (sourceCandidate._JobApplications, linkToGhosts);
            
        }
    }


    public void validate (ValidationContext context)
    {
        super.validate (context);

        
    }


    /**
     * Subclasses must override this to read in their attributes
     */
    protected void readExternalData(Map<String, Object> vals) throws IOException, ClassNotFoundException
    {
        super.readExternalData(vals);

        _Phone = (String)(HELPER_Phone.readExternal (_Phone, vals.get(FIELD_Phone))); //
        _TestInput.readExternalData(vals.get(SINGLEREFERENCE_TestInput));
        _TestAnalysises.readExternalData(vals.get(MULTIPLEREFERENCE_TestAnalysises));
        _JobApplications.readExternalData(vals.get(MULTIPLEREFERENCE_JobApplications));
        
    }


    /**
     * Subclasses must override this to write out their attributes
     */
    protected void writeExternalData(Map<String, Object> vals) throws IOException
    {
        super.writeExternalData(vals);

        vals.put (FIELD_Phone, HELPER_Phone.writeExternal (_Phone));
        vals.put (SINGLEREFERENCE_TestInput, _TestInput.writeExternalData());
        vals.put (MULTIPLEREFERENCE_TestAnalysises, _TestAnalysises.writeExternalData());
        vals.put (MULTIPLEREFERENCE_JobApplications, _JobApplications.writeExternalData());
        
    }


    public void compare (BaseBusinessClass other, AttributeChangeListener listener) throws StorageException
    {
        super.compare (other, listener);

        if (other instanceof BaseCandidate)
        {
            BaseCandidate otherCandidate = (BaseCandidate)(other);

            
            if (!HELPER_Phone.compare(this._Phone, otherCandidate._Phone))
            {
                listener.notifyFieldChange(this, other, FIELD_Phone, HELPER_Phone.toObject(this._Phone), HELPER_Phone.toObject(otherCandidate._Phone));
            }

            // Compare single assocs
            _TestInput.compare (otherCandidate._TestInput, listener);
            

            // Compare multiple assocs
            _TestAnalysises.compare (otherCandidate._TestAnalysises, listener);
            _JobApplications.compare (otherCandidate._JobApplications, listener);
            
        }
    }


    public void visitTransients (AttributeVisitor visitor) throws StorageException
    {
        super.visitAttributes (visitor);

        
    }


    public void visitAttributes (AttributeVisitor visitor) throws StorageException
    {
        super.visitAttributes (visitor);

        visitor.visitField(this, FIELD_Phone, HELPER_Phone.toObject(getPhone()));
        visitor.visitAssociation (_TestInput);
        visitor.visitAssociation (_TestAnalysises);
        visitor.visitAssociation (_JobApplications);
        
    }


    public void visitAssociations (AssociationVisitor visitor, AssociatedScope scope) throws StorageException
    {
        super.visitAssociations (visitor, scope);

        if (scope.includes (_TestInput))
        {
            visitor.visit (_TestInput);
        }
        if (scope.includes (_TestAnalysises))
        {
            visitor.visit (_TestAnalysises);
        }
        if (scope.includes (_JobApplications))
        {
            visitor.visit (_JobApplications);
        }
        
    }


    public static Candidate createCandidate (ObjectTransaction transaction) throws StorageException
    {
        Candidate     result = new Candidate ();

        result.initialiseNewObject (transaction);

        return result;
    }


    public static Candidate getCandidateByID (ObjectTransaction transaction, Long objectID) throws StorageException
    {
        return (Candidate)(transaction.getObjectByID (REFERENCE_Candidate, objectID));
    }

    public boolean testFilter (String attribName, QueryFilter filter) throws StorageException
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_Phone))
        {
            return filter.matches (getPhone ());
        }
        else if (attribName.equals (SINGLEREFERENCE_TestInput))
        {
            return filter.matches (getTestInput ());
        }
        else
        {
            return super.testFilter (attribName, filter);
        }
    }




    public Object getAttribute (String attribName)
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_Phone))
        {
            return HELPER_Phone.toObject (getPhone ());
        }
        else
        {
            return super.getAttribute (attribName);
        }
    }


    public AttributeHelper getAttributeHelper (String attribName)
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_Phone))
        {
            return HELPER_Phone;
        }
        else
        {
            return super.getAttributeHelper (attribName);
        }
    }


    public void setAttribute (String attribName, Object attribValue) throws FieldException
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_Phone))
        {
            setPhone ((String)(HELPER_Phone.fromObject (_Phone, attribValue)));            
        }
        else
        {
            super.setAttribute (attribName, attribValue);
        }
    }



    public boolean isWriteable (String fieldName)
    {
        return getWriteable (fieldName) == FieldWriteability.TRUE;
    }


    public FieldWriteability getWriteable (String fieldName)
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (fieldName.equals (FIELD_Phone))
        {
            return getWriteability_Phone ();
        }
        else if (fieldName.equals (MULTIPLEREFERENCE_TestAnalysises))
        {
            return getWriteability_TestAnalysises ();
        }
        else if (fieldName.equals (MULTIPLEREFERENCE_JobApplications))
        {
            return getWriteability_JobApplications ();
        }
        else if (fieldName.equals (SINGLEREFERENCE_TestInput))
        {
            return getWriteability_TestInput ();
        }
        else
        {
            return super.getWriteable (fieldName);
        }
    }


    public void putUnwriteable (Set<String> fields)
    {
        
            if (getWriteability_Phone () != FieldWriteability.TRUE)
            {
                fields.add (FIELD_Phone);
            }
        

        super.putUnwriteable (fields);
    }

    public List<AbstractAttribute> getAttributes ()
    {
        List result = super.getAttributes ();

        
        result.add(HELPER_Phone.getAttribObject (getClass (), _Phone, false, FIELD_Phone));

        return result;
    }


    public Map getAttributeMetadata (String attribute)
    {
        if (ATTRIBUTES_METADATA_Candidate.containsKey (attribute))
        {
            return (Map)ATTRIBUTES_METADATA_Candidate.get (attribute);
        }
        else
        {
            return super.getAttributeMetadata (attribute);
        }
    }


    public Object getAttributeMetadata (String attribute, String metadata)
    {
        if (ATTRIBUTES_METADATA_Candidate.containsKey (attribute))
        {
            return ((Map)ATTRIBUTES_METADATA_Candidate.get (attribute)).get(metadata);
        }
        else
        {
            return super.getAttributeMetadata (attribute, metadata);
        }
    }

    public void preCommit (boolean willBeStored) throws Exception
    {
        super.preCommit(willBeStored);
        
        if(willBeStored)
        {
        
        }
    }

    public oneit.servlets.objstore.binary.BinaryContentHandler getBinaryContentHandler(String attribName)
    {
        
        
        return super.getBinaryContentHandler(attribName);
    }

    public static class CandidateBehaviourDecorator extends BaseBusinessClass.BBCBehaviourDecorator<Candidate>
    {

    /**
     * Get the attribute Phone
     */
    public String getPhone (Candidate obj, String original)
    {
        return original;
    }

    /**
     * Change the value set for attribute Phone.
     * May modify the field beforehand
     * Occurs before validation.
     */
    public String setPhone (Candidate obj, String newPhone) throws FieldException
    {
        return newPhone;
    }

    }

    
    public ORMPipeLine pipes()
    {
        return new CandidatePipeLineFactory<Candidate, Candidate> ((Candidate)this);
    }
      
    /**
     * Use this instead of pipes() to get rid of type casting.
     */  
    public CandidatePipeLineFactory<Candidate, Candidate> pipelineCandidate()
    {
        return (CandidatePipeLineFactory<Candidate, Candidate>) pipes();
    }
    
    public static CandidatePipeLineFactory<Candidate, Candidate> pipesCandidate(Collection<Candidate> items)
    {
        return REFERENCE_Candidate.new CandidatePipeLineFactory<Candidate, Candidate> (items);
    }
    
    public static CandidatePipeLineFactory<Candidate, Candidate> pipesCandidate(Candidate[] _items)
    {
        return pipesCandidate(Arrays.asList (_items));
    }
    
    public static CandidatePipeLineFactory<Candidate, Candidate> pipesCandidate()
    {
        return pipesCandidate((Collection)null);
    }
    
    
    public class CandidatePipeLineFactory<From extends BaseBusinessClass, Me extends Candidate> extends SecUserExtensionPipeLineFactory<From, Me>    
    {
        public <Prev> CandidatePipeLineFactory (PipeLine<From, Prev> pipeLine, Pipe<Prev, Me> nextPipe)
        {
            super (pipeLine, nextPipe);
        }
        
        public CandidatePipeLineFactory (From seed)
        {
            super(seed);
        }

        public CandidatePipeLineFactory (Collection<From> seed)
        {
            super(seed);
        }
        
        
        public PipeLine<From, ? extends Object> to(String name)
        {
            if (name.equals ("TestAnalysises"))
            {
                return toTestAnalysises ();
            }                
            if (name.equals ("JobApplications"))
            {
                return toJobApplications ();
            }                
            if (name.equals ("Phone"))
            {
                return toPhone ();
            }                
            if (name.equals ("TestInput"))
            {
                return toTestInput ();
            }                
            
            
            return super.to(name);
        }
        
        
        public PipeLine<From, String> toPhone () { return pipe(new ORMAttributePipe<Me, String>(FIELD_Phone));  }
        public TestInput.TestInputPipeLineFactory<From, TestInput> toTestInput () { return toTestInput (Filter.ALL); }

        public TestInput.TestInputPipeLineFactory<From, TestInput> toTestInput (Filter<TestInput> filter) 
        { 
            return TestInput.REFERENCE_TestInput.new TestInputPipeLineFactory<From, TestInput> (this, new ORMSingleAssocPipe<Me, TestInput>(SINGLEREFERENCE_TestInput, filter)); 
        }
        public TestAnalysis.TestAnalysisPipeLineFactory<From, TestAnalysis> toTestAnalysises () { return toTestAnalysises(Filter.ALL); }        

        public TestAnalysis.TestAnalysisPipeLineFactory<From, TestAnalysis> toTestAnalysises (Filter<TestAnalysis> filter)
        {
            return TestAnalysis.REFERENCE_TestAnalysis.new TestAnalysisPipeLineFactory<From, TestAnalysis> (this, new ORMMultiAssocPipe<Me, TestAnalysis>(MULTIPLEREFERENCE_TestAnalysises, filter)); 
        }
        public JobApplication.JobApplicationPipeLineFactory<From, JobApplication> toJobApplications () { return toJobApplications(Filter.ALL); }        

        public JobApplication.JobApplicationPipeLineFactory<From, JobApplication> toJobApplications (Filter<JobApplication> filter)
        {
            return JobApplication.REFERENCE_JobApplication.new JobApplicationPipeLineFactory<From, JobApplication> (this, new ORMMultiAssocPipe<Me, JobApplication>(MULTIPLEREFERENCE_JobApplications, filter)); 
        }
        
    }
    
    public boolean isTransientAttrib(String attribName)
    {
        

        return super.isTransientAttrib(attribName);
    }

    public boolean isTransientSingleReference(String assocName)
    {
        

        return super.isTransientSingleReference(assocName);
    }
}

class DummyCandidate extends Candidate
{
    // Default constructor primarily to support Externalisable
    public DummyCandidate()
    {
        super();
    }

    public void assertValid ()
    {
    }


    public TestInput getTestInput () throws StorageException
    {
        return (TestInput)(TestInput.DUMMY_TestInput);
    }


    /**
     * Get the object id for the referenced object.  Does not force a DB access.
     */
    public Long getTestInputID ()
    {
        return TestInput.DUMMY_TestInput.getObjectID();
    }

    public int getTestAnalysisesCount () throws StorageException
    {
        return 0;
    }


    public TestAnalysis getTestAnalysisesAt (int index) throws StorageException
    {
        throw new RuntimeException ("No elements in a dummy object in association TestAnalysises");
    }


    public SortedSet getTestAnalysisesSet () throws StorageException
    {
        return new TreeSet();
    }

    public int getJobApplicationsCount () throws StorageException
    {
        return 0;
    }


    public JobApplication getJobApplicationsAt (int index) throws StorageException
    {
        throw new RuntimeException ("No elements in a dummy object in association JobApplications");
    }


    public SortedSet getJobApplicationsSet () throws StorageException
    {
        return new TreeSet();
    }

}

    
