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

import org.jgroups.blocks.MethodCall;
import org.jboss.cache.TreeCache;
import org.jboss.logging.Logger;

import javax.transaction.Transaction;
import javax.transaction.SystemException;
import javax.transaction.Status;

/**
 * Class representing an interceptor.
 * <em>Note that this will be replaced by {@link org.jboss.aop.advice.Interceptor} in one of the next releases</em>
 * @author Bela Ban
 * @version $Id: Interceptor.java,v 1.1.6.4 2005/04/06 21:06:41 starksm Exp $
 */
public abstract class Interceptor {
   Interceptor next=null;
   TreeCache   cache=null;
   Logger      log=null;

   public Interceptor() {
      log=Logger.getLogger(getClass());
   }


   public void setNext(Interceptor i) {
      next=i;
   }

   public Interceptor getNext() {
      return next;
   }

   public void setCache(TreeCache cache) {
      this.cache=cache;
   }

   public Object invoke(MethodCall m) throws Throwable {
      return next.invoke(m);
   }

   /** Returns true if transaction is ACTIVE, false otherwise */
   boolean isActive(Transaction tx) {
      if(tx == null) return false;
      int status=-1;
      try {
         status=tx.getStatus();
         return status == Status.STATUS_ACTIVE;
      }
      catch(SystemException e) {
         log.error("failed getting transaction status", e);
         return false;
      }
   }

   /** Returns true if transaction is PREPARING, false otherwise */
   boolean isPreparing(Transaction tx) {
      if(tx == null) return false;
      int status=-1;
      try {
         status=tx.getStatus();
         return status == Status.STATUS_PREPARING;
      }
      catch(SystemException e) {
         log.error("failed getting transaction status", e);
         return false;
      }
   }


   /**
    * Return s true of tx's status is ACTIVE or PREPARING
    * @param tx
    * @return
    */
   boolean isValid(Transaction tx) {
      return isActive(tx) || isPreparing(tx);
   }
}