/*
 * 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 BaseAttachment extends BaseBusinessClass
{
    // Reference instance for the object
    public static final Attachment REFERENCE_Attachment = new Attachment ();

    // Reference instance for the object
    public static final Attachment DUMMY_Attachment = new DummyAttachment ();

    // Static constants corresponding to field names
    
    public static final String FIELD_AttachmentName = "AttachmentName";
    public static final String FIELD_AttachmentFile = "AttachmentFile";
    public static final String SINGLEREFERENCE_EmailMessage = "EmailMessage";
    public static final String BACKREF_EmailMessage = "";

    // Static constants corresponding to searches
    

    // Static constants corresponding to attribute helpers
    private static final DefaultAttributeHelper<Attachment> HELPER_AttachmentName = DefaultAttributeHelper.INSTANCE;
    private static final BLOBAttributeHelper HELPER_AttachmentFile = BLOBAttributeHelper.INSTANCE;
    

    // Private attributes corresponding to business object data
    private String _AttachmentName;
    private BinaryContent _AttachmentFile;
    

    // Private attributes corresponding to single references
    private SingleAssociation<Attachment, EmailMessage> _EmailMessage;
    

    // Private attributes corresponding to multiple references
    

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

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

    // Arrays of behaviour decorators
    private static final AttachmentBehaviourDecorator[] Attachment_BehaviourDecorators;
    
    static
    {
        try
        {
            
            String tmp_EmailMessage = EmailMessage.BACKREF_Attachments;
            
            Map  validatorMapping = ((Map)ConfigMgr.getConfigObject ("CONFIG.ORMVALIDATOR", "ValidatorMapping"));

            setupAssocMetaData_EmailMessage();
            FIELD_AttachmentName_Validators = (AttributeValidator[])setupAttribMetaData_AttachmentName(validatorMapping).toArray (new AttributeValidator[0]);
            FIELD_AttachmentFile_Validators = (AttributeValidator[])setupAttribMetaData_AttachmentFile(validatorMapping).toArray (new AttributeValidator[0]);
            

            REFERENCE_Attachment.initialiseReference ();
            DUMMY_Attachment.initialiseReference ();
            Attachment_BehaviourDecorators = BaseBusinessClass.getBBCBehaviours(Attachment.class).toArray(new AttachmentBehaviourDecorator[0]);
        }
        catch (RuntimeException e)
        {
            LogMgr.log (BUSINESS_OBJECTS, LogLevel.SYSTEMERROR1, e, "Error initialising");
            throw e;
        }
    }

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

        metaInfo.put ("backreferenceName", "Attachments");
        metaInfo.put ("dbcol", "email_message_id");
        metaInfo.put ("name", "EmailMessage");
        metaInfo.put ("type", "EmailMessage");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Attachment.EmailMessage:", metaInfo);
        ATTRIBUTES_METADATA_Attachment.put (SINGLEREFERENCE_EmailMessage, Collections.unmodifiableMap (metaInfo));
    }
    
    
    // Meta Info setup
    private static List setupAttribMetaData_AttachmentName(Map validatorMapping)
    {
        Map  metaInfo   = new HashMap ();

        metaInfo.put ("dbcol", "attachment_name");
        metaInfo.put ("length", "100");
        metaInfo.put ("name", "AttachmentName");
        metaInfo.put ("type", "String");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Attachment.AttachmentName:", metaInfo);
        ATTRIBUTES_METADATA_Attachment.put (FIELD_AttachmentName, Collections.unmodifiableMap (metaInfo));

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

        return validators;
    }
    
    // Meta Info setup
    private static List setupAttribMetaData_AttachmentFile(Map validatorMapping)
    {
        Map  metaInfo   = new HashMap ();

        metaInfo.put ("attribHelper", "BLOBAttributeHelper");
        metaInfo.put ("attribHelperInstance", "BLOBAttributeHelper.INSTANCE");
        metaInfo.put ("binaryHandler", "loggedin");
        metaInfo.put ("dbcol", "attachment_file");
        metaInfo.put ("name", "AttachmentFile");
        metaInfo.put ("type", "BinaryContent");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Attachment.AttachmentFile:", metaInfo);
        ATTRIBUTES_METADATA_Attachment.put (FIELD_AttachmentFile, Collections.unmodifiableMap (metaInfo));

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

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


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


    


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

        
        _AttachmentName = (String)(HELPER_AttachmentName.initialise (_AttachmentName));
        _AttachmentFile = (BinaryContent)(HELPER_AttachmentFile.initialise (_AttachmentFile));
    }


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

        _EmailMessage = new SingleAssociation<Attachment, EmailMessage> (this, SINGLEREFERENCE_EmailMessage, EmailMessage.MULTIPLEREFERENCE_Attachments, EmailMessage.REFERENCE_EmailMessage, "tl_attachment");
        
    }


    // Initialise the associations
    protected BaseBusinessClass initialiseReference ()
    {
        super.initialiseReference ();
        
        _EmailMessage = new SingleAssociation<Attachment, EmailMessage> (this, SINGLEREFERENCE_EmailMessage, EmailMessage.MULTIPLEREFERENCE_Attachments, EmailMessage.REFERENCE_EmailMessage, "tl_attachment");
        
        
        return this;
    }

    

    /**
     * Get the attribute AttachmentName
     */
    public String getAttachmentName ()
    {
        assertValid();
        String valToReturn = _AttachmentName;

            for (AttachmentBehaviourDecorator bhd : Attachment_BehaviourDecorators)
            {
                valToReturn = bhd.getAttachmentName ((Attachment)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 preAttachmentNameChange (String newAttachmentName) 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 postAttachmentNameChange () throws FieldException
    {
    }

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

    /**
     * Set the attribute AttachmentName.  Checks to ensure a new value
     * has been supplied.  If so, marks the field as altered and sets the attribute.
     */
    public void setAttachmentName (String newAttachmentName) throws FieldException
    {
        boolean oldAndNewIdentical = HELPER_AttachmentName.compare (_AttachmentName, newAttachmentName);
        
        try
        {
            for (AttachmentBehaviourDecorator bhd : Attachment_BehaviourDecorators)
            {
                newAttachmentName = bhd.setAttachmentName ((Attachment)this, newAttachmentName);
                oldAndNewIdentical = HELPER_AttachmentName.compare (_AttachmentName, newAttachmentName);
            }

            

            if (FIELD_AttachmentName_Validators.length > 0)
            {
                Object newAttachmentNameObj = HELPER_AttachmentName.toObject (newAttachmentName);

                if (newAttachmentNameObj != null)
                {
                    int     loopMax = FIELD_AttachmentName_Validators.length;
                    Map     metadata = (Map)ATTRIBUTES_METADATA_Attachment.get (FIELD_AttachmentName);

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

        if (!oldAndNewIdentical)
        {
            assertValid();
            Debug.assertion (getWriteability_AttachmentName () != FieldWriteability.FALSE, "Field  AttachmentName is not writeable");
            preAttachmentNameChange (newAttachmentName);
            markFieldChange (FIELD_AttachmentName);
            _AttachmentName = newAttachmentName;            
            postFieldChange (FIELD_AttachmentName);
            postAttachmentNameChange ();
        }
    }

    /**
     * Get the attribute AttachmentFile
     */
    public BinaryContent getAttachmentFile ()
    {
        assertValid();
        BinaryContent valToReturn = _AttachmentFile;

            for (AttachmentBehaviourDecorator bhd : Attachment_BehaviourDecorators)
            {
                valToReturn = bhd.getAttachmentFile ((Attachment)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 preAttachmentFileChange (BinaryContent newAttachmentFile) 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 postAttachmentFileChange () throws FieldException
    {
    }

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

    /**
     * Set the attribute AttachmentFile.  Checks to ensure a new value
     * has been supplied.  If so, marks the field as altered and sets the attribute.
     */
    public void setAttachmentFile (BinaryContent newAttachmentFile) throws FieldException
    {
        boolean oldAndNewIdentical = HELPER_AttachmentFile.compare (_AttachmentFile, newAttachmentFile);
        
        try
        {
            for (AttachmentBehaviourDecorator bhd : Attachment_BehaviourDecorators)
            {
                newAttachmentFile = bhd.setAttachmentFile ((Attachment)this, newAttachmentFile);
                oldAndNewIdentical = HELPER_AttachmentFile.compare (_AttachmentFile, newAttachmentFile);
            }

            

            if (FIELD_AttachmentFile_Validators.length > 0)
            {
                Object newAttachmentFileObj = HELPER_AttachmentFile.toObject (newAttachmentFile);

                if (newAttachmentFileObj != null)
                {
                    int     loopMax = FIELD_AttachmentFile_Validators.length;
                    Map     metadata = (Map)ATTRIBUTES_METADATA_Attachment.get (FIELD_AttachmentFile);

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

        if (!oldAndNewIdentical)
        {
            assertValid();
            Debug.assertion (getWriteability_AttachmentFile () != FieldWriteability.FALSE, "Field  AttachmentFile is not writeable");
            preAttachmentFileChange (newAttachmentFile);
            markFieldChange (FIELD_AttachmentFile);
            _AttachmentFile = newAttachmentFile;            
            postFieldChange (FIELD_AttachmentFile);
            postAttachmentFileChange ();
        }
    }



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

        
        result.add("EmailMessage");
        

        return result;
    }
    
    
    public BaseBusinessClass getSingleAssocReferenceInstance (String assocName)
    {
        if (assocName == null)
        {
            throw new RuntimeException ("Game over == null!");
        }
        else if (assocName.equals (SINGLEREFERENCE_EmailMessage))
        {
            return _EmailMessage.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_EmailMessage))
        {
            return EmailMessage.MULTIPLEREFERENCE_Attachments ;
        }
        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_EmailMessage))
        {
            return getEmailMessage ();
        }
        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_EmailMessage))
        {
            return getEmailMessage (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_EmailMessage))
        {
            return getEmailMessageID ();
        }
        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_EmailMessage))
        {
            setEmailMessage ((EmailMessage)(newValue));
        }
        else
        {
            super.setSingleAssoc (assocName, newValue);
        }
    }



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


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


    /**
     * Get the object id for the referenced object.  Does not force a DB access.
     */
    public Long getEmailMessageID ()
    {
        assertValid();
        
        if (_EmailMessage == null)
        {
            return null;
        }
        else
        {
            return _EmailMessage.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 preEmailMessageChange (EmailMessage newEmailMessage) 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 postEmailMessageChange () throws FieldException
    {
    }



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

        if (_EmailMessage.wouldReferencedChange (newEmailMessage))
        {
            assertValid();
            Debug.assertion (getWriteability_EmailMessage () != FieldWriteability.FALSE, "Assoc EmailMessage is not writeable");
            preEmailMessageChange (newEmailMessage);
            EmailMessage oldEmailMessage = getEmailMessage ();

                    if (oldEmailMessage != null)
                    {
                        // This is to stop validation from triggering when we are removed
                        _EmailMessage.set (null);
                        oldEmailMessage.removeFromAttachments ((Attachment)(this));
                    }

                    _EmailMessage.set (newEmailMessage);

                    if (newEmailMessage != null)
                    {
                        newEmailMessage.addToAttachments ((Attachment)(this));
                    }
                
            postEmailMessageChange ();
        }
    }

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

        

        return result;
    }


    /**
     * Get the reference instance for the multi assoc name.
     */
    public BaseBusinessClass getMultiAssocReferenceInstance(String attribName)
    {
        

        return super.getMultiAssocReferenceInstance(attribName);
    }


    public String getMultiAssocBackReference(String attribName)
    {
        

        return super.getMultiAssocBackReference(attribName);
    }


    /**
     * Get the assoc count for the multi assoc name.
     */
    public int getMultiAssocCount(String attribName) throws StorageException
    {
        

        return super.getMultiAssocCount(attribName);
    }


    /**
     * Get the assoc at a particular index
     */
    public BaseBusinessClass getMultiAssocAt(String attribName, int index) throws StorageException
    {
        

        return super.getMultiAssocAt(attribName, index);
    }


    /**
     * Add to a multi assoc by attribute name
     */
    public void addToMultiAssoc(String attribName, BaseBusinessClass newElement) throws StorageException
    {
        

        super.addToMultiAssoc(attribName, newElement);
    }

    /**
     * Remove from a multi assoc by attribute name
     */
    public void removeFromMultiAssoc(String attribName, BaseBusinessClass oldElement) throws StorageException
    {
        

        super.removeFromMultiAssoc(attribName, oldElement);
    }


    protected void __loadMultiAssoc (String attribName, BaseBusinessClass[] elements)
    {
        

        super.__loadMultiAssoc(attribName, elements);
    }


    protected boolean __isMultiAssocLoaded (String attribName)
    {
        

        return super.__isMultiAssocLoaded(attribName);
    }

    



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

                if (referenced != null)
                {
                    // Stop the callback
                    LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG1, "Setting backreference to null Attachments from ", getObjectID (), " to ", referenced.getObjectID ());
                    _EmailMessage.set (null);
                    referenced.removeFromAttachments ((Attachment)this);
                }
            }
        
        }
        catch (Exception e)
        {
            throw NestedException.wrap(e);
        }

        super.onDelete ();
    }


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


    public Attachment referenceInstance ()
    {
        return REFERENCE_Attachment;
    }


    public Attachment getInTransaction (ObjectTransaction t) throws StorageException
    {
        return getAttachmentByID (t, getObjectID());
    }
    
    
    public BaseBusinessClass dummyInstance ()
    {
        return DUMMY_Attachment;
    }


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





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

        tl_attachmentPSet.setAttrib (FIELD_ObjectID, myID);
        tl_attachmentPSet.setAttrib (FIELD_AttachmentName, HELPER_AttachmentName.toObject (_AttachmentName)); //
        tl_attachmentPSet.setAttrib (FIELD_AttachmentFile, HELPER_AttachmentFile.toObject (_AttachmentFile)); //
        _EmailMessage.getPersistentSets (allSets);
        
    }


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

        
        PersistentSet   tl_attachmentPSet = allSets.getPersistentSet (objectID, "tl_attachment");

        _AttachmentName = (String)(HELPER_AttachmentName.fromObject (_AttachmentName, tl_attachmentPSet.getAttrib (FIELD_AttachmentName))); //
        _AttachmentFile = (BinaryContent)(HELPER_AttachmentFile.fromObject (_AttachmentFile, tl_attachmentPSet.getAttrib (FIELD_AttachmentFile))); //
        _EmailMessage.setFromPersistentSets (objectID, allSets);
        
    }





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

        if (other instanceof Attachment)
        {
            Attachment otherAttachment = (Attachment)other;
            
            try
            {
                setAttachmentName (otherAttachment.getAttachmentName ());
            }
            catch (FieldException ex)
            {
                e.addException (ex);
            }
            
            try
            {
                setAttachmentFile (otherAttachment.getAttachmentFile ());
            }
            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 BaseAttachment)
        {
            BaseAttachment sourceAttachment = (BaseAttachment)(source);

            _AttachmentName = sourceAttachment._AttachmentName;
            _AttachmentFile = sourceAttachment._AttachmentFile;
            
        }
    }


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

            _EmailMessage.copyFrom (sourceAttachment._EmailMessage, 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 BaseAttachment)
        {
            BaseAttachment sourceAttachment = (BaseAttachment)(source);

            
        }
    }


    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);

        _AttachmentName = (String)(HELPER_AttachmentName.readExternal (_AttachmentName, vals.get(FIELD_AttachmentName))); //
        _AttachmentFile = (BinaryContent)(HELPER_AttachmentFile.readExternal (_AttachmentFile, vals.get(FIELD_AttachmentFile))); //
        _EmailMessage.readExternalData(vals.get(SINGLEREFERENCE_EmailMessage));
        
    }


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

        vals.put (FIELD_AttachmentName, HELPER_AttachmentName.writeExternal (_AttachmentName));
        vals.put (FIELD_AttachmentFile, HELPER_AttachmentFile.writeExternal (_AttachmentFile));
        vals.put (SINGLEREFERENCE_EmailMessage, _EmailMessage.writeExternalData());
        
    }


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

        if (other instanceof BaseAttachment)
        {
            BaseAttachment otherAttachment = (BaseAttachment)(other);

            
            if (!HELPER_AttachmentName.compare(this._AttachmentName, otherAttachment._AttachmentName))
            {
                listener.notifyFieldChange(this, other, FIELD_AttachmentName, HELPER_AttachmentName.toObject(this._AttachmentName), HELPER_AttachmentName.toObject(otherAttachment._AttachmentName));
            }
            if (!HELPER_AttachmentFile.compare(this._AttachmentFile, otherAttachment._AttachmentFile))
            {
                listener.notifyFieldChange(this, other, FIELD_AttachmentFile, HELPER_AttachmentFile.toObject(this._AttachmentFile), HELPER_AttachmentFile.toObject(otherAttachment._AttachmentFile));
            }

            // Compare single assocs
            _EmailMessage.compare (otherAttachment._EmailMessage, listener);
            

            // Compare multiple assocs
            
        }
    }


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

        
    }


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

        visitor.visitField(this, FIELD_AttachmentName, HELPER_AttachmentName.toObject(getAttachmentName()));
        visitor.visitField(this, FIELD_AttachmentFile, HELPER_AttachmentFile.toObject(getAttachmentFile()));
        visitor.visitAssociation (_EmailMessage);
        
    }


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

        if (scope.includes (_EmailMessage))
        {
            visitor.visit (_EmailMessage);
        }
        
    }


    public static Attachment createAttachment (ObjectTransaction transaction) throws StorageException
    {
        Attachment     result = new Attachment ();

        result.initialiseNewObject (transaction);

        return result;
    }


    public static Attachment getAttachmentByID (ObjectTransaction transaction, Long objectID) throws StorageException
    {
        return (Attachment)(transaction.getObjectByID (REFERENCE_Attachment, objectID));
    }

    public boolean testFilter (String attribName, QueryFilter filter) throws StorageException
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_AttachmentName))
        {
            return filter.matches (getAttachmentName ());
        }
        else if (attribName.equals (FIELD_AttachmentFile))
        {
            return filter.matches (getAttachmentFile ());
        }
        else if (attribName.equals (SINGLEREFERENCE_EmailMessage))
        {
            return filter.matches (getEmailMessage ());
        }
        else
        {
            return super.testFilter (attribName, filter);
        }
    }




    public Object getAttribute (String attribName)
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_AttachmentName))
        {
            return HELPER_AttachmentName.toObject (getAttachmentName ());
        }
        else if (attribName.equals (FIELD_AttachmentFile))
        {
            return HELPER_AttachmentFile.toObject (getAttachmentFile ());
        }
        else
        {
            return super.getAttribute (attribName);
        }
    }


    public AttributeHelper getAttributeHelper (String attribName)
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_AttachmentName))
        {
            return HELPER_AttachmentName;
        }
        else if (attribName.equals (FIELD_AttachmentFile))
        {
            return HELPER_AttachmentFile;
        }
        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_AttachmentName))
        {
            setAttachmentName ((String)(HELPER_AttachmentName.fromObject (_AttachmentName, attribValue)));            
        }
        else if (attribName.equals (FIELD_AttachmentFile))
        {
            setAttachmentFile ((BinaryContent)(HELPER_AttachmentFile.fromObject (_AttachmentFile, 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_AttachmentName))
        {
            return getWriteability_AttachmentName ();
        }
        else if (fieldName.equals (FIELD_AttachmentFile))
        {
            return getWriteability_AttachmentFile ();
        }
        else if (fieldName.equals (SINGLEREFERENCE_EmailMessage))
        {
            return getWriteability_EmailMessage ();
        }
        else
        {
            return super.getWriteable (fieldName);
        }
    }


    public void putUnwriteable (Set<String> fields)
    {
        
            if (getWriteability_AttachmentName () != FieldWriteability.TRUE)
            {
                fields.add (FIELD_AttachmentName);
            }
        
            if (getWriteability_AttachmentFile () != FieldWriteability.TRUE)
            {
                fields.add (FIELD_AttachmentFile);
            }
        

        super.putUnwriteable (fields);
    }

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

        
        result.add(HELPER_AttachmentName.getAttribObject (getClass (), _AttachmentName, false, FIELD_AttachmentName));
        result.add(HELPER_AttachmentFile.getAttribObject (getClass (), _AttachmentFile, false, FIELD_AttachmentFile));

        return result;
    }


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


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

    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, "AttachmentFile");
            }
            else
            {
                LogMgr.log(BUSINESS_OBJECTS, LogLevel.SYSTEMWARNING, "Unknown BinaryContentHandler loggedin on attribute AttachmentFile");
            }
          }
          
        }
    }

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

    public static class AttachmentBehaviourDecorator extends BaseBusinessClass.BBCBehaviourDecorator<Attachment>
    {

    /**
     * Get the attribute AttachmentName
     */
    public String getAttachmentName (Attachment obj, String original)
    {
        return original;
    }

    /**
     * Change the value set for attribute AttachmentName.
     * May modify the field beforehand
     * Occurs before validation.
     */
    public String setAttachmentName (Attachment obj, String newAttachmentName) throws FieldException
    {
        return newAttachmentName;
    }

    /**
     * Get the attribute AttachmentFile
     */
    public BinaryContent getAttachmentFile (Attachment obj, BinaryContent original)
    {
        return original;
    }

    /**
     * Change the value set for attribute AttachmentFile.
     * May modify the field beforehand
     * Occurs before validation.
     */
    public BinaryContent setAttachmentFile (Attachment obj, BinaryContent newAttachmentFile) throws FieldException
    {
        return newAttachmentFile;
    }

    }

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

        public AttachmentPipeLineFactory (Collection<From> seed)
        {
            super(seed);
        }
        
        
        public PipeLine<From, ? extends Object> to(String name)
        {
            if (name.equals ("AttachmentName"))
            {
                return toAttachmentName ();
            }                
            if (name.equals ("AttachmentFile"))
            {
                return toAttachmentFile ();
            }                
            if (name.equals ("EmailMessage"))
            {
                return toEmailMessage ();
            }                
            
            
            return super.to(name);
        }
        
        
        public PipeLine<From, String> toAttachmentName () { return pipe(new ORMAttributePipe<Me, String>(FIELD_AttachmentName));  }
        
        public PipeLine<From, BinaryContent> toAttachmentFile () { return pipe(new ORMAttributePipe<Me, BinaryContent>(FIELD_AttachmentFile));  }
        public EmailMessage.EmailMessagePipeLineFactory<From, EmailMessage> toEmailMessage () { return toEmailMessage (Filter.ALL); }

        public EmailMessage.EmailMessagePipeLineFactory<From, EmailMessage> toEmailMessage (Filter<EmailMessage> filter) 
        { 
            return EmailMessage.REFERENCE_EmailMessage.new EmailMessagePipeLineFactory<From, EmailMessage> (this, new ORMSingleAssocPipe<Me, EmailMessage>(SINGLEREFERENCE_EmailMessage, filter)); 
        }
        
    }
    
    public boolean isTransientAttrib(String attribName)
    {
        

        return super.isTransientAttrib(attribName);
    }

    public boolean isTransientSingleReference(String assocName)
    {
        

        return super.isTransientSingleReference(assocName);
    }
}

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

    public void assertValid ()
    {
    }


    public EmailMessage getEmailMessage () throws StorageException
    {
        return (EmailMessage)(EmailMessage.DUMMY_EmailMessage);
    }


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

}


