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

import java.io.File;
import javax.management.ObjectName;
import javax.naming.InitialContext;
import org.jboss.cache.TreeCacheMBean;
import org.jboss.cache.loader.FileCacheLoader;
import org.jboss.ejb3.cache.tree.PassivationEvictionPolicy;
import org.jboss.ejb3.cache.tree.PassivationTreeCache;
import org.jboss.mx.util.MBeanProxy;
import org.jboss.system.ServiceMBeanSupport;
import org.jboss.system.server.ServerConfig;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.3.6.4 $
 */
public class Tester extends ServiceMBeanSupport implements TesterMBean
{
   public void test() throws Exception
   {
      ObjectName cacheON = new ObjectName("jboss.cache:service=EJB3TreeCache");
      TreeCacheMBean mbean = (TreeCacheMBean) MBeanProxy.get(TreeCacheMBean.class, cacheON, server);
      PassivationTreeCache cache = (PassivationTreeCache) mbean.getInstance();
      PassivationEvictionPolicy policy = (PassivationEvictionPolicy) cache.getEvictionPolicy();
      policy.createRegion("/mySFSB", 100, 1L);

      cache.put("/mySFSB/1234", "hello", "world");
      System.out.println("After PUT");
      Thread.sleep(5000);

      System.out.println("WAKE UP!");
      File fp = new File(System.getProperty(ServerConfig.SERVER_TEMP_DIR) + "/stateful/mySFSB." + FileCacheLoader.DIR_SUFFIX + "/1234." + FileCacheLoader.DIR_SUFFIX);
      System.out.println("exists in DB: " + fp.exists());
      if (!fp.exists()) throw new RuntimeException("No passivation happened.");
      System.out.println(cache.get("/mySFSB/1234", "hello"));
      System.out.println("exists in DB: " + fp.exists());
      if (fp.exists()) throw new RuntimeException("Should have been removed on activation.");
      if (cache.exists("/mySFSB/1234"))
      {
         cache.remove("/mySFSB/1234");
         synchronized (policy)
         {
            policy.removeRegion("/mySFSB");
         }
         cache.remove("/mySFSB");
      }
   }

   public void testSimpleLocal() throws Exception
   {
      SimpleStatefulLocal local = (SimpleStatefulLocal) new InitialContext().lookup(SimpleStatefulLocal.class.getName());
      local.reset();
      local.setState("hello");
      local.longRunning();
      if (!"hello".equals(local.getState())) throw new RuntimeException("failed state");
      if (!local.getPostActivate()) throw new RuntimeException("failed to postActivate");
      if (!local.getPrePassivate()) throw new RuntimeException("failed to prePassivate");

   }
}
