

package gov.va.med.cds.logger;


import gov.va.med.cds.ejb.interceptor.CdsLoggerAuditAutowiredInterceptor;
import gov.va.med.cds.log4j.ApplicationLogEvent;
import gov.va.med.cds.log4j.persistence.LoggerPersistenceManagerInterface;

import javax.interceptor.Interceptors;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.apache.log4j.spi.LoggingEvent;
import org.apache.logging.log4j.core.LogEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;


/**
 * @author DNS   egberb
 * 
 */
@Interceptors( CdsLoggerAuditAutowiredInterceptor.class )
public class LoggerMessageDrivenBean
    implements
        MessageListener
{

    protected final Log logger = LogFactory.getLog( getClass() );

    @Autowired
    @Qualifier( "loggerPersistenceManager2" )
    private LoggerPersistenceManagerInterface loggerPersistenceManager;


    public LoggerMessageDrivenBean( )
    {
    }


    public void onMessage( Message message )
    {
        ApplicationLogEvent appLogEvent = null;
        try
        {
            ObjectMessage objectMessage = ( ( ObjectMessage )message );
            LogEvent logEvent = ( LogEvent )objectMessage.getObject();

            appLogEvent = new ApplicationLogEvent( logEvent );

            if ( appLogEvent.getDomainName().equalsIgnoreCase( "PharmacyCreateOrUpdate40060" ) && appLogEvent.getMessage().contains( "ORA-00001" ) )
            {
                // Ignore unique constraint exceptions throw due to Rx create messages
            }
            else
            {
                loggerPersistenceManager.persistApplicationLogEvent( appLogEvent );
            }
        }
        catch ( Exception e )
        {
            // make sure that any logs comming from the logging sub-system only go
            // to the file or stdout.
            if ( logger.isErrorEnabled() )
            {
                String appName = null;
                if ( null != appLogEvent )
                {
                    appName = appLogEvent.getAppName();
                }
                logger.error( gov.va.med.cds.util.LogMessageUtil.buildMessage( null, null, appName, "Error proccessing JMS Appender log event. " ),
                                e );
            }
        }
    }

}
