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 public class EhCache<KeyType extends Serializable, ValueType extends Serializable>
37 implements org.wamblee.cache.Cache<KeyType, ValueType> {
39 private static final Logger LOGGER = Logger.getLogger(EhCache.class);
44 private CacheManager _manager;
52 * Constructs a cache based on EHCache.
55 * Resource containing the configuration file for EHCache.
57 * Name of the cache to use. If a cache with this name does not
58 * exist, one is created based on default settings.
60 * @throws CacheException
62 public EhCache(InputResource aResource, String aCacheName)
63 throws IOException, CacheException {
64 InputStream is = aResource.getInputStream();
66 _manager = new CacheManager(is);
67 _cache = _manager.getCache(aCacheName);
69 LOGGER.warn("Creating cache '" + aCacheName
70 + "' because it is not configured");
71 _manager.addCache(aCacheName);
72 _cache = _manager.getCache(aCacheName);
74 assert _cache != null;
84 * @see org.wamblee.cache.Cache#put(KeyType, ValueType)
86 public void put(KeyType aKey, ValueType aValue) {
87 _cache.put(new Element(aKey, aValue));
93 * @see org.wamblee.cache.Cache#get(KeyType)
95 public ValueType get(KeyType aKey) {
97 Element element = _cache.get(aKey);
98 if (element == null) {
101 return (ValueType) element.getValue();
102 } catch (CacheException e) {
103 throw new RuntimeException("Cache problem key = '" + aKey + "'", e);
110 * @see org.wamblee.cache.Cache#remove(KeyType)
112 public void remove(KeyType aKey) {
119 * @see org.wamblee.cache.Cache#clear()
121 public void clear() {