/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.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.4.5 2005/12/01 19:48:41 dimitris 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);
   }
}
