package org.apache.slide.util;

import java.net.URL;

import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;

/**
 * A factory for obtaining ehcache CacheManagers. This simplifies the process
 * of obtaining a CacheManager.
 *
 */
public class CacheManagerFactory {
	
	private static CacheManager defaultCacheManager;
	private static HashMap cacheManagers = new HashMap();

	private CacheManagerFactory() {}
	
	/**
	 * Retrieves the default CacheManager using the default configuration file.
	 * 
	 * @return the default CacheManager.
	 * @throws CacheException
	 */
	public static CacheManager getDefaultCacheManager() throws CacheException {
		if ( defaultCacheManager == null ) {
			defaultCacheManager = CacheManager.create();
		}
		return defaultCacheManager;
	}
	
	/**
	 * Creates a CacheManager using the configuration file at configFilePath, then adds
	 * the CacheManager to an internal Map. Subsequent requests for a CacheManager with
	 * the same configFilePath returns the CacheManager from the Map.
	 * 
	 * @param configFilePath path to the configuration file to use.
	 * @return a CacheManager
	 * @throws CacheException
	 */
	public static CacheManager getCacheManager( String configFilePath ) throws CacheException {
		CacheManager cm = (CacheManager)cacheManagers.get( configFilePath );
		if ( cm == null ) {
			cm = CacheManager.create( configFilePath );
		}
		return cm;
	}
	
	/**
	 * Creates a CacheManager using the configuration file at configFileURL, then adds
	 * the CacheManager to an internal Map. Subsequent requests for a CacheManager with
	 * the same configFileURL returns the CacheManager from the Map.
	 * 
	 * @param configFileURL URL to the configuration file to use.
	 * @return a CacheManager
	 * @throws CacheException
	 */
	public static CacheManager getCacheManager( URL configFileURL ) throws CacheException {
		CacheManager cm = (CacheManager)cacheManagers.get( configFileURL );
		if ( cm == null ) {
			cm = CacheManager.create( configFileURL );
		}
		return cm;
	}

}
