/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.fw.cache;

import org.springframework.transaction.support.TransactionSynchronizationManager;

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

/**
 * Implement generic methods to provide CRUD operations to a cached item in ThreadLocal.
 * 
 * <p>Note that this class uses ThreadLocal storage and assumes a constant implementation
 * of ThreadLocal in the Spring class TransactionSynchronizationManager.
 * 
 * Created Nov 3, 2005 12:25:34 PM
 * @author DNS   BOHMEG, DNS   LEV
 */
public class ThreadLocalCacheStrategy extends AbstractComponent implements CacheStrategy {
	
	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = -2377444842284916518L;

	/**
	 * A default constructor
	 */
	public ThreadLocalCacheStrategy() {
		super();
	}

	/**
	 * @see gov.va.med.fw.cache.CacheStrategy#getItem(java.lang.Object)
	 */
	public Object getItem(Object key) {
		
		if( this.logger.isDebugEnabled() ) {
			this.logger.debug( "Retrieving a cached item keyed by " + key );
		}
		return TransactionSynchronizationManager.getResource(key);
	}

	/**
	 * @see gov.va.med.fw.cache.CacheStrategy#removeItem(java.lang.Object)
	 */
	public synchronized Object removeItem(Object key) {
		
		Object removed = null;
		if(containsItem(key)) {
			if( this.logger.isDebugEnabled() ) {
				this.logger.debug( "Removing a cached item keyed by " + key );
			}
			removed = TransactionSynchronizationManager.unbindResource(key);
		}
		return removed;
	}
	
	/**
	 * @see gov.va.med.fw.cache.CacheStrategy#cacheItem(java.lang.Object, java.lang.Object)
	 */
	public void cacheItem(Object key, Object value) {
		if( this.logger.isDebugEnabled() ) {
			this.logger.debug( "Storing a cached item " + value + " keyed by " + key );
		}
		TransactionSynchronizationManager.bindResource(key, value);
	}
	
	/**
	 * @see gov.va.med.fw.cache.CacheStrategy#containsItem(java.lang.Object)
	 */
	public boolean containsItem(Object key) {
		if( this.logger.isDebugEnabled() ) {
			this.logger.debug( "Checking a cache for item keyed by " + key );
		}
		return TransactionSynchronizationManager.hasResource(key);
	}
}