

package gov.va.med.cds.audit.persistence.jms;


import gov.va.med.cds.audit.AbstractAuditLog;
import gov.va.med.cds.audit.persistence.AuditLogPersistenceManagerInterface;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;


/***
 * JmsAuditLogPersistenceManager writes audit information from READ requests asynchronously to ReadAuditQueue.
 * An increase in performance and throughput is expected decoupling the audit path from the READ Request path
 */
public class JmsAuditLogPersistenceManager
    implements
        AuditLogPersistenceManagerInterface
{
    private static final Log logger = LogFactory.getLog( JmsAuditLogPersistenceManager.class );

    private JmsTemplate readMessagesAuditJmsTemplate = null;
    private String appName;


    /**
     * storeAuditLog sends Audit information from READ requests as a JMS Message to the ReadAuditQueue
     * @param auditLog is the Audit information from a READ Request that gets stored
     */
    public void storeAuditLog( final AbstractAuditLog auditLog )
    {

        try
        {
            readMessagesAuditJmsTemplate.send( new MessageCreator()
            {
                public Message createMessage( Session session )
                    throws JMSException
                {
                    ObjectMessage objectMessage = session.createObjectMessage();
                    objectMessage.setObject( auditLog );
                    return objectMessage;
                }
            } );
        }
        catch ( Exception exception )
        {
            logger.error( gov.va.med.cds.util.LogMessageUtil.buildMessage( null, null, appName, "Error Auditing READ request message. " ), exception );
        }

    }

    @Autowired
    //@Qualifier("cdsAppName")
    public void setAppName( String appName )
    {
        this.appName = appName;
    }


    public String getAppName( )
    {
        return appName;
    }


    @Resource
    public void setReadMessagesAuditJmsTemplate( JmsTemplate readMessagesAuditJmsTemplate )
    {
        this.readMessagesAuditJmsTemplate = readMessagesAuditJmsTemplate;
    }


  }
