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;
27 import net.sf.ehcache.config.Configuration;
28 import net.sf.ehcache.config.ConfigurationFactory;
30 import org.apache.log4j.Logger;
31 import org.wamblee.io.InputResource;
34 * Cache implemented on top of EhCache.
36 * @author Erik Brakkee
38 public class EhCache<KeyType extends Serializable, ValueType extends Serializable>
39 implements org.wamblee.cache.Cache<KeyType, ValueType> {
41 private static final Logger LOGGER = Logger.getLogger(EhCache.class);
46 private CacheManager _manager;
54 * Constructs a cache based on EHCache.
57 * Resource containing the configuration file for EHCache.
59 * Name of the cache to use. If a cache with this name does not
60 * exist, one is created based on default settings.
62 * @throws CacheException
64 public EhCache(InputResource aResource, String aCacheName)
65 throws IOException, CacheException {
66 InputStream is = aResource.getInputStream();
68 _manager = new CacheManager(is);
69 _cache = _manager.getCache(aCacheName);
71 LOGGER.warn("Creating cache '" + aCacheName
72 + "' because it is not configured");
73 _manager.addCache(aCacheName);
74 _cache = _manager.getCache(aCacheName);
76 assert _cache != null;
86 * @see org.wamblee.cache.Cache#put(KeyType, ValueType)
88 public void put(KeyType aKey, ValueType aValue) {
89 _cache.put(new Element(aKey, aValue));
95 * @see org.wamblee.cache.Cache#get(KeyType)
97 public ValueType get(KeyType aKey) {
99 Element element = _cache.get(aKey);
100 if (element == null) {
103 return (ValueType) element.getValue();
104 } catch (CacheException e) {
105 throw new RuntimeException("Cache problem key = '" + aKey + "'", e);
112 * @see org.wamblee.cache.Cache#remove(KeyType)
114 public void remove(KeyType aKey) {
121 * @see org.wamblee.cache.Cache#clear()
123 public void clear() {