/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/

package gov.va.med.fw.cache;

// Libraries 
import org.apache.commons.lang.Validate;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

// Framework
import gov.va.med.fw.service.AbstractComponent;

/**
 * A concrete cache strategy that uses EHCache to cache an item
 * @author DNS   LEV
 *
 */
public class EHCacheStrategy extends AbstractComponent implements CacheStrategy {

	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = -8313273199973981560L;

	/**
	 * An instance of cache
	 */
	private Cache cache = null;
	
	/**
	 * A default constructor
	 */
	public EHCacheStrategy() {
		super();
	}

	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
		Validate.notNull( this.cache, "A cache must be configured" );
	}

	public void setCache(Cache cache) {
		this.cache = cache;
	}

	/**
	 * @see gov.va.med.fw.cache.CacheStrategy#getItem(java.lang.Object)
	 */
	public Object getItem(Object key) {
		Validate.notNull( key, "A key to look up a cache item must not be null" );
		Element item = this.cache.get( key );
		return item != null ? item.getObjectValue() : null;
	}

	/**
	 * @see gov.va.med.fw.cache.CacheStrategy#removeItem(java.lang.Object)
	 */
	public Object removeItem(Object key) {
		Validate.notNull( key, "A key to look up a cache item must not be null" );

		Object value = null;
		Element item = this.cache.get( key );
		if( item != null ) {
			value = item.getObjectKey();
			this.cache.remove( item.getKey() );
		}
		return value;
	}

	/**
	 * @see gov.va.med.fw.cache.CacheStrategy#cacheItem(java.lang.Object, java.lang.Object)
	 */
	public void cacheItem(Object key, Object value) {
		this.cache.put( new Element( key, value ) );
	}

	/**
	 * @see gov.va.med.fw.cache.CacheStrategy#containsItem(java.lang.Object)
	 */
	public boolean containsItem(Object key) {
		return (this.cache.get( key ) != null);
	}
}