2 * Copyright 2005-2010 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.
16 package org.wamblee.cache;
18 import net.sf.ehcache.Cache;
19 import net.sf.ehcache.CacheException;
20 import net.sf.ehcache.CacheManager;
21 import net.sf.ehcache.Element;
23 import org.wamblee.io.InputResource;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.Serializable;
28 import java.util.logging.Logger;
31 * Cache implemented on top of EhCache.
33 * @author Erik Brakkee
36 public class EhCache<KeyType extends Serializable, ValueType extends Serializable>
37 implements org.wamblee.cache.Cache<KeyType, ValueType> {
38 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();
67 manager = new CacheManager(is);
68 cache = manager.getCache(aCacheName);
71 LOGGER.warning("Creating cache '" + aCacheName +
72 "' because it is not configured");
73 manager.addCache(aCacheName);
74 cache = manager.getCache(aCacheName);
85 * @see org.wamblee.cache.Cache#put(KeyType, ValueType)
87 public void put(KeyType aKey, ValueType aValue) {
88 cache.put(new Element(aKey, aValue));
94 * @see org.wamblee.cache.Cache#get(KeyType)
96 public ValueType get(KeyType aKey) {
98 Element element = cache.get(aKey);
100 if (element == null) {
104 return (ValueType) element.getValue();
105 } catch (CacheException e) {
106 throw new RuntimeException("Cache problem key = '" + aKey + "'", e);
113 * @see org.wamblee.cache.Cache#remove(KeyType)
115 public void remove(KeyType aKey) {
122 * @see org.wamblee.cache.Cache#clear()
124 public void clear() {