package org.jboss.cache.passivation;

import org.jboss.cache.config.CacheLoaderConfig;
import org.jboss.cache.factories.XmlConfigurationParser;
import org.jboss.cache.xml.XmlHelper;
import org.testng.annotations.Test;
import org.w3c.dom.Element;

import java.io.File;
import java.io.FileFilter;

/**
 * Runs the same tests as {@link PassivationToFileCacheLoaderTest}, but with
 * Berkeley DB instead of a file-based CacheLoader
 *
 * @author <a href="mailto:{hmesha@novell.com}">{Hany Mesha}</a>
 * @version $Id: PassivationToBdbjeCacheLoaderTest.java 4915 2007-12-21 17:11:56Z manik.surtani@jboss.com $
 */
@Test(groups = "functional")
public class PassivationToBdbjeCacheLoaderTest extends PassivationTestsBase
{
   private String tmp_location = System.getProperty("java.io.tmpdir", "c:\\tmp");
   private File dir = new File(tmp_location);

   public PassivationToBdbjeCacheLoaderTest()
   {
      if (!dir.exists()) dir.mkdirs();
   }

   protected void configureCache() throws Exception
   {

      class MyFilter implements FileFilter
      {
         public boolean accept(File file)
         {
            return file.getName().endsWith(".jdb");
         }
      }

      File[] files = dir.listFiles(new MyFilter());
      if (files != null)
      {
         for (int i = 0; i < files.length; i += 1)
         {
            File file = files[i];
            if (file.isFile())
            {
               if (!file.delete())
               {
                  System.err.println("Unable to delete: " + file);
               }
            }
         }
      }

      cache.getConfiguration().setCacheLoaderConfig(getCacheLoaderConfig(tmp_location));
   }


   protected CacheLoaderConfig getCacheLoaderConfig(String loc) throws Exception
   {
      String xml = "            <config>\n" +
            "                \n" +
            "                <passivation>true</passivation>\n" +
            "                <preload></preload>\n" +
            "\n" +
            "                <cacheloader>\n" +
            "                    <class>org.jboss.cache.loader.bdbje.BdbjeCacheLoader</class>\n" +
            "                    <properties>\n" +
            "                    </properties>\n" +
            "                    <async>false</async>\n" +
            "                    <fetchPersistentState>false</fetchPersistentState>\n" +
            "                    <ignoreModifications>false</ignoreModifications>\n" +
            "                </cacheloader>\n" +
            "                \n" +
            "            </config>";
      Element element = XmlHelper.stringToElement(xml);
      return XmlConfigurationParser.parseCacheLoaderConfig(element);
   }
}
