Clover icon

Magnolia Module Cache 5.5.9

  1. Project Clover database Mon Nov 25 2019 16:46:50 CET
  2. Package info.magnolia.module.cache.filter

File CacheFilter.java

 

Coverage histogram

../../../../../img/srcFileCovDistChart7.png
45% of files have more coverage

Code metrics

20
61
12
1
253
170
28
0.46
5.08
12
2.33
7.9% of code in this file is excluded from these metrics.

Classes

Class Line # Actions
CacheFilter 73 61 7.9% 28 30
0.6774193667.7%
 

Contributing tests

This file is covered by 20 tests. .

Source view

1    /**
2    * This file Copyright (c) 2008-2018 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.filter;
35   
36    import info.magnolia.cms.core.AggregationState;
37    import info.magnolia.cms.filters.AbstractMgnlFilter;
38    import info.magnolia.cms.util.ServletUtil;
39    import info.magnolia.context.WebContext;
40    import info.magnolia.module.cache.AbstractCacheModule;
41    import info.magnolia.module.cache.BlockingCache;
42    import info.magnolia.module.cache.Cache;
43    import info.magnolia.module.cache.CacheModule;
44    import info.magnolia.module.cache.CacheModuleLifecycleListener;
45    import info.magnolia.module.cache.CachePolicyExecutor;
46    import info.magnolia.module.cache.CachePolicyResult;
47    import info.magnolia.module.cache.ContentCachingConfiguration;
48    import info.magnolia.module.cache.cachepolicy.result.CachePolicyResultProvider;
49    import info.magnolia.module.cache.exception.MgnlLockTimeoutException;
50    import info.magnolia.module.cache.mbean.CacheMonitor;
51    import info.magnolia.objectfactory.Components;
52   
53    import java.io.IOException;
54   
55    import javax.inject.Inject;
56    import javax.inject.Provider;
57    import javax.servlet.FilterChain;
58    import javax.servlet.FilterConfig;
59    import javax.servlet.ServletException;
60    import javax.servlet.ServletResponse;
61    import javax.servlet.http.HttpServletRequest;
62    import javax.servlet.http.HttpServletResponse;
63    import javax.servlet.http.HttpServletResponseWrapper;
64   
65    import org.apache.commons.lang3.exception.ExceptionUtils;
66    import org.slf4j.Logger;
67    import org.slf4j.LoggerFactory;
68   
69    /**
70    * Uses the CachePolicy to determine the cache behavior. Uses then the
71    * ContentCachingConfiguration to get the executors to be executed.
72    */
 
