01: package org.shiftone.cache.adaptor;
02:
03: import net.sf.ehcache.CacheManager;
04: import net.sf.ehcache.Element;
05: import org.shiftone.cache.Cache;
06: import org.shiftone.cache.util.Log;
07:
08: import java.io.Serializable;
09:
10: /**
11: * Makes a ehcache cache look like a shiftone cache.
12: *
13: * @version $Revision: 1.6 $
14: * @author <a href="mailto:jeff@shiftone.org">Jeff Drost</a>
15: */
16: public class EHCacheCache implements Cache {
17:
18: private static final Log LOG = new Log(EHCacheCache.class);
19: private net.sf.ehcache.Cache cache;
20:
21: public EHCacheCache(String name) throws Exception {
22:
23: CacheManager cacheManager = CacheManager.getInstance();
24:
25: cache = cacheManager.getCache(name);
26:
27: if (cache == null) {
28: cacheManager.addCache(name);
29:
30: cache = cacheManager.getCache(name);
31: }
32: }
33:
34: public EHCacheCache(net.sf.ehcache.Cache cache) {
35: this .cache = cache;
36: }
37:
38: private final Serializable ser(Object o) {
39:
40: Serializable serializable;
41:
42: try {
43: serializable = (Serializable) o;
44: } catch (ClassCastException e) {
45: throw new ClassCastException("unable to cast "
46: + o.getClass().getName() + " to Serializable");
47: }
48:
49: return serializable;
50: }
51:
52: public final void addObject(Object userKey, Object cacheObject) {
53:
54: Serializable k = ser(userKey);
55: Serializable v = ser(cacheObject);
56:
57: cache.put(new Element(k, v));
58: }
59:
60: public final Object getObject(Object key) {
61:
62: Element element = null;
63:
64: try {
65: element = cache.get((Serializable) key);
66: } catch (Exception e) {
67: LOG.error("getObject", e);
68: }
69:
70: return (element == null) ? null : element.getValue();
71: }
72:
73: public final int size() {
74: return cache.getSize();
75: }
76:
77: public final void remove(Object key) {
78: cache.remove((Serializable) key);
79: }
80:
81: public final void clear() {
82:
83: try {
84: cache.removeAll();
85: } catch (Exception e) {
86: LOG.error("clear", e);
87: }
88: }
89:
90: public String toString() {
91: return "EHCacheCache[" + cache.getName() + ":"
92: + cache.getMaxElementsInMemory() + "]";
93: }
94: }
|