/*
 * JBoss, the OpenSource J2EE webOS
 * 
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.test.messagedriven.beans;

import java.util.Enumeration;
import java.util.Properties;

import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.transaction.Transaction;

import org.jboss.ejb.plugins.jms.DLQHandler;
import org.jboss.logging.Logger;
import org.jboss.mx.util.MBeanProxyExt;
import org.jboss.test.messagedriven.mbeans.TestMessageDrivenManagementMBean;

/**
 * A Test Message Driven Bean 
 *
 * @author <a href="mailto:adrian@jboss.com>Adrian Brock</a>
 * @version <tt>$Revision: 1.4</tt>
 */
public class TestMessageDriven implements MessageDrivenBean, MessageListener
{
   /** The serialVersionUID */
   private static final long serialVersionUID = 1L;

   protected static final Logger log = Logger.getLogger(TestMessageDriven.class);
   
   protected MessageDrivenContext ctx;
   protected TestMessageDrivenManagementMBean mbean;
   
   public void onMessage(Message message)
   {
      log.info("Got message: " + message);
      mbean.addMessage(message);
      if (isDLQ(message))
         return;
      logProperties();
      logTransaction();
      String rollback = getRollback();
      if (rollback.equals("DLQ"))
      {
         log.info("Rollback DLQ");
         ctx.setRollbackOnly();
      }
   }
   
   public boolean isDLQ(Message message)
   {
      try
      {
         if (message.getStringProperty(DLQHandler.JBOSS_ORIG_DESTINATION) != null)
            return true;
      }
      catch (JMSException e)
      {
         log.error("Unhandled error", e);
      }
      return false;
   }
   
   public String getRollback()
   {
      return System.getProperty("test.messagedriven.rollback", "None");
   }
   
   public void logProperties()
   {
      Properties props = System.getProperties();
      for (Enumeration e = props.keys(); e.hasMoreElements();)
      {
         String key = (String) e.nextElement();
         if (key.startsWith("test.messagedriven."))
            log.info(key + "=" + props.getProperty(key));
      }
   }
   
   public Transaction logTransaction()
   {
      Transaction tx = mbean.getTransaction();
      log.info("tx=" + tx);
      return tx;
   }
   
   public void ejbCreate()
   {
      mbean = (TestMessageDrivenManagementMBean) MBeanProxyExt.create(TestMessageDrivenManagementMBean.class, TestMessageDrivenManagementMBean.OBJECT_NAME);
   }
   
   public void ejbRemove()
   {
   }

   public void setMessageDrivenContext(MessageDrivenContext ctx)
   {
      this.ctx = ctx;
   }
}
