KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jofti > cache > adapter > EhCacheAdapter


1 package com.jofti.cache.adapter;
2
3 import java.io.IOException JavaDoc;
4 import java.io.Serializable JavaDoc;
5 import java.util.Iterator JavaDoc;
6 import java.util.List JavaDoc;
7 import java.util.Map JavaDoc;
8 import java.util.Properties JavaDoc;
9
10 import net.sf.ehcache.Cache;
11 import net.sf.ehcache.CacheException;
12 import net.sf.ehcache.CacheManager;
13 import net.sf.ehcache.Element;
14
15 import org.apache.commons.logging.Log;
16 import org.apache.commons.logging.LogFactory;
17
18 import com.jofti.api.IndexQuery;
19 import com.jofti.cache.CacheAdapter;
20 import com.jofti.cache.BaseAdaptor;
21 import com.jofti.cache.adapter.listener.EhEventListener;
22 import com.jofti.core.INameSpaceAware;
23 import com.jofti.core.IParsedQuery;
24 import com.jofti.core.InternalIndex;
25 import com.jofti.core.QueryId;
26 import com.jofti.core.QueryType;
27 import com.jofti.exception.JoftiException;
28 import com.jofti.util.CompositeComparator;
29
30 /**
31
32  *
33  * The adapter implementation specific to EHCache.</p>
34  *
35  * The adapter takes care of the implementation specific details for converting
36  * between the process the index expects and the behaviour of EHCache. This adapter is for versions
37  * of EHCache 1.2 and upwards. For earlier versions you <b>must</b> use the EhCachePre1_2Adapter.</p>
38  *
39  *
40  * The start up of the adapter will also try and index any elements already in
41  * the cache.<P>
42  *
43  * @author Steve Woodcock
44  * <p>
45  * @version 1.0
46  * @since 1.1
47  */

