1 /**
2 * Copyright 2003-2007 Greg Luck
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16 package net.sf.ehcache.hibernate;
17
18 import net.sf.ehcache.CacheManager;
19 import net.sf.ehcache.util.ClassLoaderUtil;
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.hibernate.cache.Cache;
23 import org.hibernate.cache.CacheException;
24 import org.hibernate.cache.CacheProvider;
25 import org.hibernate.cache.Timestamper;
26
27 import java.net.URL;
28 import java.util.Properties;
29
30 /**
31 * Cache Provider plugin for Hibernate 3.2 and ehcache-1.2. New in this provider are ehcache support for multiple
32 * Hibernate session factories, each with its own ehcache configuration, and non Serializable keys and values.
33 * Ehcache-1.2 also has many other features such as cluster support and listeners, which can be used seamlessly simply
34 * by configurion in ehcache.xml.
35 * <p/>
36 * Use <code>hibernate.cache.provider_class=net.sf.ehcache.hibernate.EhCacheProvider</code> in the Hibernate configuration
37 * to enable this provider for Hibernate's second level cache.
38 * <p/>
39 * When configuring multiple ehcache CacheManagers, as you would where you have multiple Hibernate Configurations and
40 * multiple SessionFactories, specify in each Hibernate configuration the ehcache configuration using
41 * the property <code>net.sf.ehcache.configurationResourceName</code> An example to set an ehcach configuration
42 * called ehcache-2.xml would be <code>net.sf.ehcache.configurationResourceName=/ehcache-2.xml</code>. If the leading
43 * slash is not there one will be added. The configuration file will be looked for in the root of the classpath.
44 * <p/>
45 * Updated for ehcache-1.2. Note this provider requires ehcache-1.2.jar. Make sure ehcache-1.1.jar or earlier
46 * is not in the classpath or it will not work.
47 * <p/>
48 * See http://ehcache.sf.net for documentation on ehcache
49 * <p/>
50 *
51 * @author Greg Luck
52 * @author Emmanuel Bernard
53 * @version $Id: EhCacheProvider.java 512 2007-07-10 09:18:45Z gregluck $
54 */
55 public final class EhCacheProvider implements CacheProvider {
56
57 /**
58 * The Hibernate system property specifying the location of the ehcache configuration file name.
59 * <p/
60 * If not set, ehcache.xml will be looked for in the root of the classpath.
61 * <p/>
62 * If set to say ehcache-1.xml, ehcache-1.xml will be looked for in the root of the classpath.
63 */
64 public static final String NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME = "net.sf.ehcache.configurationResourceName";
65
66 private static final Log LOG = LogFactory.getLog(EhCacheProvider.class);
67
68 private CacheManager manager;
69
70
71 /**
72 * Builds a Cache.
73 * <p/>
74 * Even though this method provides properties, they are not used.
75 * Properties for EHCache are specified in the ehcache.xml file.
76 * Configuration will be read from ehcache.xml for a cache declaration
77 * where the name attribute matches the name parameter in this builder.
78 *
79 * @param name the name of the cache. Must match a cache configured in ehcache.xml
80 * @param properties not used
81 * @return a newly built cache will be built and initialised
82 * @throws org.hibernate.cache.CacheException
83 * inter alia, if a cache of the same name already exists
84 */
85 public final Cache buildCache(String name, Properties properties) throws CacheException {
86 try {
87 net.sf.ehcache.Ehcache cache = manager.getEhcache(name);
88 if (cache == null) {
89 LOG.warn("Could not find a specific ehcache configuration for cache named [" + name + "]; using defaults.");
90 manager.addCache(name);
91 cache = manager.getEhcache(name);
92 EhCacheProvider.LOG.debug("started EHCache region: " + name);
93 }
94 return new net.sf.ehcache.hibernate.EhCache(cache);
95 } catch (net.sf.ehcache.CacheException e) {
96 throw new CacheException(e);
97 }
98 }
99
100 /**
101 * Returns the next timestamp.
102 */
103 public final long nextTimestamp() {
104 return Timestamper.next();
105 }
106
107 /**
108 * Callback to perform any necessary initialization of the underlying cache implementation
109 * during SessionFactory construction.
110 * <p/>
111 *
112 * @param properties current configuration settings.
113 */
114 public final void start(Properties properties) throws CacheException {
115 if (manager != null) {
116 LOG.warn("Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() " +
117 " between repeated calls to buildSessionFactory. Using previously created EhCacheProvider." +
118 " If this behaviour is required, consider using SingletonEhCacheProvider.");
119 return;
120 }
121 try {
122 String configurationResourceName = null;
123 if (properties != null) {
124 configurationResourceName = (String) properties.get(NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME);
125 }
126 if (configurationResourceName == null || configurationResourceName.length() == 0) {
127 manager = new CacheManager();
128 } else {
129 if (!configurationResourceName.startsWith("/")) {
130 configurationResourceName = "/" + configurationResourceName;
131 if (LOG.isDebugEnabled()) {
132 LOG.debug("prepending / to " + configurationResourceName + ". It should be placed in the root"
133 + "of the classpath rather than in a package.");
134 }
135 }
136 URL url = loadResource(configurationResourceName);
137 manager = new CacheManager(url);
138 }
139 } catch (net.sf.ehcache.CacheException e) {
140 if (e.getMessage().startsWith("Cannot parseConfiguration CacheManager. Attempt to create a new instance of " +
141 "CacheManager using the diskStorePath")) {
142 throw new CacheException("Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() " +
143 " between repeated calls to buildSessionFactory. Consider using SingletonEhCacheProvider. Error from " +
144 " ehcache was: " + e.getMessage());
145 } else {
146 throw e;
147 }
148 }
149 }
150
151
152 private URL loadResource(String configurationResourceName) {
153 ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
154 URL url = null;
155 if (standardClassloader != null) {
156 url = standardClassloader.getResource(configurationResourceName);
157 }
158 if (url == null) {
159 url = this.getClass().getResource(configurationResourceName);
160 }
161 if (LOG.isDebugEnabled()) {
162 LOG.debug("Creating EhCacheProvider from a specified resource: "
163 + configurationResourceName + " Resolved to URL: " + url);
164 }
165 if (url == null) {
166 if (LOG.isWarnEnabled()) {
167 LOG.warn("A configurationResourceName was set to " + configurationResourceName +
168 " but the resource could not be loaded from the classpath." +
169 "Ehcache will configure itself using defaults.");
170 }
171 }
172 return url;
173 }
174
175 /**
176 * Callback to perform any necessary cleanup of the underlying cache implementation
177 * during SessionFactory.close().
178 */
179 public final void stop() {
180 if (manager != null) {
181 manager.shutdown();
182 manager = null;
183 }
184 }
185
186
187 /**
188 * Not sure what this is supposed to do.
189 *
190 * @return false to be safe
191 */
192 public final boolean isMinimalPutsEnabledByDefault() {
193 return false;
194 }
195
196 }
197