/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.hibernate.cache;

import net.sf.hibernate.cache.CacheProvider;
import net.sf.hibernate.cache.Cache;
import net.sf.hibernate.cache.CacheException;

import java.util.Properties;

import org.jboss.cache.TreeCache;
import org.jboss.logging.Logger;

import javax.naming.InitialContext;

/**
 * A Hibernate CacheProvider implementation which knows how to
 * obtain a deployed JBossCache accessible via JNDI to be
 * used as the backing store.
 *
 * @version <tt>$Revision: 1.2.2.2 $</tt>
 * @author <a href="mailto:steve@hibernate.org">Steve Ebersole</a>
 */
public class DeployedTreeCacheProvider
      implements CacheProvider
{
   public static final String NAMESPACE_PROP_NAME = "hibernate.treecache.jndiName";
   private static final Logger log = Logger.getLogger(DeployedTreeCacheProvider.class);

   private TreeCache deployedTreeCache;

   /**
    * Called by Hibernate in order to build the given named cache "region".
    *
    * @param name The cache "region" name.
    * @param properties The configuration properties.
    * @return The constructed Cache wrapper around the jndi-deployed TreeCache.
    * @throws CacheException Generally indicates a problem locating the TreeCache.
    */
   public Cache buildCache(String name, Properties properties) throws CacheException
   {
      return new DeployedTreeCache( name, getOrLookupDeployedTreeCache(properties) );
   }

   public long nextTimestamp()
   {
		return System.currentTimeMillis() / 100;
   }

   private TreeCache getOrLookupDeployedTreeCache(Properties properties) throws CacheException
   {
      try
      {
			synchronized (TreeCache.class)
         {
				if (deployedTreeCache==null)
            {
               String jndiName = properties.getProperty(NAMESPACE_PROP_NAME);
               if ( jndiName == null || "".equals(jndiName) )
               {
                  throw new CacheException("Must specify jndi location of deployed TreeCache");
               }
               log.debug("TreeCache not previously looked up; obtaining from [" + jndiName + "]");
               deployedTreeCache = lookupDeployedTreeCache(jndiName);
            }
         }
      }
      catch( CacheException e)
      {
         throw e;
      }
		catch (Exception e)
      {
			throw new CacheException(e);
		}

      return deployedTreeCache;
   }

   private TreeCache lookupDeployedTreeCache(String jndiName) throws Exception
   {
      InitialContext ctx = null;
      try
      {
         ctx = new InitialContext();
         return (TreeCache) ctx.lookup(jndiName);
      }
      catch(Exception e)
      {
         log.warn("Unable to locate TreeCache at specified namespace [" + jndiName + "]", e);
         throw e;
      }
      finally
      {
         if (ctx == null)
         {
            try
            {
               ctx.close();
            }
            catch(Exception ignore)
            {
               // ignore...
            }
         }
      }
   }
}
