View Javadoc
1   /**
2    * This file Copyright (c) 2008-2015 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.cache.ehcache;
35  
36  import info.magnolia.context.MgnlContext;
37  import info.magnolia.module.cache.CacheModule;
38  import info.magnolia.module.cache.exception.MgnlLockTimeoutException;
39  import info.magnolia.module.cache.listeners.AbstractListeningCacheWrapper;
40  import info.magnolia.module.cache.mbean.CacheMonitor;
41  import info.magnolia.objectfactory.Components;
42  
43  import java.util.List;
44  
45  import org.slf4j.Logger;
46  import org.slf4j.LoggerFactory;
47  
48  import net.sf.ehcache.Ehcache;
49  import net.sf.ehcache.Element;
50  import net.sf.ehcache.constructs.blocking.BlockingCache;
51  import net.sf.ehcache.constructs.blocking.LockTimeoutException;
52  
53  /**
54   * Magnolia cache wrapper for underlying ehCache implementation.
55   */
56  public class EhCacheWrapper extends AbstractListeningCacheWrapper implements info.magnolia.module.cache.BlockingCache {
57      private static final Logger log = LoggerFactory.getLogger(EhCacheWrapper.class);
58  
59      private final BlockingCache ehcache;
60      private final CacheMonitor cacheMonitor;
61      private final String name;
62  
63      public EhCacheWrapper(CacheModule cacheModule, Ehcache ehcache, CacheMonitor cacheMonitor, String name) {
64          super(cacheModule);
65          this.ehcache = castToBlockingCacheOrThrowException(ehcache);
66          this.cacheMonitor = cacheMonitor;
67          this.name = name;
68      }
69  
70      /**
71       * @deprecated since 5.3. Use {@link #EhCacheWrapper(CacheModule, Ehcache, CacheMonitor, String)} instead.
72       */
73      public EhCacheWrapper(BlockingCache ehcache, CacheMonitor cacheMonitor, String name) {
74          this(Components.getComponent(CacheModule.class), ehcache, cacheMonitor, name);
75      }
76  
77      /**
78       * @deprecated since 5.3. Use {@link #EhCacheWrapper(CacheModule, Ehcache, CacheMonitor, String)} instead.
79       */
80      public EhCacheWrapper(Ehcache ehcache, CacheMonitor cacheMonitor, String name) {
81          this(castToBlockingCacheOrThrowException(ehcache), cacheMonitor, name);
82      }
83  
84      private static BlockingCache castToBlockingCacheOrThrowException(Ehcache ehcache) {
85          if (!(ehcache instanceof BlockingCache)) {
86              throw new RuntimeException("The current caching framework depends on the fact the a blocking cache is used.");
87          }
88          return (BlockingCache) ehcache;
89      }
90  
91      @Override
92      public Object get(Object key) {
93          final Element element = ehcache.get(key);
94          Object value;
95          try {
96              value = element != null ? element.getObjectValue() : null;
97          } catch (LockTimeoutException e) {
98              log.error("Detected 1 thread stuck in generating response. This might be temporary if obtaining the response is resource intensive or when accessing remote resources. [url={}]", MgnlContext.getWebContext().getRequest().getRequestURL());
99              throw new MgnlLockTimeoutException(e);
100         }
101         super.get(key);
102         return value;
103     }
104 
105     @Override
106     public Object getQuiet(Object key) {
107         super.getQuiet(key);
108         return ehcache.getQuiet(key).getObjectValue();
109     }
110 
111     @Override
112     public boolean hasElement(Object key) {
113         boolean hasElement;
114         // we can't use isKeyInCache(), as it does not check for the element's expiration
115         // which may lead to unexpected results.
116         // return ehcache.isKeyInCache(key);
117         try {
118             // get() and getQuiet() do check for expiration and return null if the element was expired.
119             // we can't use getQuiet, as it's non-blocking which could lead to multiple copies of same page to be generated
120             // if page is requested while previous request for same page is still being processed by different thread
121             hasElement = ehcache.get(key) != null;
122         } catch (LockTimeoutException e) {
123             log.error("Detected 1 thread stuck in generating response. This might be temporary if obtaining the response is resource intensive or when accessing remote resources. [url={}]", MgnlContext.getWebContext().getRequest().getRequestURL());
124             // FYI: in case you want to return some value instead of re-throwing exception: this is a dilemma ... obviously resource does not exist yet, but being stuck here for while means that it is either being generated or it takes time to generate.
125             // returning false would mean server attempts to generate the response again, possibly loosing another thread in the process
126             // returning true means server will assume resource exists and will try to retrieve it later, possibly failing with the same error
127             throw new MgnlLockTimeoutException(e);
128         }
129         return hasElement;
130     }
131 
132     @Override
133     public void put(Object key, Object value) {
134         final Element element = new Element(key, value);
135         ehcache.put(element);
136         super.put(key, value);
137     }
138 
139     @Override
140     public void put(Object key, Object value, int timeToLiveInSeconds) {
141         final Element element = new Element(key, value);
142         element.setTimeToLive(timeToLiveInSeconds);
143         ehcache.put(element);
144         super.put(key, value, timeToLiveInSeconds);
145     }
146 
147     @Override
148     public void remove(Object key) {
149         ehcache.remove(key);
150         super.remove(key);
151     }
152 
153     @Override
154     public void clear() {
155         cacheMonitor.countFlush(this.name);
156         ehcache.removeAll();
157         super.clear();
158     }
159 
160     @Override
161     public void unlock(Object key) {
162         if (ehcache.getQuiet(key) == null) {
163             put(key, null);
164             remove(key);
165         }
166     }
167 
168     @Override
169     public int getBlockingTimeout() {
170         return ehcache.getTimeoutMillis();
171     }
172 
173     public Ehcache getWrappedEhcache() {
174         return ehcache;
175     }
176 
177     @Override
178     public String getName() {
179         return name;
180     }
181 
182     @Override
183     public int getSize() {
184         return ehcache.getSize();
185     }
186 
187     @Override
188     public List<Object> getKeys() {
189         return ehcache.getKeys();
190     }
191 
192 }