48 public class EhCacheAdapter extends BaseAdaptor implements CacheAdapter
49 {
50
51     private net.sf.ehcache.CacheManager manager;
52
53     private static Log log = LogFactory
54                                                     .getLog(EhCacheAdapter.class);
55
56     private net.sf.ehcache.Cache cache;
57
58     private String JavaDoc name;
59
60     
61     private EhEventListener eventListener =null;
62
63     public EhCacheAdapter()
64     {
65     }
66
67     public EhCacheAdapter(Object JavaDoc cache)
68     {
69         this.cache = (net.sf.ehcache.Cache) cache;
70
71     }
72
73     public void setCacheImpl(Object JavaDoc cache)
74     {
75         this.cache = (net.sf.ehcache.Cache) cache;
76
77     }
78
79     /*
80      * (non-Javadoc)
81      *
82      * @see com.jofti.api.IndexCache#get(java.lang.Object)
83      */

84     public Object JavaDoc get(Object JavaDoc key)
85     {
86     
87         try {
88             if (key != null) {
89                 // do the cast early - seems to help the performance slightly -
90
// otherwise
91
// we have multiple casts in this method
92
Comparable JavaDoc tempKey = (Comparable JavaDoc) key;
93                 // get a lock for the key that we are trying to add
94
// we do not care about other parts of the cache or the index
95
synchronized (getCacheLock(key)) {
96
97                     // get the element from the cache if it exists
98
Element element = cache.get((Serializable JavaDoc) tempKey);
99                     // if it is null either it has expired or it was never there
100
if (element == null) {
101                         return null;
102                     } else {
103                         // we should not need to do this as there should be no
104
// way an entry can just appear without going through
105
// this classe
106

107                         return element.getValue();
108                     }
109                 }
110
111             } else {
112                 return null;
113             }
114         } catch (net.sf.ehcache.CacheException e) {
115             log.warn("Unable to retrieve value from cache", e);
116  
117         }
118         return null;
119     }
120
121     /*
122      * (non-Javadoc)
123      *
124      * @see com.jofti.api.IndexCache#put(java.lang.Object, java.lang.Object)
125      */

126     public void put(Object JavaDoc key, Object JavaDoc value) throws JoftiException
127     {
128         
129         try{
130             synchronized (getCacheLock(key)) {
131
132                 // we have to remove a potentially expired result
133

134                 Element element = new Element((Serializable JavaDoc) key,
135                         (Serializable JavaDoc) value);
136                 cache.put(element);
137
138             }
139         } catch (IllegalArgumentException JavaDoc e) {
140             throw new JoftiException(e);
141         } catch (IllegalStateException JavaDoc e) {
142             throw new JoftiException(e);
143         }
144
145     }
146
147     /**
148      * Removes the element which matches the key.
149      * <p>
150      * If no element matches, nothing is removed and no Exception is thrown.
151      *
152      * @param key
153      * the key of the element to remove
154      * @throws CacheException
155      */

156     public void remove(Object JavaDoc key) throws JoftiException
157     {
158     
159
160         try {
161
162             synchronized (getCacheLock(key)) {
163                 // remove if we need to based on the key - as it may be expired
164

165
166                 cache.remove((Serializable JavaDoc) key);
167             }
168
169         } catch (ClassCastException JavaDoc e) {
170             throw new JoftiException(e);
171         } catch (IllegalStateException JavaDoc e) {
172             throw new JoftiException(e);
173         }
174     }
175
176     /**
177      * Remove all elements in the cache, but leave the cache in a useable state.
178      *
179      * @throws CacheException
180      */

181     public synchronized void removeAll() throws JoftiException
182     {
183         try {
184
185             cache.removeAll();
186             index.removeAll();
187
188         } catch (IllegalStateException JavaDoc e) {
189             throw new JoftiException(e);
190         } catch (Exception JavaDoc e) {
191             throw new JoftiException(e);
192         }
193     }
194
195     /* (non-Javadoc)
196      * @see com.jofti.cache.LifeCycleAdapter#init(java.util.Properties)
197      */

198     public synchronized void init(Properties JavaDoc properties) throws JoftiException
199     {
200         try {
201             String JavaDoc cacheConfigFile = null;
202             if (properties != null) {
203                 String JavaDoc key = null;
204                 for (Iterator JavaDoc it = properties.keySet().iterator(); it.hasNext();) {
205                     key = (String JavaDoc) it.next();
206                     if (MUTABLE_VALUES.equalsIgnoreCase(key)) {
207                         checkMutable = Boolean.valueOf(
208                                 properties.getProperty(key)).booleanValue();
209                         if (log.isInfoEnabled()) {
210                             log.info("Mutability checking is set to "
211                                     + checkMutable);
212                         }
213                     }
214                     if ("file".equalsIgnoreCase(key)) {
215                         cacheConfigFile = properties.getProperty(key);
216                     }
217                 }
218             }
219             log.debug("looking up CacheManager for EHCache");
220                 if (manager == null) {
221                     log.debug("no CacheManager found obtaining one via static CacheManager methods");
222                     if (cacheConfigFile != null) {
223                         log.debug("obtaining CacheManager using config file "+ cacheConfigFile);
224                         manager = net.sf.ehcache.CacheManager
225                                 .create(cacheConfigFile);
226                     } else {
227                         log.debug("obtaining CacheManager using no config file ");
228                         manager = CacheManager.create();
229                     }
230                 }
231                 log.debug("finished looking up CacheManager for EHCache");
232          
233             if (cache == null) {
234                 log.debug("EHCache impl is null - initialising cache");
235                 initCache();
236             } else {
237                 // try and add it to the cache
238
log.debug("EHCache impl is not null - checking if exists in CacheManager");
239                 if (!(manager.cacheExists(cache.getName()))) {
240                     log
241                     .info("Cache "
242                             + cache.getName()
243                             + "does not exist in CacheManager - adding new cache");
244                     manager.addCache(cache);
245                 } else {
246                     log
247                             .info("Cache "
248                                     + cache.getName()
249                                     + "already exists in CacheManager - not adding new cache");
250                 }
251             }
252             eventListener = new EhEventListener(this);
253          } catch (net.sf.ehcache.CacheException e) {
254             throw new JoftiException(e);
255         }
256
257     }
258
259     private void initCache() throws JoftiException
260     {
261         if (cache == null) {
262             if (manager == null){
263                 throw new JoftiException("No Cache Manager specified unable to initialise cache "+name);
264             }
265             cache = manager.getCache(name);
266             if (cache == null) {
267                 log.warn("Unable to find cache named '" + name
268                         + "' in EHCacheManager");
269                 String JavaDoc[] names = manager.getCacheNames();
270                 log.warn("Available cache names are:");
271                 for (int i = 0; i < names.length; i++) {
272                     log.warn("IndexCache:" + names[i]);
273                 }
274                 throw new JoftiException("Unable to find cache named '" + name
275                         + "' in EHCacheManager");
276             }
277         }
278   
279     }
280
281     /* (non-Javadoc)
282      * @see com.jofti.cache.LifeCycleAdapter#start()
283      */

284     public synchronized void start() throws JoftiException
285     {
286         if (cache != null){
287             ((Cache)cache).getCacheEventNotificationService().registerListener(eventListener);
288             
289         }
290         try {
291             loadInitialValues(cache);
292         } catch (CacheException ce) {
293             throw new JoftiException(ce);
294         }
295     }
296
297     private void loadInitialValues(net.sf.ehcache.Cache cache)
298             throws CacheException, JoftiException
299     {
300         if (cache == null){
301             log.info("No initial values to load as Cache is null");
302             return;
303         }
304         List JavaDoc keys = cache.getKeys();
305         int size = keys.size();
306         Iterator JavaDoc it = keys.iterator();
307         for (int i=0;i<size;i++) {
308             Object JavaDoc key = it.next();
309             Element element = cache.get((Serializable JavaDoc) key);
310             if (key instanceof Comparable JavaDoc) {
311                 Comparable JavaDoc tempKey = (Comparable JavaDoc) key;
312                 if (element != null && element.getValue() != null) {
313                     // then we must remove from index
314
index.insert(tempKey, element.getValue());
315                 }
316             } else {
317                 log.info("Ignoring value at key:" + key
318                         + " as key is not Comparable");
319             }
320         }
321     }
322
323     /* (non-Javadoc)
324      * @see com.jofti.cache.LifeCycleAdapter#destroy()
325      */

326     public synchronized void destroy() throws JoftiException
327     {
328         try {
329             if (manager != null) {
330                 manager.removeCache(name);
331                 manager.shutdown();
332                 index.removeAll();
333             }
334         } catch (IllegalStateException JavaDoc e) {
335             throw new JoftiException(e);
336         }
337     }
338
339     /* (non-Javadoc)
340      * @see com.jofti.cache.LifeCycleAdapter#getName()
341      */

342     public String JavaDoc getName()
343     {
344         return name;
345     }
346
347     /* (non-Javadoc)
348      * @see com.jofti.cache.LifeCycleAdapter#setName(java.lang.String)
349      */

350     public void setName(String JavaDoc name)
351     {
352         this.name = name;
353     }
354
355     public String JavaDoc toString()
356     {
357         return "EHCache(" + getName() + ')';
358     }
359
360
361     /*
362      * (non-Javadoc)
363      *
364      * @see com.jofti.api.IndexCache#getCacheImpl()
365      */

366     public Object JavaDoc getCacheImpl()
367     {
368         return cache;
369     }
370
371     /*
372      * (non-Javadoc)
373      *
374      * @see com.jofticache.CacheAdapter#setInternalIndex(com.jofti.core.InternalIndex)
375      */

376     public void setInternalIndex(InternalIndex index)
377     {
378         this.index = index;
379
380     }
381
382   
383
384
385   /* (non-Javadoc)
386      * @see com.jofti.cache.CacheLocking#getCacheValue(java.lang.Object)
387      */

388     protected Object JavaDoc getCacheValue(Object JavaDoc key) {
389         try{
390             Element res= cache.get((Serializable JavaDoc)key);
391             if (res != null){
392                 return res.getValue();
393             }else{
394                 log.warn("No Cache value found for indexed key "+key);
395             }
396         } catch (Throwable JavaDoc e){
397             log.warn(e);
398         }
399         return null;
400     }
401
402     /* (non-Javadoc)
403      * @see com.jofti.cache.CacheLocking#getIndex()
404      */

405     public InternalIndex getIndex() {
406         return index;
407     }
408
409     /* (non-Javadoc)
410      * @see com.jofti.api.Index#addQuery(java.lang.String, com.jofti.api.IndexQuery)
411      */

412     public IndexQuery addQuery(String JavaDoc name, IndexQuery query)throws JoftiException {
413         
414         return index.getParserManager().addQuery(name, query);
415     }
416
417     /* (non-Javadoc)
418      * @see com.jofti.api.Index#getQuery(java.lang.String)
419      */

420     public IndexQuery getQuery(String JavaDoc name) {
421         
422         return index.getParserManager().getQuery(name);
423     }
424 }
Popular Tags