/*
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.cache.pojo.interceptors;

import org.jboss.aop.joinpoint.Invocation;
import org.jboss.aop.joinpoint.MethodInvocation;
import org.jboss.cache.Fqn;
import org.jboss.cache.pojo.impl.InternalConstant;

import javax.transaction.Transaction;

/**
 * Interceptor to mockup tx failure that resulting in rollback. User can simulate a rollback
 * by setting the static method <code>setRollback</code>. Note that you will need to use
 * setRollback for every method call, that is, it will reset itself after a rollback
 * has been performed.
 *
 * @author Ben Wang
 * @version $Id: PojoFailedTxMockupInterceptor.java 3937 2007-05-30 06:08:03Z jgreene $
 */
public class PojoFailedTxMockupInterceptor extends AbstractInterceptor
{
   public static boolean TX_ROLLBACK = false;

   public static void setTxRollback(boolean isTrue)
   {
      TX_ROLLBACK = isTrue;
   }

   public Object invoke(Invocation in) throws Throwable
   {
      if (!(in instanceof MethodInvocation))
      {
         throw new IllegalArgumentException(
                 "PojoFailedTxMockupInterceptor.invoke(): invocation not MethodInvocation");
      }
      MethodInvocation invocation = (MethodInvocation) in;
      try
      {
         Object obj = null;
         obj = invocation.invokeNext(); // proceed to next advice or actual call
         if(TX_ROLLBACK)
         {
            Transaction tx = (Transaction)
                    invocation.getMetaData().getMetaData(PojoTxInterceptor.TAG, PojoTxInterceptor.TX);

            Fqn id = (Fqn) invocation.getArguments()[0];

            if(!id.isChildOrEquals(InternalConstant.JBOSS_INTERNAL))
            {
               tx.setRollbackOnly();
               TX_ROLLBACK = false;
            }
         }
         return obj;
      } finally
      {
      }
   }
}
