/*
 * IMPORTANT!!!! XSL Autogenerated class, DO NOT EDIT!!!!!
 * Template: Infrastructure9.0 [oneit.objstore.BusinessObjectTemplate.xsl]
 *   Vendor: Apache Software Foundation (Xalan XSLTC) (Version: 1.0)
 */
    
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.servlets.orm.*;

// __#BUILD_NO_TABLE_NAME#: No table name == No persistence manager and scripts required.

public abstract class BaseTestInput extends NonPersistentBO
{
    // Reference instance for the object
    public static final TestInput REFERENCE_TestInput = new TestInput ();

    // Reference instance for the object
    public static final TestInput DUMMY_TestInput = new DummyTestInput ();

    // Static constants corresponding to field names
    
    public static final String FIELD_CSV = "CSV";
    public static final String SINGLEREFERENCE_Level = "Level";
    public static final String MULTIPLEREFERENCE_Candidates = "Candidates";
    public static final String BACKREF_Candidates = "";

    // Static constants corresponding to searches
    

    // Static constants corresponding to attribute helpers
    private static final BLOBAttributeHelper HELPER_CSV = BLOBAttributeHelper.INSTANCE;
    

    // Private attributes corresponding to business object data
    private BinaryContent _CSV;
    

    // Private attributes corresponding to single references
    private SingleAssociation<TestInput, Level> _Level;
    

    // Private attributes corresponding to multiple references
    private MultipleAssociation<TestInput, Candidate> _Candidates;
    

    // Map of maps of metadata
    private static final Map ATTRIBUTES_METADATA_TestInput = new LinkedHashMap ();

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

    // Arrays of AttributeDecorators for each attribute
    private static final AttributeDecorator<TestInput, BinaryContent>[] FIELD_CSV_Decorators;
    
    
    // Arrays of SingleAssocDecorators for each attribute
    private static final SingleAssocDecorator<TestInput, Level>[] SINGLEREFERENCE_Level_Decorators;
    
    
    // Arrays of MultiAssocDecorators for each attribute
    private static final MultiAssocDecorator<TestInput, Candidate>[] MULTIPLEREFERENCE_Candidates_Decorators;
    

    // Arrays of behaviour decorators
    private static final TestInputBehaviourDecorator[] TestInput_BehaviourDecorators;
    
