Package org.shiftone.cache.adaptor

Source Code of org.shiftone.cache.adaptor.EHCacheCache

package org.shiftone.cache.adaptor;



import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.shiftone.cache.Cache;
import org.shiftone.cache.util.Log;

import java.io.Serializable;


/**
* Makes a ehcache cache look like a shiftone cache.
*
* @version $Revision: 1.6 $
* @author <a href="mailto:jeff@shiftone.org">Jeff Drost</a>
*/
public class EHCacheCache implements Cache
{

    private static final Log     LOG = new Log(EHCacheCache.class);
    private net.sf.ehcache.Cache cache;

    public EHCacheCache(String name) throws Exception
    {

        CacheManager cacheManager = CacheManager.getInstance();

        cache = cacheManager.getCache(name);

        if (cache == null)
        {
            cacheManager.addCache(name);

            cache = cacheManager.getCache(name);
        }
    }


    public EHCacheCache(net.sf.ehcache.Cache cache)
    {
        this.cache = cache;
    }


    private final Serializable ser(Object o)
    {

        Serializable serializable;

        try
        {
            serializable = (Serializable) o;
        }
        catch (ClassCastException e)
        {
            throw new ClassCastException("unable to cast " + o.getClass().getName() + " to Serializable");
        }

        return serializable;
    }


    public final void addObject(Object userKey, Object cacheObject)
    {

        Serializable k = ser(userKey);
        Serializable v = ser(cacheObject);

        cache.put(new Element(k, v));
    }


    public final Object getObject(Object key)
    {

        Element element = null;

        try
        {
            element = cache.get((Serializable) key);
        }
        catch (Exception e)
        {
            LOG.error("getObject", e);
        }

        return (element == null)
               ? null
               : element.getValue();
    }


    public final int size()
    {
        return cache.getSize();
    }


    public final void remove(Object key)
    {
        cache.remove((Serializable) key);
    }


    public final void clear()
    {

        try
        {
            cache.removeAll();
        }
        catch (Exception e)
        {
            LOG.error("clear", e);
        }
    }


    public String toString()
    {
        return "EHCacheCache[" + cache.getName() + ":" + cache.getMaxElementsInMemory() + "]";
    }
}
TOP

Related Classes of org.shiftone.cache.adaptor.EHCacheCache

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.