/*
 * JBoss, the OpenSource J2EE webOS
 * 
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.resource.adapter.jms.inflow.dlq;

import javax.jms.Message;
import javax.naming.Context;

import org.jboss.resource.adapter.jms.inflow.JmsActivation;

/**
 * A DLQ Handler that knows about JBossMQ redelivery properties
 * 
 * @author <a href="adrian@jboss.com">Adrian Brock</a>
 * @version $Revision: 1.1.2.1 $
 */
public class JBossMQDLQHandler extends AbstractDLQHandler
{
   // Constants -----------------------------------------------------

   /** Properties copied from org.jboss.mq.SpyMessage */
   protected static final String JMS_JBOSS_REDELIVERY_COUNT = "JMS_JBOSS_REDELIVERY_COUNT";

   /** Properties copied from org.jboss.mq.SpyMessage */
   protected static final String JMS_JBOSS_REDELIVERY_LIMIT = "JMS_JBOSS_REDELIVERY_LIMIT";

   // Attributes ----------------------------------------------------
   
   /** The maximum number of resends */
   protected int maxResent;
   
   // Static --------------------------------------------------------

   // Constructors --------------------------------------------------

   // Public --------------------------------------------------------
   
   // AbstractDLQHandler overrides ----------------------------------

   public void setup(JmsActivation activation, Context ctx) throws Exception
   {
      super.setup(activation, ctx);
      maxResent = activation.getActivationSpec().getDLQMaxResent();
   }
   
   protected boolean handleDelivery(Message msg)
   {
      int max = maxResent;
      try
      {
         if (msg.propertyExists(JMS_JBOSS_REDELIVERY_LIMIT))
            max = msg.getIntProperty(JMS_JBOSS_REDELIVERY_LIMIT);

         if (msg.propertyExists(JMS_JBOSS_REDELIVERY_COUNT))
         {
            int count = msg.getIntProperty(JMS_JBOSS_REDELIVERY_COUNT);
         
            if (count > max)
            {
               warnDLQ(msg, count, max);
               return true;
            }
         }
      }
      catch (Throwable t)
      {
         log.warn("Unexpected error retrieving message properties " + msg, t);
      }
      return false;
   }
   
   // Protected -----------------------------------------------------
   
   // Private -------------------------------------------------------

   // Inner classes -------------------------------------------------
}