73    public class CacheFilter extends AbstractMgnlFilter implements CacheModuleLifecycleListener {
74   
75    /**
76    * @deprecated since 5.4, use {@link AbstractCacheModule#DEFAULT_CACHE_CONFIG}.
77    */
78    @Deprecated
79    public static final String DEFAULT_CONTENT_CACHING_CONFIGURATION_NAME = AbstractCacheModule.DEFAULT_CACHE_CONFIG;
80   
81    private static final Logger log = LoggerFactory.getLogger(CacheFilter.class);
82   
83   
84    private String defaultContentCachingConfigurationName;
85    private Cache cache;
86    private ContentCachingConfiguration contentCaching;
87   
88    private final CacheModule cacheModule;
89    private final CacheMonitor monitor;
90    private final Provider<WebContext> webContextProvider;
91    private final Provider<CachePolicyResultProvider> cachePolicyResultProviderProvider;
92   
 
93  22 toggle @Inject
94    public CacheFilter(Provider<WebContext> webContextProvider, CacheModule cacheModule, CacheMonitor cacheMonitor, Provider<CachePolicyResultProvider> cachePolicyResultProvider) {
95  22 this.cacheModule = cacheModule;
96  22 this.monitor = cacheMonitor;
97  22 this.webContextProvider = webContextProvider;
98  22 this.cachePolicyResultProviderProvider = cachePolicyResultProvider;
99    }
100   
101    /**
102    * @deprecated since 5.5. Use {@link #CacheFilter(Provider, CacheModule, CacheMonitor, Provider)} instead.
103    */
 
104  0 toggle @Deprecated
105    public CacheFilter(CacheModule cacheModule, CacheMonitor cacheMonitor, Provider<AggregationState> aggregationStateProvider, Provider<CachePolicyResultProvider> cachePolicyResultProvider) {
106  0 this(new Provider<WebContext>() {
 
107  0 toggle @Override
108    public WebContext get() {
109  0 return Components.getComponent(WebContext.class);
110    }
111    }, cacheModule, cacheMonitor, cachePolicyResultProvider);
112    }
113   
114    /**
115    * @deprecated since 5.4.7. Use {@link #CacheFilter(Provider, CacheModule, CacheMonitor, Provider)} instead.
116    */
 
117  0 toggle @Deprecated
118    public CacheFilter(CacheModule cacheModule, CacheMonitor cacheMonitor) {
119  0 this(new Provider<WebContext>() {
 
120  0 toggle @Override
121    public WebContext get() {
122  0 return Components.getComponent(WebContext.class);
123    }
124    }, cacheModule, cacheMonitor, new Provider<CachePolicyResultProvider>() {
 
125  0 toggle @Override
126    public CachePolicyResultProvider get() {
127  0 return Components.getComponent(CachePolicyResultProvider.class);
128    }
129    }
130    );
131    }
132   
133    /**
134    * @deprecated since 5.4, use {@link #getDefaultContentCachingConfigurationName()}.
135    */
 
136    toggle @Deprecated
137    public String getCacheConfigurationName() {
138    return getDefaultContentCachingConfigurationName();
139    }
140   
141    /**
142    * @deprecated since 5.4, use {@link #setDefaultContentCachingConfigurationName(String)}.
143    */
 
144    toggle @Deprecated
145    public void setCacheConfigurationName(String cacheConfigurationName) {
146    setDefaultContentCachingConfigurationName(cacheConfigurationName);
147    }
148   
 
149    toggle public String getDefaultContentCachingConfigurationName() {
150    return defaultContentCachingConfigurationName;
151    }
152   
 
153    toggle public void setDefaultContentCachingConfigurationName(String defaultContentCachingConfigurationName) {
154    this.defaultContentCachingConfigurationName = defaultContentCachingConfigurationName;
155    }
156   
 
157  23 toggle @Override
158    public void init(FilterConfig filterConfig) throws ServletException {
159  23 super.init(filterConfig);
160  23 cacheModule.register(this);
161    // filters are started *after* modules - so we have to force a call onCacheModuleStart() here
162  23 onCacheModuleStart();
163    }
164   
 
165  24 toggle @Override
166    public void onCacheModuleStart() {
167   
168  24 if (defaultContentCachingConfigurationName == null) {
169  0 log.warn("The {} property is not set for the {} CacheFilter, falling back to {}.", "defaultContentCachingConfigurationName", getName(), AbstractCacheModule.DEFAULT_CACHE_CONFIG);
170  0 this.defaultContentCachingConfigurationName = AbstractCacheModule.DEFAULT_CACHE_CONFIG;
171    }
172  24 this.contentCaching = cacheModule.getContentCaching(defaultContentCachingConfigurationName);
173  24 cache = cacheModule.getCacheFactory().getCache(contentCaching.getCacheName());
174   
175  24 if (contentCaching == null || cache == null) {
176  1 log.error("The " + getName() + " CacheFilter is not properly configured, either default contentCaching(" + contentCaching + ") or cache(" + cache + ") is null. Check if " + defaultContentCachingConfigurationName + " is a valid content caching configuration name. Will disable temporarily.");
177  1 setEnabled(false);
178    }
179    }
180   
 
181  17 toggle protected Cache getCurrentPageCache() {
182  17 return cache;
183    }
184   
 
185  0 toggle protected CacheModule getModule() {
186  0 return cacheModule;
187    }
188   
 
189  17 toggle @Override
190    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
191   
192  17 final CachePolicyResult cachePolicyResult;
193  17 final Cache cache = this.getCurrentPageCache();
194  17 int blockingTimeout = -1;
195  17 if (cache instanceof BlockingCache) {
196  0 blockingTimeout = ((BlockingCache) cache).getBlockingTimeout();
197    }
198  17 final ContentCachingConfiguration contentCachingConfiguration = cacheModule.getContentCaching(cache.getName());
199  17 try {
200  17 cachePolicyResult = contentCachingConfiguration.getCachePolicy().shouldCache(cache, webContextProvider.get().getAggregationState(), contentCachingConfiguration.getFlushPolicy());
201  17 cachePolicyResult.setCacheName(cache.getName());
202  17 cachePolicyResultProviderProvider.get().setCachePolicyResult(cachePolicyResult);
203    } catch (MgnlLockTimeoutException timeout) {
204  0 log.warn("The following URL was blocked for longer than {} seconds and has timed-out. The request has been blocked as another request is already processing the same resource. [url={}]", blockingTimeout / 1000, request.getRequestURL());
205  0 throw timeout;
206    }
207   
208  17 log.debug("Cache policy result: {}", cachePolicyResult);
209   
210  17 final CachePolicyResult.CachePolicyBehaviour behaviour = cachePolicyResult.getBehaviour();
211  17 monitor.logBehavior(behaviour.getName());
212  17 monitor.logAccess(cachePolicyResult.getCacheKey());
213  17 final CachePolicyExecutor executor = contentCachingConfiguration.getExecutor(behaviour);
214  17 if (executor == null) {
215  0 throw new IllegalStateException("Unexpected cache policy result: " + cachePolicyResult);
216    }
217   
218  17 try {
219  17 final long start = System.currentTimeMillis();
220  17 executor.processCacheRequest(request, response, chain, cache, cachePolicyResult);
221  16 final long end = System.currentTimeMillis();
222   
223  16 if (blockingTimeout != -1 && (end - start) >= blockingTimeout) {
224  0 log.warn("The following URL took longer than {} seconds ({} ms) to render. This might cause timeout exceptions on other requests to the same URI. [url={}]", blockingTimeout / 1000, (end - start), request.getRequestURL());
225    }
226    } catch (Throwable th) {
227  1 if (cachePolicyResult.getBehaviour() == CachePolicyResult.store && cache instanceof BlockingCache) {
228  0 log.error("A request started to cache but failed with an exception ({}). [url={}]", ExceptionUtils.getRootCauseMessage(th), request.getRequestURL());
229  0 ((BlockingCache) cache).unlock(cachePolicyResult.getCacheKey());
230    }
231  1 if (th instanceof RuntimeException) { // no need to rewrap RuntimeException
232  1 throw (RuntimeException) th;
233    }
234  0 throw new RuntimeException(th);
235    }
236    }
237   
 
238  2 toggle @Override
239    public boolean bypasses(HttpServletRequest request) {
240  2 if (request.getAttribute(ServletUtil.ERROR_REQUEST_STATUS_CODE_ATTRIBUTE) != null) {
241  1 return true;
242    }
243  1 ServletResponse responseWrapper = webContextProvider.get().getResponse();
244  2 while (responseWrapper instanceof HttpServletResponseWrapper) {
245  2 if (responseWrapper instanceof CacheResponseWrapper && !(responseWrapper instanceof GZipFilter.GZipCacheResponseWrapper)) {
246  1 return true;
247    } else {
248  1 responseWrapper = ((HttpServletResponseWrapper) responseWrapper).getResponse();
249    }
250    }
251  0 return super.bypasses(request);
252    }
253    }