KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > cache > EhCache


1 //$Id: EhCache.java,v 1.10 2005/04/21 07:57:19 oneovthafew Exp $
2
/* ====================================================================
3  * The Apache Software License, Version 1.1
4  *
5  * Copyright (c) 2003 - 2004 Greg Luck. All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if
20  * any, must include the following acknowlegement:
21  * "This product includes software developed by Greg Luck
22  * (http://sourceforge.net/users/gregluck) and contributors.
23  * See http://sourceforge.net/project/memberlist.php?group_id=93232
24  * for a list of contributors"
25  * Alternately, this acknowledgement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "EHCache" must not be used to endorse or promote products
29  * derived from this software without prior written permission. For written
30  * permission, please contact Greg Luck (gregluck at users.sourceforge.net).
31  *
32  * 5. Products derived from this software may not be called "EHCache"
33  * nor may "EHCache" appear in their names without prior written
34  * permission of Greg Luck.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL GREG LUCK OR OTHER
40  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by contributors
51  * individuals on behalf of the EHCache project. For more
52  * information on EHCache, please see <http://ehcache.sourceforge.net/>.
53  *
54  */

55 package org.hibernate.cache;
56
57 import java.io.IOException JavaDoc;
58 import java.io.Serializable JavaDoc;
59 import java.util.HashMap JavaDoc;
60 import java.util.Iterator JavaDoc;
61 import java.util.Map JavaDoc;
62
63 import net.sf.ehcache.CacheManager;
64 import net.sf.ehcache.Element;
65
66 import org.apache.commons.logging.Log;
67 import org.apache.commons.logging.LogFactory;
68
69 /**
70  * EHCache plugin for Hibernate
71  *
72  * EHCache uses a {@link net.sf.ehcache.store.MemoryStore} and a
73  * {@link net.sf.ehcache.store.DiskStore}. The {@link net.sf.ehcache.store.DiskStore}
74  * requires that both keys and values be {@link Serializable}. For this reason
75  * this plugin throws Exceptions when either of these are not castable to {@link Serializable}.
76  *
77  * @version Taken from EhCache 0.9
78  * @author Greg Luck
79  * @author Emmanuel Bernard
80  */

