2 * Copyright 2005 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.wamblee.cache;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.Serializable;
23 import net.sf.ehcache.Cache;
24 import net.sf.ehcache.CacheException;
25 import net.sf.ehcache.CacheManager;
26 import net.sf.ehcache.Element;
28 import org.apache.log4j.Logger;
29 import org.wamblee.io.InputResource;
32 * Cache implemented on top of EhCache.
34 public class EhCache<KeyType extends Serializable, ValueType extends Serializable>
35 implements org.wamblee.cache.Cache<KeyType, ValueType> {
37 private static final Logger LOGGER = Logger.getLogger(EhCache.class);
42 private CacheManager _manager;
50 * Constructs a cache based on EHCache.
51 * @param aResource Resource containing the configuration file for
53 * @param aCacheName Name of the cache to use. If a cache with this name does
54 * not exist, one is created based on default settings.
56 * @throws CacheException
58 public EhCache(InputResource aResource, String aCacheName)
59 throws IOException, CacheException {
60 InputStream is = aResource.getInputStream();
62 _manager = CacheManager.create();
63 _cache = _manager.getCache(aCacheName);
65 LOGGER.warn("Creating cache '" + aCacheName + "' because it is not configured");;
66 _manager.addCache(aCacheName);
67 _cache = _manager.getCache(aCacheName);
69 assert _cache != null;
79 * @see org.wamblee.cache.Cache#put(KeyType, ValueType)
81 public void put(KeyType aKey, ValueType aValue) {
82 _cache.put(new Element(aKey, aValue));
88 * @see org.wamblee.cache.Cache#get(KeyType)
90 public ValueType get(KeyType aKey) {
92 Element element = _cache.get(aKey);
93 if ( element == null ) {
96 return (ValueType)element.getValue();
97 } catch (CacheException e) {
98 throw new RuntimeException("Cache problem key = '" + aKey + "'", e);
105 * @see org.wamblee.cache.Cache#remove(KeyType)
107 public void remove(KeyType aKey) {
114 * @see org.wamblee.cache.Cache#clear()
116 public void clear() {
119 } catch (IOException e) {
120 throw new RuntimeException("Problem removing items from cache", e);