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



public abstract class BaseCandidate extends BaseBusinessClass
{
    // 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_FirstName = "FirstName";
    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_Answers = "Answers";
    public static final String BACKREF_Answers = "";

    // Static constants corresponding to searches
    public static final String SEARCH_All = "All";
    

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

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

    // 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, Answer> _Answers;
    

    // 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_FirstName_Validators;
    

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

            setupAssocMetaData_TestAnalysises();
            setupAssocMetaData_Answers();
            setupAssocMetaData_TestInput();
            FIELD_FirstName_Validators = (AttributeValidator[])setupAttribMetaData_FirstName(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_Answers()
    {
        Map metaInfo = new HashMap ();

        metaInfo.put ("backreferenceName", "Candidate");
        metaInfo.put ("name", "Answers");
        metaInfo.put ("type", "Answer");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Candidate.Answers:", metaInfo);
        ATTRIBUTES_METADATA_Candidate.put (MULTIPLEREFERENCE_Answers, 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_FirstName(Map validatorMapping)
    {
        Map  metaInfo   = new HashMap ();

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

        List validators = BaseBusinessClass.getAttribValidators(Candidate.class, "FirstName", metaInfo, validatorMapping);
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG1, "Validators for Candidate.FirstName:", 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);

        
        _FirstName = (String)(HELPER_FirstName.initialise (_FirstName));
    }


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

        _TestInput = new SingleAssociation<Candidate, TestInput> (this, SINGLEREFERENCE_TestInput, TestInput.MULTIPLEREFERENCE_Candidates, TestInput.REFERENCE_TestInput, "rs_candidate");
        _TestAnalysises = new MultipleAssociation<Candidate, TestAnalysis> (this, MULTIPLEREFERENCE_TestAnalysises, TestAnalysis.SINGLEREFERENCE_Candidate, TestAnalysis.REFERENCE_TestAnalysis);
        _Answers = new MultipleAssociation<Candidate, Answer> (this, MULTIPLEREFERENCE_Answers, Answer.SINGLEREFERENCE_Candidate, Answer.REFERENCE_Answer);
        
    }


    // Initialise the associations
    protected BaseBusinessClass initialiseReference ()
    {
        super.initialiseReference ();
        
        _TestInput = new SingleAssociation<Candidate, TestInput> (this, SINGLEREFERENCE_TestInput, TestInput.MULTIPLEREFERENCE_Candidates, TestInput.REFERENCE_TestInput, "rs_candidate");
        _TestAnalysises = new MultipleAssociation<Candidate, TestAnalysis> (this, MULTIPLEREFERENCE_TestAnalysises, TestAnalysis.SINGLEREFERENCE_Candidate, TestAnalysis.REFERENCE_TestAnalysis);
        _Answers = new MultipleAssociation<Candidate, Answer> (this, MULTIPLEREFERENCE_Answers, Answer.SINGLEREFERENCE_Candidate, Answer.REFERENCE_Answer);
        
        
        return this;
    }

    

    /**
     * Get the attribute FirstName
     */
    public String getFirstName ()
    {
        assertValid();
        String valToReturn = _FirstName;

            for (CandidateBehaviourDecorator bhd : Candidate_BehaviourDecorators)
            {
                valToReturn = bhd.getFirstName ((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 preFirstNameChange (String newFirstName) 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 postFirstNameChange () throws FieldException
    {
    }

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

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

            

            if (FIELD_FirstName_Validators.length > 0)
            {
                Object newFirstNameObj = HELPER_FirstName.toObject (newFirstName);

                if (newFirstNameObj != null)
                {
                    int     loopMax = FIELD_FirstName_Validators.length;
                    Map     metadata = (Map)ATTRIBUTES_METADATA_Candidate.get (FIELD_FirstName);

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

        if (!oldAndNewIdentical)
        {
            assertValid();
            Debug.assertion (getWriteability_FirstName () != FieldWriteability.FALSE, "Field  FirstName is not writeable");
            preFirstNameChange (newFirstName);
            markFieldChange (FIELD_FirstName);
            _FirstName = newFirstName;            
            postFieldChange (FIELD_FirstName);
            postFirstNameChange ();
        }
    }



    /**
     * 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("Answers");
        

        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_Answers.equals(attribName))
        {
            return Answer.REFERENCE_Answer ;
        }
        

        return super.getMultiAssocReferenceInstance(attribName);
    }


    public String getMultiAssocBackReference(String attribName)
    {
        
        if (MULTIPLEREFERENCE_TestAnalysises.equals(attribName))
        {
            return TestAnalysis.SINGLEREFERENCE_Candidate ;
        }
        
        if (MULTIPLEREFERENCE_Answers.equals(attribName))
        {
            return Answer.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_Answers.equals(attribName))
        {
            return this.getAnswersCount();
        }
        

        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_Answers.equals(attribName))
        {
            return this.getAnswersAt(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_Answers.equals(attribName))
        {
            addToAnswers((Answer)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_Answers.equals(attribName))
        {
            removeFromAnswers((Answer)oldElement);

            return;
        }
        

        super.removeFromMultiAssoc(attribName, oldElement);
    }


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

        super.__loadMultiAssoc(attribName, elements);
    }


    protected boolean __isMultiAssocLoaded (String attribName)
    {
        
        if (MULTIPLEREFERENCE_TestAnalysises.equals(attribName))
        {
            return _TestAnalysises.isLoaded ();
        }
        
        if (MULTIPLEREFERENCE_Answers.equals(attribName))
        {
            return _Answers.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_Answers ()
    {
        return getFieldWritabilityUtil (FieldWriteability.TRUE);
    }
    
    
    public int getAnswersCount () throws StorageException
    {
        assertValid();
        return _Answers.getReferencedObjectsCount ();
    }


    public void addToAnswers (Answer newElement) throws StorageException
    {
        if (_Answers.wouldAddChange (newElement))
        {
            assertValid();
            Debug.assertion (getWriteability_Answers () != FieldWriteability.FALSE, "MultiAssoc Answers is not writeable (add)");
            _Answers.appendElement (newElement);

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


    public void removeFromAnswers (Answer elementToRemove) throws StorageException
    {
        if (_Answers.wouldRemoveChange (elementToRemove))
        {
            assertValid();
            Debug.assertion (getWriteability_Answers () != FieldWriteability.FALSE, "MultiAssoc Answers is not writeable (remove)");
            _Answers.removeElement (elementToRemove);
            try
            {
                if (elementToRemove.getCandidate () != null)
                {
                    elementToRemove.setCandidate (null);
                }
            }
            catch (Exception e)
            {
                throw NestedException.wrap(e);
            }
        }
    }


    public Answer getAnswersAt (int index) throws StorageException
    {
        return (Answer)(_Answers.getElementAt (index));
    }


    public SortedSet<Answer> getAnswersSet () throws StorageException
    {
        return _Answers.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(Answer referenced : CollectionUtils.reverse(getAnswersSet()))
            { 
                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 "rs_candidate";
    }





    /**
     * 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   rs_candidatePSet = allSets.getPersistentSet (myID, "rs_candidate", myPSetStatus);

        rs_candidatePSet.setAttrib (FIELD_ObjectID, myID);
        rs_candidatePSet.setAttrib (FIELD_FirstName, HELPER_FirstName.toObject (_FirstName)); //
        _TestInput.getPersistentSets (allSets);
        
    }


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

        
        PersistentSet   rs_candidatePSet = allSets.getPersistentSet (objectID, "rs_candidate");

        _FirstName = (String)(HELPER_FirstName.fromObject (_FirstName, rs_candidatePSet.getAttrib (FIELD_FirstName))); //
        _TestInput.setFromPersistentSets (objectID, allSets);
        
    }





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

        if (other instanceof Candidate)
        {
            Candidate otherCandidate = (Candidate)other;
            
            try
            {
                setFirstName (otherCandidate.getFirstName ());
            }
            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);

            _FirstName = sourceCandidate._FirstName;
            
        }
    }


    /**
     * 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);
            _Answers.copyFrom (sourceCandidate._Answers, 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);

        _FirstName = (String)(HELPER_FirstName.readExternal (_FirstName, vals.get(FIELD_FirstName))); //
        _TestInput.readExternalData(vals.get(SINGLEREFERENCE_TestInput));
        _TestAnalysises.readExternalData(vals.get(MULTIPLEREFERENCE_TestAnalysises));
        _Answers.readExternalData(vals.get(MULTIPLEREFERENCE_Answers));
        
    }


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

        vals.put (FIELD_FirstName, HELPER_FirstName.writeExternal (_FirstName));
        vals.put (SINGLEREFERENCE_TestInput, _TestInput.writeExternalData());
        vals.put (MULTIPLEREFERENCE_TestAnalysises, _TestAnalysises.writeExternalData());
        vals.put (MULTIPLEREFERENCE_Answers, _Answers.writeExternalData());
        
    }


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

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

            
            if (!HELPER_FirstName.compare(this._FirstName, otherCandidate._FirstName))
            {
                listener.notifyFieldChange(this, other, FIELD_FirstName, HELPER_FirstName.toObject(this._FirstName), HELPER_FirstName.toObject(otherCandidate._FirstName));
            }

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

            // Compare multiple assocs
            _TestAnalysises.compare (otherCandidate._TestAnalysises, listener);
            _Answers.compare (otherCandidate._Answers, 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_FirstName, HELPER_FirstName.toObject(getFirstName()));
        visitor.visitAssociation (_TestInput);
        visitor.visitAssociation (_TestAnalysises);
        visitor.visitAssociation (_Answers);
        
    }


    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 (_Answers))
        {
            visitor.visit (_Answers);
        }
        
    }


    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_FirstName))
        {
            return filter.matches (getFirstName ());
        }
        else if (attribName.equals (SINGLEREFERENCE_TestInput))
        {
            return filter.matches (getTestInput ());
        }
        else
        {
            return super.testFilter (attribName, filter);
        }
    }


    public static SearchAll SearchByAll () { return new SearchAll (); }

    public static class SearchAll extends SearchObject<Candidate>
    {
        
            public SearchAll andObjectID (QueryFilter<Long> filter)
            {
                filter.addFilter (context, "rs_candidate.object_id", FIELD_ObjectID);
                return this;
            }

            public SearchAll andObjectCreated (QueryFilter<Date> filter)
            {
                filter.addFilter (context, "rs_candidate.object_created_date", FIELD_ObjectCreated);
                return this;
            }

            public SearchAll andObjectLastModified (QueryFilter<Date> filter)
            {
                filter.addFilter (context, "rs_candidate.object_last_updated_date", FIELD_ObjectLastModified);
                return this;
            }

            
            public SearchAll andFirstName (QueryFilter<String> filter)
            {
                filter.addFilter (context, "rs_candidate.first_name", "FirstName");
                return this;
            }
            
            public SearchAll andTestInput (QueryFilter<TestInput> filter)
            {
                filter.addFilter (context, "rs_candidate.test_input_id", "TestInput");
                return this;
            }
            
                public Candidate[]
             search (ObjectTransaction transaction) throws StorageException
        {
            
            
            BaseBusinessClass[]     results = super.search (transaction, REFERENCE_Candidate, SEARCH_All, criteria);
            Set<Candidate>   typedResults = new LinkedHashSet <Candidate> ();
            for (BaseBusinessClass bbcResult : results)
            {
                Candidate aResult = (Candidate)bbcResult;
                
                typedResults.add (aResult);
            }
            
                    return ObjstoreUtils.removeDeleted(transaction, typedResults).toArray (new Candidate[0]);
                            
        }
    }

        
                public static Candidate[]
             searchAll (ObjectTransaction transaction) throws StorageException
        {
            return SearchByAll ()
            .search (transaction);
        }



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


    public AttributeHelper getAttributeHelper (String attribName)
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_FirstName))
        {
            return HELPER_FirstName;
        }
        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_FirstName))
        {
            setFirstName ((String)(HELPER_FirstName.fromObject (_FirstName, 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_FirstName))
        {
            return getWriteability_FirstName ();
        }
        else if (fieldName.equals (MULTIPLEREFERENCE_TestAnalysises))
        {
            return getWriteability_TestAnalysises ();
        }
        else if (fieldName.equals (MULTIPLEREFERENCE_Answers))
        {
            return getWriteability_Answers ();
        }
        else if (fieldName.equals (SINGLEREFERENCE_TestInput))
        {
            return getWriteability_TestInput ();
        }
        else
        {
            return super.getWriteable (fieldName);
        }
    }


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

        super.putUnwriteable (fields);
    }

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

        
        result.add(HELPER_FirstName.getAttribObject (getClass (), _FirstName, false, FIELD_FirstName));

        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 FirstName
     */
    public String getFirstName (Candidate obj, String original)
    {
        return original;
    }

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

    }

    
    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 BaseBusinessClass.ORMPipeLine<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 ("Answers"))
            {
                return toAnswers ();
            }                
            if (name.equals ("FirstName"))
            {
                return toFirstName ();
            }                
            if (name.equals ("TestInput"))
            {
                return toTestInput ();
            }                
            
            
            return super.to(name);
        }
        
        
        public PipeLine<From, String> toFirstName () { return pipe(new ORMAttributePipe<Me, String>(FIELD_FirstName));  }
        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 Answer.AnswerPipeLineFactory<From, Answer> toAnswers () { return toAnswers(Filter.ALL); }        

        public Answer.AnswerPipeLineFactory<From, Answer> toAnswers (Filter<Answer> filter)
        {
            return Answer.REFERENCE_Answer.new AnswerPipeLineFactory<From, Answer> (this, new ORMMultiAssocPipe<Me, Answer>(MULTIPLEREFERENCE_Answers, 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 getAnswersCount () throws StorageException
    {
        return 0;
    }


    public Answer getAnswersAt (int index) throws StorageException
    {
        throw new RuntimeException ("No elements in a dummy object in association Answers");
    }


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

}

    