81 public class EhCache implements Cache {
82     private static final Log log = LogFactory.getLog(EhCache.class);
83
84     private net.sf.ehcache.Cache cache;
85
86     /**
87      * Creates a new Hibernate pluggable cache based on a cache name.
88      * <p>
89      * @param cache The underlying EhCache instance to use.
90      */

91     public EhCache(net.sf.ehcache.Cache cache) {
92         this.cache = cache;
93     }
94
95     /**
96      * Gets a value of an element which matches the given key.
97      * @param key the key of the element to return.
98      * @return The value placed into the cache with an earlier put, or null if not found or expired
99      * @throws CacheException
100      */

101     public Object JavaDoc get(Object JavaDoc key) throws CacheException {
102         try {
103             if ( log.isDebugEnabled() ) {
104                 log.debug("key: " + key);
105             }
106             if (key == null) {
107                 return null;
108             }
109             else {
110                 Element element = cache.get( (Serializable JavaDoc) key );
111                 if (element == null) {
112                     if ( log.isDebugEnabled() ) {
113                         log.debug("Element for " + key + " is null");
114                     }
115                     return null;
116                 }
117                 else {
118                     return element.getValue();
119                 }
120             }
121         }
122         catch (net.sf.ehcache.CacheException e) {
123             throw new CacheException(e);
124         }
125     }
126     
127     public Object JavaDoc read(Object JavaDoc key) throws CacheException {
128         return get(key);
129     }
130
131
132     /**
133      * Puts an object into the cache.
134      * @param key a {@link Serializable} key
135      * @param value a {@link Serializable} value
136      * @throws CacheException if the parameters are not {@link Serializable}, the {@link CacheManager}
137      * is shutdown or another {@link Exception} occurs.
138      */

139     public void update(Object JavaDoc key, Object JavaDoc value) throws CacheException {
140         put(key, value);
141     }
142     
143     /**
144      * Puts an object into the cache.
145      * @param key a {@link Serializable} key
146      * @param value a {@link Serializable} value
147      * @throws CacheException if the parameters are not {@link Serializable}, the {@link CacheManager}
148      * is shutdown or another {@link Exception} occurs.
149      */

150     public void put(Object JavaDoc key, Object JavaDoc value) throws CacheException {
151         try {
152             Element element = new Element( (Serializable JavaDoc) key, (Serializable JavaDoc) value );
153             cache.put(element);
154         }
155         catch (IllegalArgumentException JavaDoc e) {
156             throw new CacheException(e);
157         }
158         catch (IllegalStateException JavaDoc e) {
159             throw new CacheException(e);
160         }
161
162     }
163
164     /**
165      * Removes the element which matches the key.
166      * <p>
167      * If no element matches, nothing is removed and no Exception is thrown.
168      * @param key the key of the element to remove
169      * @throws CacheException
170      */

171     public void remove(Object JavaDoc key) throws CacheException {
172         try {
173             cache.remove( (Serializable JavaDoc) key );
174         }
175         catch (ClassCastException JavaDoc e) {
176             throw new CacheException(e);
177         }
178         catch (IllegalStateException JavaDoc e) {
179             throw new CacheException(e);
180         }
181     }
182
183     /**
184      * Remove all elements in the cache, but leave the cache
185      * in a useable state.
186      * @throws CacheException
187      */

188     public void clear() throws CacheException {
189         try {
190             cache.removeAll();
191         }
192         catch (IllegalStateException JavaDoc e) {
193             throw new CacheException(e);
194         }
195         catch (IOException JavaDoc e) {
196             throw new CacheException(e);
197         }
198     }
199
200     /**
201      * Remove the cache and make it unuseable.
202      * @throws CacheException
203      */

204     public void destroy() throws CacheException {
205         try {
206             CacheManager.getInstance().removeCache( cache.getName() );
207         }
208         catch (IllegalStateException JavaDoc e) {
209             throw new CacheException(e);
210         }
211         catch (net.sf.ehcache.CacheException e) {
212             throw new CacheException(e);
213         }
214     }
215
216     /**
217      * Calls to this method should perform there own synchronization.
218      * It is provided for distributed caches. Because EHCache is not distributed
219      * this method does nothing.
220      */

221     public void lock(Object JavaDoc key) throws CacheException {
222     }
223
224     /**
225      * Calls to this method should perform there own synchronization.
226      * It is provided for distributed caches. Because EHCache is not distributed
227      * this method does nothing.
228      */

229     public void unlock(Object JavaDoc key) throws CacheException {
230     }
231
232     /**
233      * Gets the next timestamp;
234      */

235     public long nextTimestamp() {
236         return Timestamper.next();
237     }
238
239     /**
240      * Returns the lock timeout for this cache.
241      */

242     public int getTimeout() {
243         // 60 second lock timeout
244
return Timestamper.ONE_MS * 60000;
245     }
246
247     public String JavaDoc getRegionName() {
248         return cache.getName();
249     }
250
251     public long getSizeInMemory() {
252         try {
253             return cache.calculateInMemorySize();
254         }
255         catch(Throwable JavaDoc t) {
256             return -1;
257         }
258     }
259
260     public long getElementCountInMemory() {
261         try {
262             return cache.getSize();
263         }
264         catch (net.sf.ehcache.CacheException ce) {
265             throw new CacheException(ce);
266         }
267     }
268
269     public long getElementCountOnDisk() {
270         return cache.getDiskStoreSize();
271     }
272
273     public Map JavaDoc toMap() {
274         try {
275             Map JavaDoc result = new HashMap JavaDoc();
276             Iterator JavaDoc iter = cache.getKeys().iterator();
277             while ( iter.hasNext() ) {
278                 Object JavaDoc key = iter.next();
279                 result.put( key, cache.get( (Serializable JavaDoc) key ).getValue() );
280             }
281             return result;
282         }
283         catch (Exception JavaDoc e) {
284             throw new CacheException(e);
285         }
286     }
287
288     public String JavaDoc toString() {
289         return "EHCache(" + getRegionName() + ')';
290     }
291
292 }
Popular Tags