/*
 * 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 performa.orm.types.*;
import oneit.security.*;


public abstract class BaseMessage extends BaseBusinessClass
{
    // Reference instance for the object
    public static final Message REFERENCE_Message = new Message ();

    // Reference instance for the object
    public static final Message DUMMY_Message = new DummyMessage ();

    // Static constants corresponding to field names
    
    public static final String FIELD_SentVia = "SentVia";
    public static final String FIELD_MessageContent = "MessageContent";
    public static final String FIELD_IsRead = "IsRead";
    public static final String SINGLEREFERENCE_SentBy = "SentBy";
    public static final String SINGLEREFERENCE_WorkFlowMessage = "WorkFlowMessage";
    public static final String SINGLEREFERENCE_JobApplication = "JobApplication";
    public static final String BACKREF_JobApplication = "";
    public static final String MULTIPLEREFERENCE_Attachments = "Attachments";
    public static final String BACKREF_Attachments = "";

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

    // Static constants corresponding to attribute helpers
    private static final EnumeratedAttributeHelper<Message, SentVia> HELPER_SentVia =  new EnumeratedAttributeHelper<Message, SentVia> (SentVia.FACTORY_SentVia);
    private static final DefaultAttributeHelper<Message> HELPER_MessageContent = DefaultAttributeHelper.INSTANCE;
    private static final DefaultAttributeHelper<Message> HELPER_IsRead = DefaultAttributeHelper.INSTANCE;
    

    // Private attributes corresponding to business object data
    private SentVia _SentVia;
    private String _MessageContent;
    private Boolean _IsRead;
    

    // Private attributes corresponding to single references
    private SingleAssociation<Message, SecUser> _SentBy;
    private SingleAssociation<Message, WorkFlowMessage> _WorkFlowMessage;
    private SingleAssociation<Message, JobApplication> _JobApplication;
    

    // Private attributes corresponding to multiple references
    private MultipleAssociation<Message, ChatAttachment> _Attachments;
    

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

    // Arrays of validators for each attribute
    private static final AttributeValidator[] FIELD_SentVia_Validators;
    private static final AttributeValidator[] FIELD_MessageContent_Validators;
    private static final AttributeValidator[] FIELD_IsRead_Validators;
    

    // Arrays of AttributeDecorators for each attribute
    private static final AttributeDecorator<Message, SentVia>[] FIELD_SentVia_Decorators;
    private static final AttributeDecorator<Message, String>[] FIELD_MessageContent_Decorators;
    private static final AttributeDecorator<Message, Boolean>[] FIELD_IsRead_Decorators;
    
    
    // Arrays of SingleAssocDecorators for each attribute
    private static final SingleAssocDecorator<Message, SecUser>[] SINGLEREFERENCE_SentBy_Decorators;
    private static final SingleAssocDecorator<Message, WorkFlowMessage>[] SINGLEREFERENCE_WorkFlowMessage_Decorators;
    private static final SingleAssocDecorator<Message, JobApplication>[] SINGLEREFERENCE_JobApplication_Decorators;
    
    
    // Arrays of MultiAssocDecorators for each attribute
    private static final MultiAssocDecorator<Message, ChatAttachment>[] MULTIPLEREFERENCE_Attachments_Decorators;
    

    // Arrays of behaviour decorators
    private static final MessageBehaviourDecorator[] Message_BehaviourDecorators;
    
    static
    {
        try
        {
            
            String tmp_Attachments = ChatAttachment.BACKREF_Message;
            String tmp_JobApplication = JobApplication.BACKREF_Messages;
            
            Map  validatorMapping = ((Map)ConfigMgr.getConfigObject ("CONFIG.ORMVALIDATOR", "ValidatorMapping"));

            setupAssocMetaData_Attachments();
            setupAssocMetaData_SentBy();
            setupAssocMetaData_WorkFlowMessage();
            setupAssocMetaData_JobApplication();
            FIELD_SentVia_Validators = (AttributeValidator[])setupAttribMetaData_SentVia(validatorMapping).toArray (new AttributeValidator[0]);
            FIELD_MessageContent_Validators = (AttributeValidator[])setupAttribMetaData_MessageContent(validatorMapping).toArray (new AttributeValidator[0]);
            FIELD_IsRead_Validators = (AttributeValidator[])setupAttribMetaData_IsRead(validatorMapping).toArray (new AttributeValidator[0]);
            FIELD_SentVia_Decorators = (AttributeDecorator[])AttributeDecoratorUtils.getAttributeDecorators(REFERENCE_Message, FIELD_SentVia).toArray (new AttributeDecorator[0]);
            FIELD_MessageContent_Decorators = (AttributeDecorator[])AttributeDecoratorUtils.getAttributeDecorators(REFERENCE_Message, FIELD_MessageContent).toArray (new AttributeDecorator[0]);
            FIELD_IsRead_Decorators = (AttributeDecorator[])AttributeDecoratorUtils.getAttributeDecorators(REFERENCE_Message, FIELD_IsRead).toArray (new AttributeDecorator[0]);
            SINGLEREFERENCE_SentBy_Decorators = (SingleAssocDecorator[])AttributeDecoratorUtils.getSingleAssocDecorators(REFERENCE_Message, SINGLEREFERENCE_SentBy).toArray (new SingleAssocDecorator[0]);
            SINGLEREFERENCE_WorkFlowMessage_Decorators = (SingleAssocDecorator[])AttributeDecoratorUtils.getSingleAssocDecorators(REFERENCE_Message, SINGLEREFERENCE_WorkFlowMessage).toArray (new SingleAssocDecorator[0]);
            SINGLEREFERENCE_JobApplication_Decorators = (SingleAssocDecorator[])AttributeDecoratorUtils.getSingleAssocDecorators(REFERENCE_Message, SINGLEREFERENCE_JobApplication).toArray (new SingleAssocDecorator[0]);
            MULTIPLEREFERENCE_Attachments_Decorators = (MultiAssocDecorator[])AttributeDecoratorUtils.getMultiAssocDecorators(REFERENCE_Message, MULTIPLEREFERENCE_Attachments).toArray (new MultiAssocDecorator[0]);
            

            REFERENCE_Message.initialiseReference ();
            DUMMY_Message.initialiseReference ();
            Message_BehaviourDecorators = BaseBusinessClass.getBBCBehaviours(Message.class).toArray(new MessageBehaviourDecorator[0]);
        }
        catch (RuntimeException e)
        {
            LogMgr.log (BUSINESS_OBJECTS, LogLevel.SYSTEMERROR1, e, "Error initialising");
            throw e;
        }
    }

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

        metaInfo.put ("backreferenceName", "Message");
        metaInfo.put ("name", "Attachments");
        metaInfo.put ("type", "ChatAttachment");
        
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Message.Attachments:", metaInfo);
        ATTRIBUTES_METADATA_Message.put (MULTIPLEREFERENCE_Attachments, Collections.unmodifiableMap (metaInfo));
    }
    
    
    private static void setupAssocMetaData_SentBy()
    {
        Map metaInfo = new HashMap ();

        metaInfo.put ("dbcol", "sent_by");
        metaInfo.put ("name", "SentBy");
        metaInfo.put ("type", "SecUser");
        metaInfo.put (METADATA_DB_TABLENAME, "tl_message");
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Message.SentBy:", metaInfo);
        ATTRIBUTES_METADATA_Message.put (SINGLEREFERENCE_SentBy, Collections.unmodifiableMap (metaInfo));
    }
    
    
    private static void setupAssocMetaData_WorkFlowMessage()
    {
        Map metaInfo = new HashMap ();

        metaInfo.put ("dbcol", "work_flow_message");
        metaInfo.put ("name", "WorkFlowMessage");
        metaInfo.put ("type", "WorkFlowMessage");
        metaInfo.put (METADATA_DB_TABLENAME, "tl_message");
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Message.WorkFlowMessage:", metaInfo);
        ATTRIBUTES_METADATA_Message.put (SINGLEREFERENCE_WorkFlowMessage, Collections.unmodifiableMap (metaInfo));
    }
    
    
    private static void setupAssocMetaData_JobApplication()
    {
        Map metaInfo = new HashMap ();

        metaInfo.put ("backreferenceName", "Messages");
        metaInfo.put ("dbcol", "job_application_id");
        metaInfo.put ("mandatory", "true");
        metaInfo.put ("name", "JobApplication");
        metaInfo.put ("type", "JobApplication");
        metaInfo.put (METADATA_DB_TABLENAME, "tl_message");
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Message.JobApplication:", metaInfo);
        ATTRIBUTES_METADATA_Message.put (SINGLEREFERENCE_JobApplication, Collections.unmodifiableMap (metaInfo));
    }
    
    
    private static List setupAttribMetaData_SentVia(Map validatorMapping)
    {
        Map  metaInfo   = new HashMap ();

        metaInfo.put ("attribHelper", "EnumeratedAttributeHelper");
        metaInfo.put ("dbcol", "sent_via");
        metaInfo.put ("defaultValue", "SentVia.ON_APP");
        metaInfo.put ("mandatory", "false");
        metaInfo.put ("name", "SentVia");
        metaInfo.put ("type", "SentVia");
        metaInfo.put (METADATA_DB_TABLENAME, "tl_message");
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Message.SentVia:", metaInfo);
        ATTRIBUTES_METADATA_Message.put (FIELD_SentVia, Collections.unmodifiableMap (metaInfo));

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

        return validators;
    }
    
    private static List setupAttribMetaData_MessageContent(Map validatorMapping)
    {
        Map  metaInfo   = new HashMap ();

        metaInfo.put ("dbcol", "message_content");
        metaInfo.put ("mandatory", "false");
        metaInfo.put ("name", "MessageContent");
        metaInfo.put ("type", "String");
        metaInfo.put (METADATA_DB_TABLENAME, "tl_message");
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Message.MessageContent:", metaInfo);
        ATTRIBUTES_METADATA_Message.put (FIELD_MessageContent, Collections.unmodifiableMap (metaInfo));

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

        return validators;
    }
    
    private static List setupAttribMetaData_IsRead(Map validatorMapping)
    {
        Map  metaInfo   = new HashMap ();

        metaInfo.put ("dbcol", "is_read");
        metaInfo.put ("mandatory", "false");
        metaInfo.put ("name", "IsRead");
        metaInfo.put ("type", "Boolean");
        metaInfo.put (METADATA_DB_TABLENAME, "tl_message");
        LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG2, "Metadata for Message.IsRead:", metaInfo);
        ATTRIBUTES_METADATA_Message.put (FIELD_IsRead, Collections.unmodifiableMap (metaInfo));

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

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


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

    


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

        
        _SentVia = (SentVia)(SentVia.ON_APP);
        _MessageContent = (String)(HELPER_MessageContent.initialise (_MessageContent));
        _IsRead = (Boolean)(HELPER_IsRead.initialise (_IsRead));
    }


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

        _SentBy = new SingleAssociation<Message, SecUser> (this, SINGLEREFERENCE_SentBy, null, SecUser.REFERENCE_SecUser, "tl_message");
        _WorkFlowMessage = new SingleAssociation<Message, WorkFlowMessage> (this, SINGLEREFERENCE_WorkFlowMessage, null, WorkFlowMessage.REFERENCE_WorkFlowMessage, "tl_message");
        _JobApplication = new SingleAssociation<Message, JobApplication> (this, SINGLEREFERENCE_JobApplication, JobApplication.MULTIPLEREFERENCE_Messages, JobApplication.REFERENCE_JobApplication, "tl_message");
        _Attachments = new MultipleAssociation<Message, ChatAttachment> (this, MULTIPLEREFERENCE_Attachments, ChatAttachment.SINGLEREFERENCE_Message, ChatAttachment.REFERENCE_ChatAttachment);
    }


    protected BaseBusinessClass initialiseReference ()
    {
        super.initialiseReference ();
        
        _SentBy = new SingleAssociation<Message, SecUser> (this, SINGLEREFERENCE_SentBy, null, SecUser.REFERENCE_SecUser, "tl_message");
        _WorkFlowMessage = new SingleAssociation<Message, WorkFlowMessage> (this, SINGLEREFERENCE_WorkFlowMessage, null, WorkFlowMessage.REFERENCE_WorkFlowMessage, "tl_message");
        _JobApplication = new SingleAssociation<Message, JobApplication> (this, SINGLEREFERENCE_JobApplication, JobApplication.MULTIPLEREFERENCE_Messages, JobApplication.REFERENCE_JobApplication, "tl_message");
        _Attachments = new MultipleAssociation<Message, ChatAttachment> (this, MULTIPLEREFERENCE_Attachments, ChatAttachment.SINGLEREFERENCE_Message, ChatAttachment.REFERENCE_ChatAttachment);
        
        return this;
    }


    /**
     * Attribute SentVia
     */
    public SentVia getSentVia ()
    {
        assertValid();
        SentVia valToReturn = AttributeDecoratorUtils.getValue (FIELD_SentVia_Decorators, (Message)this, FIELD_SentVia, _SentVia);

        
        for (MessageBehaviourDecorator bhd : Message_BehaviourDecorators)
        {
            valToReturn = bhd.getSentVia ((Message)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 preSentViaChange (SentVia newSentVia) 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 postSentViaChange () throws FieldException
    {
    }

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

    /**
     * Set the attribute SentVia.  Checks to ensure a new value
     * has been supplied.  If so, marks the field as altered and sets the attribute.
     */
    public void setSentVia (SentVia newSentVia) throws FieldException
    {
        newSentVia = AttributeDecoratorUtils.setValue (FIELD_SentVia_Decorators, (Message)this, FIELD_SentVia, newSentVia);

        boolean oldAndNewIdentical = HELPER_SentVia.compare (_SentVia, newSentVia);
        
        try
        {
            for (MessageBehaviourDecorator bhd : Message_BehaviourDecorators)
            {
                newSentVia = bhd.setSentVia ((Message)this, newSentVia);
                oldAndNewIdentical = HELPER_SentVia.compare (_SentVia, newSentVia);
            }

            

            if (FIELD_SentVia_Validators.length > 0)
            {
                Object newSentViaObj = HELPER_SentVia.toObject (newSentVia);

                if (newSentViaObj != null)
                {
                    int     loopMax = FIELD_SentVia_Validators.length;
                    Map     metadata = (Map)ATTRIBUTES_METADATA_Message.get (FIELD_SentVia);

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

        if (!oldAndNewIdentical)
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (FIELD_SentVia_Decorators, (Message)this, FIELD_SentVia ,getWriteability_SentVia ()) != FieldWriteability.FALSE, "Field  SentVia is not writeable");
            preSentViaChange (newSentVia);
            markFieldChange (FIELD_SentVia);
            _SentVia = newSentVia;            
            postFieldChange (FIELD_SentVia);
            postSentViaChange ();
        }
    }

    /**
     * Attribute MessageContent
     */
    public String getMessageContent ()
    {
        assertValid();
        String valToReturn = AttributeDecoratorUtils.getValue (FIELD_MessageContent_Decorators, (Message)this, FIELD_MessageContent, _MessageContent);

        
        for (MessageBehaviourDecorator bhd : Message_BehaviourDecorators)
        {
            valToReturn = bhd.getMessageContent ((Message)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 preMessageContentChange (String newMessageContent) 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 postMessageContentChange () throws FieldException
    {
    }

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

    /**
     * Set the attribute MessageContent.  Checks to ensure a new value
     * has been supplied.  If so, marks the field as altered and sets the attribute.
     */
    public void setMessageContent (String newMessageContent) throws FieldException
    {
        newMessageContent = AttributeDecoratorUtils.setValue (FIELD_MessageContent_Decorators, (Message)this, FIELD_MessageContent, newMessageContent);

        boolean oldAndNewIdentical = HELPER_MessageContent.compare (_MessageContent, newMessageContent);
        
        try
        {
            for (MessageBehaviourDecorator bhd : Message_BehaviourDecorators)
            {
                newMessageContent = bhd.setMessageContent ((Message)this, newMessageContent);
                oldAndNewIdentical = HELPER_MessageContent.compare (_MessageContent, newMessageContent);
            }

            

            if (FIELD_MessageContent_Validators.length > 0)
            {
                Object newMessageContentObj = HELPER_MessageContent.toObject (newMessageContent);

                if (newMessageContentObj != null)
                {
                    int     loopMax = FIELD_MessageContent_Validators.length;
                    Map     metadata = (Map)ATTRIBUTES_METADATA_Message.get (FIELD_MessageContent);

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

        if (!oldAndNewIdentical)
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (FIELD_MessageContent_Decorators, (Message)this, FIELD_MessageContent ,getWriteability_MessageContent ()) != FieldWriteability.FALSE, "Field  MessageContent is not writeable");
            preMessageContentChange (newMessageContent);
            markFieldChange (FIELD_MessageContent);
            _MessageContent = newMessageContent;            
            postFieldChange (FIELD_MessageContent);
            postMessageContentChange ();
        }
    }

    /**
     * Attribute IsRead
     */
    public Boolean getIsRead ()
    {
        assertValid();
        Boolean valToReturn = AttributeDecoratorUtils.getValue (FIELD_IsRead_Decorators, (Message)this, FIELD_IsRead, _IsRead);

        
        for (MessageBehaviourDecorator bhd : Message_BehaviourDecorators)
        {
            valToReturn = bhd.getIsRead ((Message)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 preIsReadChange (Boolean newIsRead) 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 postIsReadChange () throws FieldException
    {
    }

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

    /**
     * Set the attribute IsRead.  Checks to ensure a new value
     * has been supplied.  If so, marks the field as altered and sets the attribute.
     */
    public void setIsRead (Boolean newIsRead) throws FieldException
    {
        newIsRead = AttributeDecoratorUtils.setValue (FIELD_IsRead_Decorators, (Message)this, FIELD_IsRead, newIsRead);

        boolean oldAndNewIdentical = HELPER_IsRead.compare (_IsRead, newIsRead);
        
        try
        {
            for (MessageBehaviourDecorator bhd : Message_BehaviourDecorators)
            {
                newIsRead = bhd.setIsRead ((Message)this, newIsRead);
                oldAndNewIdentical = HELPER_IsRead.compare (_IsRead, newIsRead);
            }

            

            if (FIELD_IsRead_Validators.length > 0)
            {
                Object newIsReadObj = HELPER_IsRead.toObject (newIsRead);

                if (newIsReadObj != null)
                {
                    int     loopMax = FIELD_IsRead_Validators.length;
                    Map     metadata = (Map)ATTRIBUTES_METADATA_Message.get (FIELD_IsRead);

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

        if (!oldAndNewIdentical)
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (FIELD_IsRead_Decorators, (Message)this, FIELD_IsRead ,getWriteability_IsRead ()) != FieldWriteability.FALSE, "Field  IsRead is not writeable");
            preIsReadChange (newIsRead);
            markFieldChange (FIELD_IsRead);
            _IsRead = newIsRead;            
            postFieldChange (FIELD_IsRead);
            postIsReadChange ();
        }
    }



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

        return result;
    }
    
    
    public BaseBusinessClass getSingleAssocReferenceInstance (String assocName)
    {
        if (assocName == null)
        {
            throw new RuntimeException ("Game over == null!");
        }
        else if (assocName.equals (SINGLEREFERENCE_SentBy))
        {
            return _SentBy.getReferencedType ();
        }
        else if (assocName.equals (SINGLEREFERENCE_WorkFlowMessage))
        {
            return _WorkFlowMessage.getReferencedType ();
        }
        else if (assocName.equals (SINGLEREFERENCE_JobApplication))
        {
            return _JobApplication.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_SentBy))
        {
            return null ;
        }
        else if (assocName.equals (SINGLEREFERENCE_WorkFlowMessage))
        {
            return null ;
        }
        else if (assocName.equals (SINGLEREFERENCE_JobApplication))
        {
            return JobApplication.MULTIPLEREFERENCE_Messages ;
        }
        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_SentBy))
        {
            return getSentBy ();
        }
        else if (assocName.equals (SINGLEREFERENCE_WorkFlowMessage))
        {
            return getWorkFlowMessage ();
        }
        else if (assocName.equals (SINGLEREFERENCE_JobApplication))
        {
            return getJobApplication ();
        }
        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_SentBy))
        {
            return getSentBy (getType);
        }
        else if (assocName.equals (SINGLEREFERENCE_WorkFlowMessage))
        {
            return getWorkFlowMessage (getType);
        }
        else if (assocName.equals (SINGLEREFERENCE_JobApplication))
        {
            return getJobApplication (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_SentBy))
        {
            return getSentByID ();
        }
        else if (assocName.equals (SINGLEREFERENCE_WorkFlowMessage))
        {
            return getWorkFlowMessageID ();
        }
        else if (assocName.equals (SINGLEREFERENCE_JobApplication))
        {
            return getJobApplicationID ();
        }
        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_SentBy))
        {
            setSentBy ((SecUser)(newValue));
        }
        else if (assocName.equals (SINGLEREFERENCE_WorkFlowMessage))
        {
            setWorkFlowMessage ((WorkFlowMessage)(newValue));
        }
        else if (assocName.equals (SINGLEREFERENCE_JobApplication))
        {
            setJobApplication ((JobApplication)(newValue));
        }
        else
        {
            super.setSingleAssoc (assocName, newValue);
        }
    }



    /**
     * Get the reference SentBy
     */
    public SecUser getSentBy () throws StorageException
    {
        assertValid();
        
        try
        {
            return (SecUser)(_SentBy.get ());
        }
        catch (ClassCastException e)
        {
            LogMgr.log (BUSINESS_OBJECTS, LogLevel.SYSTEMERROR2, "Cache collision in Message:", this.getObjectID (), ", was trying to get SecUser:",  getSentByID ());
            LogMgr.log (BUSINESS_OBJECTS, LogLevel.SYSTEMERROR2, "Instead I got:", _SentBy.get ().getClass ());
            throw e;
        }
    }


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


    /**
     * Get the object id for the referenced object.  Does not force a DB access.
     */
    public Long getSentByID ()
    {
        assertValid();
        
        if (_SentBy == null)
        {
            return null;
        }
        else
        {
            return _SentBy.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 preSentByChange (SecUser newSentBy) 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 postSentByChange () throws FieldException
    {
    }


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

        
    /**
     * Set the reference SentBy.  Checks to ensure a new value
     * has been supplied.  If so, marks the reference as altered and sets it.
     */
    public void setSentBy (SecUser newSentBy) throws StorageException, FieldException
    {
        if (_SentBy.wouldReferencedChange (newSentBy))
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (SINGLEREFERENCE_SentBy_Decorators, (Message)this, SINGLEREFERENCE_SentBy ,getWriteability_SentBy ()) != FieldWriteability.FALSE, "Assoc SentBy is not writeable");
            preSentByChange (newSentBy);
            
            _SentBy.set (newSentBy);
                
            postSentByChange ();
        }
    }

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


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


    /**
     * Get the object id for the referenced object.  Does not force a DB access.
     */
    public Long getWorkFlowMessageID ()
    {
        assertValid();
        
        if (_WorkFlowMessage == null)
        {
            return null;
        }
        else
        {
            return _WorkFlowMessage.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 preWorkFlowMessageChange (WorkFlowMessage newWorkFlowMessage) 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 postWorkFlowMessageChange () throws FieldException
    {
    }


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

        
    /**
     * Set the reference WorkFlowMessage.  Checks to ensure a new value
     * has been supplied.  If so, marks the reference as altered and sets it.
     */
    public void setWorkFlowMessage (WorkFlowMessage newWorkFlowMessage) throws StorageException, FieldException
    {
        if (_WorkFlowMessage.wouldReferencedChange (newWorkFlowMessage))
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (SINGLEREFERENCE_WorkFlowMessage_Decorators, (Message)this, SINGLEREFERENCE_WorkFlowMessage ,getWriteability_WorkFlowMessage ()) != FieldWriteability.FALSE, "Assoc WorkFlowMessage is not writeable");
            preWorkFlowMessageChange (newWorkFlowMessage);
            
            _WorkFlowMessage.set (newWorkFlowMessage);
                
            postWorkFlowMessageChange ();
        }
    }

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


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


    /**
     * Get the object id for the referenced object.  Does not force a DB access.
     */
    public Long getJobApplicationID ()
    {
        assertValid();
        
        if (_JobApplication == null)
        {
            return null;
        }
        else
        {
            return _JobApplication.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 preJobApplicationChange (JobApplication newJobApplication) 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 postJobApplicationChange () throws FieldException
    {
    }


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

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

        if (_JobApplication.wouldReferencedChange (newJobApplication))
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (SINGLEREFERENCE_JobApplication_Decorators, (Message)this, SINGLEREFERENCE_JobApplication ,getWriteability_JobApplication ()) != FieldWriteability.FALSE, "Assoc JobApplication is not writeable");
            preJobApplicationChange (newJobApplication);
            JobApplication oldJobApplication = getJobApplication ();

            if (oldJobApplication != null)
            {
                // This is to stop validation from triggering when we are removed
                _JobApplication.set (null);
                oldJobApplication.removeFromMessages ((Message)(this));
            }

            _JobApplication.set (newJobApplication);

            if (newJobApplication != null)
            {
                newJobApplication.addToMessages ((Message)(this));
            }
                
            postJobApplicationChange ();
        }
    }

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

        return result;
    }


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

        return super.getMultiAssocReferenceInstance(attribName);
    }


    public String getMultiAssocBackReference(String attribName)
    {
        if (MULTIPLEREFERENCE_Attachments.equals(attribName))
        {
            return ChatAttachment.SINGLEREFERENCE_Message ;
        }

        return super.getMultiAssocBackReference(attribName);
    }


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

        return super.getMultiAssocCount(attribName);
    }


    /**
     * Get the assoc at a particular index
     */
    public BaseBusinessClass getMultiAssocAt(String attribName, int index) throws StorageException
    {
        if (MULTIPLEREFERENCE_Attachments.equals(attribName))
        {
            return this.getAttachmentsAt(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_Attachments.equals(attribName))
        {
            addToAttachments((ChatAttachment)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_Attachments.equals(attribName))
        {
            removeFromAttachments((ChatAttachment)oldElement);
            return;
        }

        super.removeFromMultiAssoc(attribName, oldElement);
    }


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

        super.__loadMultiAssoc(attribName, elements);
    }


    protected boolean __isMultiAssocLoaded (String attribName)
    {
        if (MULTIPLEREFERENCE_Attachments.equals(attribName))
        {
            return _Attachments.isLoaded ();
        }

        return super.__isMultiAssocLoaded(attribName);
    }


    public FieldWriteability getWriteability_Attachments ()
    {
        return getFieldWritabilityUtil (FieldWriteability.TRUE);
    }
    
    
    public int getAttachmentsCount () throws StorageException
    {
        assertValid();
        return _Attachments.getReferencedObjectsCount ();
    }


    public void addToAttachments (ChatAttachment newElement) throws StorageException
    {
        if (_Attachments.wouldAddChange (newElement))
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (MULTIPLEREFERENCE_Attachments_Decorators, (Message)this, MULTIPLEREFERENCE_Attachments ,getWriteability_Attachments ()) != FieldWriteability.FALSE, "MultiAssoc Attachments is not writeable (add)");
            _Attachments.appendElement (newElement);

            try
            {
                if (newElement.getMessage () != this)
                {
                    newElement.setMessage ((Message)(this));
                }
            }
            catch (Exception e)
            {
                throw NestedException.wrap(e);
            }
        }
    }


    public void removeFromAttachments (ChatAttachment elementToRemove) throws StorageException
    {
        if (_Attachments.wouldRemoveChange (elementToRemove))
        {
            assertValid();
            Debug.assertion (AttributeDecoratorUtils.getWriteability (MULTIPLEREFERENCE_Attachments_Decorators, (Message)this, MULTIPLEREFERENCE_Attachments ,getWriteability_Attachments ()) != FieldWriteability.FALSE, "MultiAssoc Attachments is not writeable (remove)");
            _Attachments.removeElement (elementToRemove);
            try
            {
                if (elementToRemove.getMessage () != null)
                {
                    elementToRemove.setMessage (null);
                }
            }
            catch (Exception e)
            {
                throw NestedException.wrap(e);
            }
        }
    }


    public ChatAttachment getAttachmentsAt (int index) throws StorageException
    {
        return (ChatAttachment)(_Attachments.getElementAt (index));
    }


    public SortedSet<ChatAttachment> getAttachmentsSet () throws StorageException
    {
        return _Attachments.getSet ();
    }



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

                if (referenced != null)
                {
                    // Stop the callback
                    LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG1, "Setting backreference to null Messages from ", getObjectID (), " to ", referenced.getObjectID ());
                    _JobApplication.set (null);
                    referenced.removeFromMessages ((Message)this);
                }
            }
        
            for(ChatAttachment referenced : CollectionUtils.reverse(getAttachmentsSet()))
            { 
                LogMgr.log (BUSINESS_OBJECTS, LogLevel.DEBUG1, "Setting backreference to null Message from ", getObjectID (), " to ", referenced.getObjectID ());
                referenced.setMessage(null);
            }

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

        super.onDelete ();
    }


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


    public Message referenceInstance ()
    {
        return REFERENCE_Message;
    }


    public Message getInTransaction (ObjectTransaction t) throws StorageException
    {
        return getMessageByID (t, getObjectID());
    }
    
    
    public BaseBusinessClass dummyInstance ()
    {
        return DUMMY_Message;
    }


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



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

        tl_messagePSet.setAttrib (FIELD_ObjectID, myID);
        tl_messagePSet.setAttrib (FIELD_SentVia, HELPER_SentVia.toObject (_SentVia)); //
        tl_messagePSet.setAttrib (FIELD_MessageContent, HELPER_MessageContent.toObject (_MessageContent)); //
        tl_messagePSet.setAttrib (FIELD_IsRead, HELPER_IsRead.toObject (_IsRead)); //
        _SentBy.getPersistentSets (allSets);
        _WorkFlowMessage.getPersistentSets (allSets);
        _JobApplication.getPersistentSets (allSets);
        
    }


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

        _SentVia = (SentVia)(HELPER_SentVia.fromObject (_SentVia, tl_messagePSet.getAttrib (FIELD_SentVia))); //
        _MessageContent = (String)(HELPER_MessageContent.fromObject (_MessageContent, tl_messagePSet.getAttrib (FIELD_MessageContent))); //
        _IsRead = (Boolean)(HELPER_IsRead.fromObject (_IsRead, tl_messagePSet.getAttrib (FIELD_IsRead))); //
        _SentBy.setFromPersistentSets (objectID, allSets);
        _WorkFlowMessage.setFromPersistentSets (objectID, allSets);
        _JobApplication.setFromPersistentSets (objectID, allSets);
        
    }


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

        if (other instanceof Message)
        {
            Message otherMessage = (Message)other;
            

            try
            {
                setSentVia (otherMessage.getSentVia ());
            }
            catch (FieldException ex)
            {
                e.addException (ex);
            }

            try
            {
                setMessageContent (otherMessage.getMessageContent ());
            }
            catch (FieldException ex)
            {
                e.addException (ex);
            }

            try
            {
                setIsRead (otherMessage.getIsRead ());
            }
            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 BaseMessage)
        {
            BaseMessage sourceMessage = (BaseMessage)(source);

            _SentVia = sourceMessage._SentVia;
            _MessageContent = sourceMessage._MessageContent;
            _IsRead = sourceMessage._IsRead;
            
        }
    }


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

            _SentBy.copyFrom (sourceMessage._SentBy, linkToGhosts);
            _WorkFlowMessage.copyFrom (sourceMessage._WorkFlowMessage, linkToGhosts);
            _JobApplication.copyFrom (sourceMessage._JobApplication, 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 BaseMessage)
        {
            BaseMessage sourceMessage = (BaseMessage)(source);

            _Attachments.copyFrom (sourceMessage._Attachments, linkToGhosts);
            
        }
    }


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

        
        context.check (getJobApplicationID() != null, this, SINGLEREFERENCE_JobApplication, "mandatory");
        
    }


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

        _SentVia = (SentVia)(HELPER_SentVia.readExternal (_SentVia, vals.get(FIELD_SentVia))); //
        _MessageContent = (String)(HELPER_MessageContent.readExternal (_MessageContent, vals.get(FIELD_MessageContent))); //
        _IsRead = (Boolean)(HELPER_IsRead.readExternal (_IsRead, vals.get(FIELD_IsRead))); //
        _SentBy.readExternalData(vals.get(SINGLEREFERENCE_SentBy));
        _WorkFlowMessage.readExternalData(vals.get(SINGLEREFERENCE_WorkFlowMessage));
        _JobApplication.readExternalData(vals.get(SINGLEREFERENCE_JobApplication));
        _Attachments.readExternalData(vals.get(MULTIPLEREFERENCE_Attachments));
        
    }


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

        vals.put (FIELD_SentVia, HELPER_SentVia.writeExternal (_SentVia));
        vals.put (FIELD_MessageContent, HELPER_MessageContent.writeExternal (_MessageContent));
        vals.put (FIELD_IsRead, HELPER_IsRead.writeExternal (_IsRead));
        vals.put (SINGLEREFERENCE_SentBy, _SentBy.writeExternalData());
        vals.put (SINGLEREFERENCE_WorkFlowMessage, _WorkFlowMessage.writeExternalData());
        vals.put (SINGLEREFERENCE_JobApplication, _JobApplication.writeExternalData());
        vals.put (MULTIPLEREFERENCE_Attachments, _Attachments.writeExternalData());
        
    }


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

        if (other instanceof BaseMessage)
        {
            BaseMessage otherMessage = (BaseMessage)(other);

            
            if (!HELPER_SentVia.compare(this._SentVia, otherMessage._SentVia))
            {
                listener.notifyFieldChange(this, other, FIELD_SentVia, HELPER_SentVia.toObject(this._SentVia), HELPER_SentVia.toObject(otherMessage._SentVia));
            }
            if (!HELPER_MessageContent.compare(this._MessageContent, otherMessage._MessageContent))
            {
                listener.notifyFieldChange(this, other, FIELD_MessageContent, HELPER_MessageContent.toObject(this._MessageContent), HELPER_MessageContent.toObject(otherMessage._MessageContent));
            }
            if (!HELPER_IsRead.compare(this._IsRead, otherMessage._IsRead))
            {
                listener.notifyFieldChange(this, other, FIELD_IsRead, HELPER_IsRead.toObject(this._IsRead), HELPER_IsRead.toObject(otherMessage._IsRead));
            }

            // Compare single assocs
            _SentBy.compare (otherMessage._SentBy, listener);
            _WorkFlowMessage.compare (otherMessage._WorkFlowMessage, listener);
            _JobApplication.compare (otherMessage._JobApplication, listener);
            

            // Compare multiple assocs
            _Attachments.compare (otherMessage._Attachments, 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_SentVia, HELPER_SentVia.toObject(getSentVia()));
        visitor.visitField(this, FIELD_MessageContent, HELPER_MessageContent.toObject(getMessageContent()));
        visitor.visitField(this, FIELD_IsRead, HELPER_IsRead.toObject(getIsRead()));
        visitor.visitAssociation (_SentBy);
        visitor.visitAssociation (_WorkFlowMessage);
        visitor.visitAssociation (_JobApplication);
        visitor.visitAssociation (_Attachments);
        
    }


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

        if (scope.includes (_SentBy))
        {
            visitor.visit (_SentBy);
        }
        if (scope.includes (_WorkFlowMessage))
        {
            visitor.visit (_WorkFlowMessage);
        }
        if (scope.includes (_JobApplication))
        {
            visitor.visit (_JobApplication);
        }
        if (scope.includes (_Attachments))
        {
            visitor.visit (_Attachments);
        }
        
    }


    public static Message createMessage (ObjectTransaction transaction) throws StorageException
    {
        Message     result = new Message ();

        result.initialiseNewObject (transaction);

        return result;
    }


    public static Message getMessageByID (ObjectTransaction transaction, Long objectID) throws StorageException
    {
        return (Message)(transaction.getObjectByID (REFERENCE_Message, objectID));
    }

    public boolean testFilter (String attribName, QueryFilter filter) throws StorageException
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_SentVia))
        {
            return filter.matches (getSentVia ());
        }
        else if (attribName.equals (FIELD_MessageContent))
        {
            return filter.matches (getMessageContent ());
        }
        else if (attribName.equals (FIELD_IsRead))
        {
            return filter.matches (getIsRead ());
        }
        else if (attribName.equals (SINGLEREFERENCE_SentBy))
        {
            return filter.matches (getSentBy ());
        }
        else if (attribName.equals (SINGLEREFERENCE_WorkFlowMessage))
        {
            return filter.matches (getWorkFlowMessage ());
        }
        else if (attribName.equals (SINGLEREFERENCE_JobApplication))
        {
            return filter.matches (getJobApplication ());
        }
        else
        {
            return super.testFilter (attribName, filter);
        }
    }


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

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

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

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

            
        public SearchAll andSentVia (QueryFilter<SentVia> filter)
        {
            filter.addFilter (context, "tl_message.sent_via", "SentVia");
            return this;
        }
            
        public SearchAll andMessageContent (QueryFilter<String> filter)
        {
            filter.addFilter (context, "tl_message.message_content", "MessageContent");
            return this;
        }
            
        public SearchAll andIsRead (QueryFilter<Boolean> filter)
        {
            filter.addFilter (context, "tl_message.is_read", "IsRead");
            return this;
        }
            
        public SearchAll andSentBy (QueryFilter<SecUser> filter)
        {
            filter.addFilter (context, "tl_message.sent_by", "SentBy");
            return this;
        }
            
        public SearchAll andWorkFlowMessage (QueryFilter<WorkFlowMessage> filter)
        {
            filter.addFilter (context, "tl_message.work_flow_message", "WorkFlowMessage");
            return this;
        }
            
        public SearchAll andJobApplication (QueryFilter<JobApplication> filter)
        {
            filter.addFilter (context, "tl_message.job_application_id", "JobApplication");
            return this;
        }
            
        public Message[] search (ObjectTransaction transaction) throws StorageException
        {
            
            BaseBusinessClass[]     results = super.search (transaction, REFERENCE_Message, SEARCH_All, criteria);
            Set<Message>   typedResults = new LinkedHashSet <Message> ();
            for (BaseBusinessClass bbcResult : results)
            {
                Message aResult = (Message)bbcResult;
                
                typedResults.add (aResult);
            }
            
            return ObjstoreUtils.removeDeleted(transaction, typedResults).toArray (new Message[0]);
                            
        }
    }

        
    public static Message[] 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_SentVia))
        {
            return HELPER_SentVia.toObject (getSentVia ());
        }
        else if (attribName.equals (FIELD_MessageContent))
        {
            return HELPER_MessageContent.toObject (getMessageContent ());
        }
        else if (attribName.equals (FIELD_IsRead))
        {
            return HELPER_IsRead.toObject (getIsRead ());
        }
        else
        {
            return super.getAttribute (attribName);
        }
    }


    public AttributeHelper getAttributeHelper (String attribName)
    {
        if (false)
        {
            throw new RuntimeException ("Game over man!!");
        }
        else if (attribName.equals (FIELD_SentVia))
        {
            return HELPER_SentVia;
        }
        else if (attribName.equals (FIELD_MessageContent))
        {
            return HELPER_MessageContent;
        }
        else if (attribName.equals (FIELD_IsRead))
        {
            return HELPER_IsRead;
        }
        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_SentVia))
        {
            setSentVia ((SentVia)(HELPER_SentVia.fromObject (_SentVia, attribValue)));            
        }
        else if (attribName.equals (FIELD_MessageContent))
        {
            setMessageContent ((String)(HELPER_MessageContent.fromObject (_MessageContent, attribValue)));            
        }
        else if (attribName.equals (FIELD_IsRead))
        {
            setIsRead ((Boolean)(HELPER_IsRead.fromObject (_IsRead, 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_SentVia))
        {
            return getWriteability_SentVia ();
        }
        else if (fieldName.equals (FIELD_MessageContent))
        {
            return getWriteability_MessageContent ();
        }
        else if (fieldName.equals (FIELD_IsRead))
        {
            return getWriteability_IsRead ();
        }
        else if (fieldName.equals (MULTIPLEREFERENCE_Attachments))
        {
            return getWriteability_Attachments ();
        }
        else if (fieldName.equals (SINGLEREFERENCE_SentBy))
        {
            return getWriteability_SentBy ();
        }
        else if (fieldName.equals (SINGLEREFERENCE_WorkFlowMessage))
        {
            return getWriteability_WorkFlowMessage ();
        }
        else if (fieldName.equals (SINGLEREFERENCE_JobApplication))
        {
            return getWriteability_JobApplication ();
        }
        else
        {
            return super.getWriteable (fieldName);
        }
    }


    public void putUnwriteable (Set<String> fields)
    {
        if (getWriteability_SentVia () != FieldWriteability.TRUE)
        {
            fields.add (FIELD_SentVia);
        }
        
        if (getWriteability_MessageContent () != FieldWriteability.TRUE)
        {
            fields.add (FIELD_MessageContent);
        }
        
        if (getWriteability_IsRead () != FieldWriteability.TRUE)
        {
            fields.add (FIELD_IsRead);
        }
        

        super.putUnwriteable (fields);
    }

    public String[] getAllTableNames()
    {
        return new String[] {"tl_message"};
    }
    
    public boolean isPolymorphic(String tableName)
    {
        return super.isPolymorphic(tableName);
    }


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

        
        result.add(HELPER_SentVia.getAttribObject (getClass (), _SentVia, false, FIELD_SentVia));
        result.add(HELPER_MessageContent.getAttribObject (getClass (), _MessageContent, false, FIELD_MessageContent));
        result.add(HELPER_IsRead.getAttribObject (getClass (), _IsRead, false, FIELD_IsRead));

        return result;
    }


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


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

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

        copyInto.putAll(ATTRIBUTES_METADATA_Message);
    }
            

    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 MessageBehaviourDecorator extends BaseBusinessClass.BBCBehaviourDecorator<Message>
    {

    /**
     * Get the attribute SentVia
     */
    public SentVia getSentVia (Message obj, SentVia original)
    {
        return original;
    }

    /**
     * Change the value set for attribute SentVia.
     * May modify the field beforehand
     * Occurs before validation.
     */
    public SentVia setSentVia (Message obj, SentVia newSentVia) throws FieldException
    {
        return newSentVia;
    }

    /**
     * Get the attribute MessageContent
     */
    public String getMessageContent (Message obj, String original)
    {
        return original;
    }

    /**
     * Change the value set for attribute MessageContent.
     * May modify the field beforehand
     * Occurs before validation.
     */
    public String setMessageContent (Message obj, String newMessageContent) throws FieldException
    {
        return newMessageContent;
    }

    /**
     * Get the attribute IsRead
     */
    public Boolean getIsRead (Message obj, Boolean original)
    {
        return original;
    }

    /**
     * Change the value set for attribute IsRead.
     * May modify the field beforehand
     * Occurs before validation.
     */
    public Boolean setIsRead (Message obj, Boolean newIsRead) throws FieldException
    {
        return newIsRead;
    }

    }

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

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

        public MessagePipeLineFactory (Collection<From> seed)
        {
            super(seed);
        }
        
        
        public PipeLine<From, ? extends Object> to(String name)
        {
            if (name.equals ("Attachments"))
            {
                return toAttachments ();
            }                
            if (name.equals ("SentVia"))
            {
                return toSentVia ();
            }                
            if (name.equals ("MessageContent"))
            {
                return toMessageContent ();
            }                
            if (name.equals ("IsRead"))
            {
                return toIsRead ();
            }                
            if (name.equals ("SentBy"))
            {
                return toSentBy ();
            }                
            if (name.equals ("WorkFlowMessage"))
            {
                return toWorkFlowMessage ();
            }                
            if (name.equals ("JobApplication"))
            {
                return toJobApplication ();
            }                
            
            
            return super.to(name);
        }
        
        
        public SentVia.SentViaPipeLineFactory<From, SentVia> toSentVia () 
        { 
            return new SentVia.SentViaPipeLineFactory<> (this, new ORMAttributePipe<>(FIELD_SentVia));
        }
        
        public PipeLine<From, String> toMessageContent () { return pipe(new ORMAttributePipe<Me, String>(FIELD_MessageContent));  }
        
        public PipeLine<From, Boolean> toIsRead () { return pipe(new ORMAttributePipe<Me, Boolean>(FIELD_IsRead));  }

        public SecUser.SecUserPipeLineFactory<From, SecUser> toSentBy () { return toSentBy (Filter.ALL); }

        public SecUser.SecUserPipeLineFactory<From, SecUser> toSentBy (Filter<SecUser> filter) 
        { 
            return SecUser.REFERENCE_SecUser.new SecUserPipeLineFactory<From, SecUser> (this, new ORMSingleAssocPipe<Me, SecUser>(SINGLEREFERENCE_SentBy, filter)); 
        }

        public WorkFlowMessage.WorkFlowMessagePipeLineFactory<From, WorkFlowMessage> toWorkFlowMessage () { return toWorkFlowMessage (Filter.ALL); }

        public WorkFlowMessage.WorkFlowMessagePipeLineFactory<From, WorkFlowMessage> toWorkFlowMessage (Filter<WorkFlowMessage> filter) 
        { 
            return WorkFlowMessage.REFERENCE_WorkFlowMessage.new WorkFlowMessagePipeLineFactory<From, WorkFlowMessage> (this, new ORMSingleAssocPipe<Me, WorkFlowMessage>(SINGLEREFERENCE_WorkFlowMessage, filter)); 
        }

        public JobApplication.JobApplicationPipeLineFactory<From, JobApplication> toJobApplication () { return toJobApplication (Filter.ALL); }

        public JobApplication.JobApplicationPipeLineFactory<From, JobApplication> toJobApplication (Filter<JobApplication> filter) 
        { 
            return JobApplication.REFERENCE_JobApplication.new JobApplicationPipeLineFactory<From, JobApplication> (this, new ORMSingleAssocPipe<Me, JobApplication>(SINGLEREFERENCE_JobApplication, filter)); 
        }

        public ChatAttachment.ChatAttachmentPipeLineFactory<From, ChatAttachment> toAttachments () { return toAttachments(Filter.ALL); }        

        public ChatAttachment.ChatAttachmentPipeLineFactory<From, ChatAttachment> toAttachments (Filter<ChatAttachment> filter)
        {
            return ChatAttachment.REFERENCE_ChatAttachment.new ChatAttachmentPipeLineFactory<From, ChatAttachment> (this, new ORMMultiAssocPipe<Me, ChatAttachment>(MULTIPLEREFERENCE_Attachments, filter)); 
        }
    }
    
    public boolean isTransientAttrib(String attribName)
    {
        

        return super.isTransientAttrib(attribName);
    }

    public boolean isTransientSingleReference(String assocName)
    {
        

        return super.isTransientSingleReference(assocName);
    }
}

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

    public void assertValid ()
    {
    }


    public SecUser getSentBy () throws StorageException
    {
        return (SecUser)(SecUser.DUMMY_SecUser);
    }


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

    public WorkFlowMessage getWorkFlowMessage () throws StorageException
    {
        return (WorkFlowMessage)(WorkFlowMessage.DUMMY_WorkFlowMessage);
    }


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

    public JobApplication getJobApplication () throws StorageException
    {
        return (JobApplication)(JobApplication.DUMMY_JobApplication);
    }


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

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


    public ChatAttachment getAttachmentsAt (int index) throws StorageException
    {
        throw new RuntimeException ("No elements in a dummy object in association Attachments");
    }


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

}

    
