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

import java.lang.reflect.Method;
import java.rmi.RemoteException;

import javax.transaction.Transaction;

import org.jboss.ejb.plugins.AbstractInterceptor;
import org.jboss.invocation.Invocation;
import org.jboss.invocation.InvocationType;
import org.jboss.metadata.BeanMetaData;
import org.jboss.metadata.MetaData;

/**
 * A NoTxPropagationInterceptor for throwing remote exceptions
 * according to the spec.
 * 
 * @author <a href="adrian@jboss.com">Adrian Brock</a>
 * @version $Revision: 1.1.4.1 $
 */
public class NoTxPropagationInterceptor extends AbstractInterceptor
{
   
   public Object invokeHome(Invocation mi) throws Exception
   {
      checkNoTxPropagation(mi);
      return getNext().invokeHome(mi);
   }

   public Object invoke(Invocation mi) throws Exception
   {
      checkNoTxPropagation(mi);
      return getNext().invoke(mi);
   }
   
   protected void checkNoTxPropagation(Invocation mi) throws Exception
   {
      // No problem for local
      if (mi.isLocal())
         return;
      
      // Do we have a foreign transaction context?
      Transaction tx = mi.getTransaction();
      if (tx == null || (tx instanceof ForeignTransaction) == false)
         return;
      
      byte txType = container.getBeanMetaData().getTransactionMethod(mi.getMethod(), mi.getType());
      if (txType != MetaData.TX_NOT_SUPPORTED && txType != MetaData.TX_REQUIRES_NEW)
         throw new RemoteException("TxPropagation is not supported: " + container.getJmxName() + " method=" + mi.getMethod());
      
      // The propogation is not a problem
      mi.setTransaction(null);
   }
}
