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

import org.jboss.aop.joinpoint.FieldReadInvocation;
import org.jboss.aop.joinpoint.FieldWriteInvocation;
import org.jboss.tm.TransactionLocal;

/**
 * This aspect should be scoped PER_JOINPOINT
 * It allows a field to have the value of itself pertain
 * to the current transaction.
 *
 * The fields transactional and non-transactional value is always separate
 * At tx commit, the transactional value the field had is wiped away.
 * At tx commit, the transactional value does not correspond to the non-transactional value
 *
 * If you are within a transaction and you get the value of the field before setting it
 * then the initial transational value will be set to the current non-transactional value
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.2.2.4 $
 */
public class TransactionLocalAspect
{
   private TransactionLocal txLocal = new TransactionLocal();

   public Object access(FieldReadInvocation invocation) throws Throwable
   {
      // Return non-Tx value
      if (txLocal.getTransaction() == null) return invocation.invokeNext();

      // just in case we have a primitive, we can't return null so set txLocal to be the current nonTx value
      if (txLocal.get() == null)
      {
         txLocal.set(invocation.invokeNext());
      }
      return txLocal.get();
   }

   public Object access(FieldWriteInvocation invocation) throws Throwable
   {
      // Return non-Tx value
      if (txLocal.getTransaction() == null) return invocation.invokeNext();

      txLocal.set(invocation.getValue());
      return null;
   }
}
