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

import java.util.HashMap;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.jboss.ejb3.stateful.StatefulBeanContext;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.1.6.5 $
 */
public class StatefulEvictionPolicy extends PassivationEvictionPolicy
{

   public StatefulEvictionPolicy()
   {
   }

   public void evict(Fqn fqn) throws Exception
   {
      // never allow root node to be evicted
      if (fqn.size() == 2)
      {
         Node node = cache_.get(fqn);
         StatefulBeanContext bean = (StatefulBeanContext) node.getData().get("bean");
         if (bean == null)
         {
            superEvict(fqn);
            return;
         }
         synchronized (bean)
         {
            if (bean.inUse)
            {
               bean.markedForPassivation = true;
               superEvict(fqn);
               return;
            }
            superEvict(fqn);
            passivate(node, bean);
         }
      }
   }

   public void passivate(Node node, StatefulBeanContext bean) throws Exception
   {
      bean.getContainer().invokePrePassivate(bean.getInstance());
      fileCacheLoader.put(node.getFqn(), node.getData(), true);
   }

   public void passivate(Fqn fqn, StatefulBeanContext bean) throws Exception
   {
      bean.getContainer().invokePrePassivate(bean.getInstance());
      HashMap map = new HashMap();
      map.put("bean", bean);
      fileCacheLoader.put(fqn, map, true);
   }


}