    static
    {
        try
        {
            
            String tmp_Candidates = Candidate.BACKREF_TestInput;
            
            Map  validatorMapping = ((Map)ConfigMgr.getConfigObject ("CONFIG.ORMVALIDATOR", "ValidatorMapping"));

            setupAssocMetaData_Candidates();
            setupAssocMetaData_Level();
            FIELD_CSV_Validators = (AttributeValidator[])setupAttribMetaData_CSV(validatorMapping).toArray (new AttributeValidator[0]);
            FIELD_CSV_Decorators = (AttributeDecorator[])AttributeDecoratorUtils.getAttributeDecorators(REFERENCE_TestInput, FIELD_CSV).toArray (new AttributeDecorator[0]);
            SINGLEREFERENCE_Level_Decorators = (SingleAssocDecorator[])AttributeDecoratorUtils.getSingleAssocDecorators(REFERENCE_TestInput, SINGLEREFERENCE_Level).toArray (new SingleAssocDecorator[0]);
            MULTIPLEREFERENCE_Candidates_Decorators = (MultiAssocDecorator[])AttributeDecoratorUtils.getMultiAssocDecorators(REFERENCE_TestInput, MULTIPLEREFERENCE_Candidates).toArray (new MultiAssocDecorator[0]);
            

            REFERENCE_TestInput.initialiseReference ();
            DUMMY_TestInput.initialiseReference ();
            TestInput_BehaviourDecorators = BaseBusinessClass.getBBCBehaviours(TestInput.class).toArray(new TestInputBehaviourDecorator[0]);
        }
        catch (RuntimeException e)
        {
            LogMgr.log (BUSINESS_OBJECTS, LogLevel.SYSTEMERROR1, e, "Error initialising");
            throw e;
        }
    }

    
    private static void setupAssocMetaData_Candidates()
    {
        Map metaInfo = new HashMap ();

        metaInfo.put ("backreferenceName", "TestInput");
        metaInfo.put ("name", "Candidates");
        metaInfo.put ("owner", "true");
        metaInfo.put ("type", "Candidate");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for TestInput.Candidates:", metaInfo);
        ATTRIBUTES_METADATA_TestInput.put (MULTIPLEREFERENCE_Candidates, Collections.unmodifiableMap (metaInfo));
    }
    
    
    private static void setupAssocMetaData_Level()
    {
        Map metaInfo = new HashMap ();

        metaInfo.put ("mandatory", "true");
        metaInfo.put ("name", "Level");
        metaInfo.put ("type", "Level");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for TestInput.Level:", metaInfo);
        ATTRIBUTES_METADATA_TestInput.put (SINGLEREFERENCE_Level, Collections.unmodifiableMap (metaInfo));
    }
    
    
    private static List setupAttribMetaData_CSV(Map validatorMapping)
    {
        Map  metaInfo   = new HashMap ();

        metaInfo.put ("attribHelper", "BLOBAttributeHelper");
        metaInfo.put ("attribHelperInstance", "BLOBAttributeHelper.INSTANCE");
        metaInfo.put ("binaryHandler", "loggedin");
        metaInfo.put ("mandatory", "true");
        metaInfo.put ("name", "CSV");
        metaInfo.put ("type", "BinaryContent");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for TestInput.CSV:", metaInfo);
        ATTRIBUTES_METADATA_TestInput.put (FIELD_CSV, Collections.unmodifiableMap (metaInfo));

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

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


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

    


    protected void _initialiseNewObjAttributes (ObjectTransaction transaction) throws StorageException
    {
        super._initialiseNewObjAttributes (transaction);

        
        _CSV = (BinaryContent)(HELPER_CSV.initialise (_CSV));
    }


    protected void _initialiseAssociations ()
    {
        super._initialiseAssociations ();

        _Level = new SingleAssociation<TestInput, Level> (this, SINGLEREFERENCE_Level, null, Level.REFERENCE_Level, "");
        _Candidates = new MultipleAssociation<TestInput, Candidate> (this, MULTIPLEREFERENCE_Candidates, Candidate.SINGLEREFERENCE_TestInput, Candidate.REFERENCE_Candidate);
    }


    protected BaseBusinessClass initialiseReference ()
    {
        super.initialiseReference ();
        
        _Level = new SingleAssociation<TestInput, Level> (this, SINGLEREFERENCE_Level, null, Level.REFERENCE_Level, "");
        _Candidates = new MultipleAssociation<TestInput, Candidate> (this, MULTIPLEREFERENCE_Candidates, Candidate.SINGLEREFERENCE_TestInput, Candidate.REFERENCE_Candidate);
        
        return this;
    }


    /**
     * Attribute CSV
     */
    public BinaryContent getCSV ()
    {
        assertValid();
        BinaryContent valToReturn = AttributeDecoratorUtils.getValue (FIELD_CSV_Decorators, (TestInput)this, FIELD_CSV, _CSV);

        
        for (TestInputBehaviourDecorator bhd : TestInput_BehaviourDecorators)
        {
            valToReturn = bhd.getCSV ((TestInput)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 preCSVChange (BinaryContent newCSV) 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 postCSVChange () throws FieldException
    {
    }

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

    /**
     * Set the attribute CSV.  Checks to ensure a new value
     * has been supplied.  If so, marks the field as altered and sets the attribute.
     */
    public void setCSV (BinaryContent newCSV) throws FieldException
    {
        newCSV = AttributeDecoratorUtils.setValue (FIELD_CSV_Decorators, (TestInput)this, FIELD_CSV, newCSV);

        boolean oldAndNewIdentical = HELPER_CSV.compare (_CSV, newCSV);
        
        try
        {
            for (TestInputBehaviourDecorator bhd : TestInput_BehaviourDecorators)
            {
                newCSV = bhd.setCSV ((TestInput)this, newCSV);
                oldAndNewIdentical = HELPER_CSV.compare (_CSV, newCSV);
            }

            BusinessObjectParser.assertFieldCondition (newCSV != null, this, FIELD_CSV, "mandatory");
            

            if (FIELD_CSV_Validators.length > 0)
            {
                Object newCSVObj = HELPER_CSV.toObject (newCSV);

                if (newCSVObj != null)
                {
                    int     loopMax = FIELD_CSV_Validators.length;
                    Map     metadata = (Map)ATTRIBUTES_METADATA_TestInput.get (FIELD_CSV);

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

        if (!oldAndNewIdentical)
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (FIELD_CSV_Decorators, (TestInput)this, FIELD_CSV ,getWriteability_CSV ()) != FieldWriteability.FALSE, "Field  CSV is not writeable");
            preCSVChange (newCSV);
            markFieldChange (FIELD_CSV);
            _CSV = newCSV;            
            postFieldChange (FIELD_CSV);
            postCSVChange ();
        }
    }



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

        return result;
    }
    
    
    public BaseBusinessClass getSingleAssocReferenceInstance (String assocName)
    {
        if (assocName == null)
        {
            throw new RuntimeException ("Game over == null!");
        }
        else if (assocName.equals (SINGLEREFERENCE_Level))
        {
            return _Level.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_Level))
        {
            return null ;
        }
        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_Level))
        {
            return getLevel ();
        }
        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_Level))
        {
            return getLevel (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_Level))
        {
            return getLevelID ();
        }
        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_Level))
        {
            setLevel ((Level)(newValue));
        }
        else
        {
            super.setSingleAssoc (assocName, newValue);
        }
    }



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


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


    /**
     * Get the object id for the referenced object.  Does not force a DB access.
     */
    public Long getLevelID ()
    {
        assertValid();
        
        if (_Level == null)
        {
            return null;
        }
        else
        {
            return _Level.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 preLevelChange (Level newLevel) 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 postLevelChange () throws FieldException
    {
    }


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

        
    /**
     * Set the reference Level.  Checks to ensure a new value
     * has been supplied.  If so, marks the reference as altered and sets it.
     */
    public void setLevel (Level newLevel) throws StorageException, FieldException
    {
        BusinessObjectParser.assertFieldCondition (newLevel != null, this, SINGLEREFERENCE_Level, "mandatory");

        if (_Level.wouldReferencedChange (newLevel))
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (SINGLEREFERENCE_Level_Decorators, (TestInput)this, SINGLEREFERENCE_Level ,getWriteability_Level ()) != FieldWriteability.FALSE, "Assoc Level is not writeable");
            preLevelChange (newLevel);
            
            _Level.set (newLevel);
                
            postLevelChange ();
        }
    }

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

        return result;
    }


    /**
     * Get the reference instance for the multi assoc name.
     */
    public BaseBusinessClass getMultiAssocReferenceInstance(String attribName)
    {
        if (MULTIPLEREFERENCE_Candidates.equals(attribName))
        {
            return Candidate.REFERENCE_Candidate ;
        }

        return super.getMultiAssocReferenceInstance(attribName);
    }


    public String getMultiAssocBackReference(String attribName)
    {
        if (MULTIPLEREFERENCE_Candidates.equals(attribName))
        {
            return Candidate.SINGLEREFERENCE_TestInput ;
        }

        return super.getMultiAssocBackReference(attribName);
    }


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

        return super.getMultiAssocCount(attribName);
    }


    /**
     * Get the assoc at a particular index
     */
    public BaseBusinessClass getMultiAssocAt(String attribName, int index) throws StorageException
    {
        if (MULTIPLEREFERENCE_Candidates.equals(attribName))
        {
            return this.getCandidatesAt(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_Candidates.equals(attribName))
        {
            addToCandidates((Candidate)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_Candidates.equals(attribName))
        {
            removeFromCandidates((Candidate)oldElement);
            return;
        }

        super.removeFromMultiAssoc(attribName, oldElement);
    }


    protected void __loadMultiAssoc (String attribName, BaseBusinessClass[] elements)
    {
        if (MULTIPLEREFERENCE_Candidates.equals(attribName))
        {
            _Candidates.__loadAssociation (elements);
            return;
        }

        super.__loadMultiAssoc(attribName, elements);
    }


    protected boolean __isMultiAssocLoaded (String attribName)
    {
        if (MULTIPLEREFERENCE_Candidates.equals(attribName))
        {
            return _Candidates.isLoaded ();
        }

        return super.__isMultiAssocLoaded(attribName);
    }


    public FieldWriteability getWriteability_Candidates ()
    {
        return getFieldWritabilityUtil (FieldWriteability.TRUE);
    }
    
    
    public int getCandidatesCount () throws StorageException
    {
        assertValid();
        return _Candidates.getReferencedObjectsCount ();
    }


    public void addToCandidates (Candidate newElement) throws StorageException
    {
        if (_Candidates.wouldAddChange (newElement))
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (MULTIPLEREFERENCE_Candidates_Decorators, (TestInput)this, MULTIPLEREFERENCE_Candidates ,getWriteability_Candidates ()) != FieldWriteability.FALSE, "MultiAssoc Candidates is not writeable (add)");
            _Candidates.appendElement (newElement);

            try
            {
                if (newElement.getTestInput () != this)
                {
                    newElement.setTestInput ((TestInput)(this));
                }
            }
            catch (Exception e)
            {
                throw NestedException.wrap(e);
            }
        }
    }


    public void removeFromCandidates (Candidate elementToRemove) throws StorageException
    {
        if (_Candidates.wouldRemoveChange (elementToRemove))
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (MULTIPLEREFERENCE_Candidates_Decorators, (TestInput)this, MULTIPLEREFERENCE_Candidates ,getWriteability_Candidates ()) != FieldWriteability.FALSE, "MultiAssoc Candidates is not writeable (remove)");
            _Candidates.removeElement (elementToRemove);
            try
            {
                if (elementToRemove.getTestInput () != null)
                {
                    elementToRemove.setTestInput (null);
                }
            }
            catch (Exception e)
            {
                throw NestedException.wrap(e);
            }
        }
    }


    public Candidate getCandidatesAt (int index) throws StorageException
    {
        return (Candidate)(_Candidates.getElementAt (index));
    }


    public SortedSet<Candidate> getCandidatesSet () throws StorageException
    {
        return _Candidates.getSet ();
    }



    public void onDelete ()
    {
        try 
        {
            for(Candidate referenced : CollectionUtils.reverse(getCandidatesSet()))
            { 
                LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG1, "Cascading delete for Candidates from ", getObjectID (), " to ", referenced.getObjectID ());
                referenced.delete ();
            }

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

        super.onDelete ();
    }


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


    public TestInput referenceInstance ()
    {
        return REFERENCE_TestInput;
    }


    public TestInput getInTransaction (ObjectTransaction t) throws StorageException
    {
        return getTestInputByID (t, getObjectID());
    }
    
    
    public BaseBusinessClass dummyInstance ()
    {
        return DUMMY_TestInput;
    }


    public String getBaseSetName ()
    {
        return "";
    }



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

        PSet.setAttrib (FIELD_ObjectID, myID);
        PSet.setAttrib (FIELD_CSV, HELPER_CSV.toObject (_CSV)); //
        _Level.getPersistentSets (allSets);
        
    }


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

        _CSV = (BinaryContent)(HELPER_CSV.fromObject (_CSV, PSet.getAttrib (FIELD_CSV))); //
        _Level.setFromPersistentSets (objectID, allSets);
        
    }


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

        if (other instanceof TestInput)
        {
            TestInput otherTestInput = (TestInput)other;
            

            try
            {
                setCSV (otherTestInput.getCSV ());
            }
            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 BaseTestInput)
        {
            BaseTestInput sourceTestInput = (BaseTestInput)(source);

            _CSV = sourceTestInput._CSV;
            
        }
    }


    /**
     * 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 BaseTestInput)
        {
            BaseTestInput sourceTestInput = (BaseTestInput)(source);

            _Level.copyFrom (sourceTestInput._Level, 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 BaseTestInput)
        {
            BaseTestInput sourceTestInput = (BaseTestInput)(source);

            _Candidates.copyFrom (sourceTestInput._Candidates, linkToGhosts);
            
        }
    }


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

        
        context.check (getLevelID() != null, this, SINGLEREFERENCE_Level, "mandatory");
        
    }


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

        _CSV = (BinaryContent)(HELPER_CSV.readExternal (_CSV, vals.get(FIELD_CSV))); //
        _Level.readExternalData(vals.get(SINGLEREFERENCE_Level));
        _Candidates.readExternalData(vals.get(MULTIPLEREFERENCE_Candidates));
        
    }


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

        vals.put (FIELD_CSV, HELPER_CSV.writeExternal (_CSV));
        vals.put (SINGLEREFERENCE_Level, _Level.writeExternalData());
        vals.put (MULTIPLEREFERENCE_Candidates, _Candidates.writeExternalData());
        
    }


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

        if (other instanceof BaseTestInput)
        {
            BaseTestInput otherTestInput = (BaseTestInput)(other);

            
            if (!HELPER_CSV.compare(this._CSV, otherTestInput._CSV))
            {
                listener.notifyFieldChange(this, other, FIELD_CSV, HELPER_CSV.toObject(this._CSV), HELPER_CSV.toObject(otherTestInput._CSV));
            }

            // Compare single assocs
            _Level.compare (otherTestInput._Level, listener);
            

            // Compare multiple assocs
            _Candidates.compare (otherTestInput._Candidates, 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_CSV, HELPER_CSV.toObject(getCSV()));
        visitor.visitAssociation (_Level);
        visitor.visitAssociation (_Candidates);
        
    }


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

        if (scope.includes (_Level))
        {
            visitor.visit (_Level);
        }
        if (scope.includes (_Candidates))
        {
            visitor.visit (_Candidates);
        }
        
    }


    public static TestInput createTestInput (ObjectTransaction transaction) throws StorageException
    {
        TestInput     result = new TestInput ();

        result.initialiseNewObject (transaction);

        return result;
    }


    public static TestInput getTestInputByID (ObjectTransaction transaction, Long objectID) throws StorageException
    {
        return (TestInput)(transaction.getObjectByID (REFERENCE_TestInput, objectID));
    }

    public boolean testFilter (String attribName, QueryFilter filter) throws StorageException
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_CSV))
        {
            return filter.matches (getCSV ());
        }
        else if (attribName.equals (SINGLEREFERENCE_Level))
        {
            return filter.matches (getLevel ());
        }
        else
        {
            return super.testFilter (attribName, filter);
        }
    }




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


    public AttributeHelper getAttributeHelper (String attribName)
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_CSV))
        {
            return HELPER_CSV;
        }
        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_CSV))
        {
            setCSV ((BinaryContent)(HELPER_CSV.fromObject (_CSV, attribValue)));            
        }
        else
        {
            super.setAttribute (attribName, attribValue);
        }
    }

    

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

    public boolean isReadable ()
    {
        return super.isReadable();
    }

    public boolean isReadable (String fieldName)
    {
        return super.isReadable(fieldName);
    }


    public FieldWriteability getWriteable (String fieldName)
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (fieldName.equals (FIELD_CSV))
        {
            return getWriteability_CSV ();
        }
        else if (fieldName.equals (MULTIPLEREFERENCE_Candidates))
        {
            return getWriteability_Candidates ();
        }
        else if (fieldName.equals (SINGLEREFERENCE_Level))
        {
            return getWriteability_Level ();
        }
        else
        {
            return super.getWriteable (fieldName);
        }
    }


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

        super.putUnwriteable (fields);
    }

    // This generally means there's no specific persistence manager and we don't read or write from a table
    public boolean hasNoTable()
    {
        return true;
    }


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

        
        result.add(HELPER_CSV.getAttribObject (getClass (), _CSV, true, FIELD_CSV));

        return result;
    }


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


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

    public void copyAllAttributeMetadata (Map copyInto)
    {
        super.copyAllAttributeMetadata(copyInto);

        copyInto.putAll(ATTRIBUTES_METADATA_TestInput);
    }
            

    public void preCommit (boolean willBeStored) throws Exception
    {
        super.preCommit(willBeStored);
        
        if(willBeStored)
        {
        
          {  
            oneit.servlets.objstore.binary.BinaryContentHandler bchandler = oneit.servlets.objstore.binary.BinaryContentServlet.getHandler("loggedin");
              
            if(bchandler != null)
            {
                bchandler.preCommit(willBeStored, this, "CSV");
            }
            else
            {
                LogMgr.log(BUSINESS_OBJECTS, LogLevel.SYSTEMWARNING, "Unknown BinaryContentHandler loggedin on attribute CSV");
            }
          }
          
        }
    }

    public oneit.servlets.objstore.binary.BinaryContentHandler getBinaryContentHandler(String attribName)
    {
        if(CollectionUtils.equals(attribName, "CSV"))      
        {  
            return oneit.servlets.objstore.binary.BinaryContentServlet.getHandler("loggedin");
        }     
          
        
        return super.getBinaryContentHandler(attribName);
    }

    public static class TestInputBehaviourDecorator extends BaseBusinessClass.BBCBehaviourDecorator<TestInput>
    {

    /**
     * Get the attribute CSV
     */
    public BinaryContent getCSV (TestInput obj, BinaryContent original)
    {
        return original;
    }

    /**
     * Change the value set for attribute CSV.
     * May modify the field beforehand
     * Occurs before validation.
     */
    public BinaryContent setCSV (TestInput obj, BinaryContent newCSV) throws FieldException
    {
        return newCSV;
    }

    }

    @Override
    public ORMPipeLine pipes()
    {
        return new TestInputPipeLineFactory<TestInput, TestInput> ((TestInput)this);
    }

    @Override
    public ORMPipeLine pipes(Collection _items)
    {
        return pipesTestInput(_items);
    }
      
    /**
     * Use this instead of pipes() to get rid of type casting.
     */  
    public TestInputPipeLineFactory<TestInput, TestInput> pipelineTestInput()
    {
        return (TestInputPipeLineFactory<TestInput, TestInput>) pipes();
    }
    
    public static TestInputPipeLineFactory<TestInput, TestInput> pipesTestInput(Collection<TestInput> items)
    {
        return REFERENCE_TestInput.new TestInputPipeLineFactory<TestInput, TestInput> (items);
    }
    
    public static TestInputPipeLineFactory<TestInput, TestInput> pipesTestInput(TestInput[] _items)
    {
        return pipesTestInput(Arrays.asList (_items));
    }
    
    public static TestInputPipeLineFactory<TestInput, TestInput> pipesTestInput()
    {
        return pipesTestInput((Collection)null);
    }
    
    
    public class TestInputPipeLineFactory<From extends BaseBusinessClass, Me extends TestInput> extends NonPersistentBOPipeLineFactory<From, Me>    
    {
        public <Prev> TestInputPipeLineFactory (PipeLine<From, Prev> pipeLine, Pipe<Prev, Me> nextPipe)
        {
            super (pipeLine, nextPipe);
        }
        
        public TestInputPipeLineFactory (From seed)
        {
            super(seed);
        }

        public TestInputPipeLineFactory (Collection<From> seed)
        {
            super(seed);
        }
        
        
        public PipeLine<From, ? extends Object> to(String name)
        {
            if (name.equals ("Candidates"))
            {
                return toCandidates ();
            }                
            if (name.equals ("CSV"))
            {
                return toCSV ();
            }                
            if (name.equals ("Level"))
            {
                return toLevel ();
            }                
            
            
            return super.to(name);
        }
        
        
        public PipeLine<From, BinaryContent> toCSV () { return pipe(new ORMAttributePipe<Me, BinaryContent>(FIELD_CSV));  }

        public Level.LevelPipeLineFactory<From, Level> toLevel () { return toLevel (Filter.ALL); }

        public Level.LevelPipeLineFactory<From, Level> toLevel (Filter<Level> filter) 
        { 
            return Level.REFERENCE_Level.new LevelPipeLineFactory<From, Level> (this, new ORMSingleAssocPipe<Me, Level>(SINGLEREFERENCE_Level, filter)); 
        }

        public Candidate.CandidatePipeLineFactory<From, Candidate> toCandidates () { return toCandidates(Filter.ALL); }        

        public Candidate.CandidatePipeLineFactory<From, Candidate> toCandidates (Filter<Candidate> filter)
        {
            return Candidate.REFERENCE_Candidate.new CandidatePipeLineFactory<From, Candidate> (this, new ORMMultiAssocPipe<Me, Candidate>(MULTIPLEREFERENCE_Candidates, filter)); 
        }
    }
    
    public boolean isTransientAttrib(String attribName)
    {
        

        return super.isTransientAttrib(attribName);
    }

    public boolean isTransientSingleReference(String assocName)
    {
        

        return super.isTransientSingleReference(assocName);
    }
}

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

    public void assertValid ()
    {
    }


    public Level getLevel () throws StorageException
    {
        return (Level)(Level.DUMMY_Level);
    }


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

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


    public Candidate getCandidatesAt (int index) throws StorageException
    {
        throw new RuntimeException ("No elements in a dummy object in association Candidates");
    }


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

}

