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

import org.jboss.aop.advice.Interceptor;
import org.jboss.aop.joinpoint.Invocation;
import org.jboss.ejb3.entity.ExtendedPersistenceContext;
import org.jboss.ejb3.entity.ManagedEntityManagerFactory;
import org.jboss.logging.Logger;

/**
 * Handles @Remove on a Stateful bean.
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 */
public class StatefulRemoveInterceptor implements Interceptor
{
   private static final Logger log = Logger.getLogger(StatefulRemoveInterceptor.class);
   protected boolean retainIfException;

   public StatefulRemoveInterceptor(boolean removeOnException)
   {
      this.retainIfException = removeOnException;
   }

   public String getName()
   {
      return this.getClass().getName();
   }

   public Object invoke(Invocation invocation) throws Throwable
   {
      Object rtn = null;
      try
      {
         rtn = invocation.invokeNext();
      }
      catch (Throwable t)
      {
         if (!retainIfException)
         {
            removeSession(invocation);
         }
         throw t;
      }
      removeSession(invocation);
      return rtn;
   }

   protected void removeSession(Invocation invocation)
   {
      StatefulContainerInvocation ejb = (StatefulContainerInvocation) invocation;
      Object id = ejb.getId();
      StatefulContainer container = (StatefulContainer) ejb.getAdvisor();
      StatefulBeanContext ctx = (StatefulBeanContext) ejb.getBeanContext();
      container.getCache().remove(id);
      ExtendedPersistenceContext session = (ExtendedPersistenceContext) ctx.getMetaData().getMetaData(ManagedEntityManagerFactory.LONG_LIVED_SESSION, ManagedEntityManagerFactory.LONG_LIVED_SESSION);
      if (session != null)
      {
         log.debug("REMOVING EXTENDED PERSISTENCE CONTEXT");
         session.closeExtendedPersistenceContext();
      }
   }
}
