View Javadoc

1   /**
2    * This file Copyright (c) 2008-2014 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.executor;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.context.MgnlContext;
38  import info.magnolia.jcr.util.NodeUtil;
39  import info.magnolia.module.ModuleRegistry;
40  import info.magnolia.module.cache.Cache;
41  import info.magnolia.module.cache.CacheModule;
42  import info.magnolia.module.cache.CachePolicy;
43  import info.magnolia.module.cache.CachePolicyResult;
44  import info.magnolia.module.cache.filter.CacheResponseWrapper;
45  import info.magnolia.module.cache.filter.CachedEntry;
46  import info.magnolia.module.cache.filter.CachedError;
47  import info.magnolia.module.cache.filter.CachedRedirect;
48  import info.magnolia.module.cache.filter.ContentCachedEntry;
49  import info.magnolia.module.cache.filter.DelegatingBlobCachedEntry;
50  import info.magnolia.module.cache.filter.InMemoryCachedEntry;
51  import info.magnolia.objectfactory.Components;
52  
53  import java.io.IOException;
54  
55  import javax.inject.Inject;
56  import javax.jcr.Node;
57  import javax.jcr.RepositoryException;
58  import javax.servlet.FilterChain;
59  import javax.servlet.ServletException;
60  import javax.servlet.http.HttpServletRequest;
61  import javax.servlet.http.HttpServletResponse;
62  
63  /**
64   * Wraps the response and stores the content in a cache Entry.
65   * 
66   * @author pbracher
67   * @version $Revision: $ ($Author: $)
68   */
69  public class Store extends AbstractExecutor {
70  
71      private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Store.class);
72      private final CacheModule cacheModule;
73  
74      /**
75       * @deprecated since 4.5.17. Use {@link #Store(CacheModule)} instead.
76       */
77      public Store() {
78          this.cacheModule = Components.getComponent(ModuleRegistry.class).getModuleInstance(CacheModule.class);
79      }
80  
81      @Inject
82      public Store(CacheModule cacheModule) {
83          this.cacheModule = cacheModule;
84      }
85  
86      @Override
87      public void processCacheRequest(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Cache cache, CachePolicyResult cachePolicyResult) throws IOException, ServletException {
88          CachedEntry cachedEntry = null;
89          final Object key = cachePolicyResult.getCacheKey();
90  
91          final CacheResponseWrapper responseWrapper = new CacheResponseWrapper(response, CacheResponseWrapper.DEFAULT_THRESHOLD, false);
92          responseWrapper.setResponseExpirationDetectionEnabled();
93  
94          // setting Last-Modified to when this resource was stored in the cache. This value might get overridden by further filters or servlets.
95          final long cacheStorageDate = System.currentTimeMillis();
96          responseWrapper.setDateHeader("Last-Modified", cacheStorageDate);
97  
98          try {
99              chain.doFilter(request, responseWrapper);
100             if (responseWrapper.getStatus() == HttpServletResponse.SC_NOT_MODIFIED) {
101                 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
102             }
103             else {
104                 responseWrapper.flushBuffer();
105                 cachedEntry = makeCachedEntry(request, responseWrapper);
106             }
107 
108         } catch (IOException e) {
109             responseWrapper.cleanUp();
110             throw e;
111         } catch (ServletException e) {
112             responseWrapper.cleanUp();
113             throw e;
114         } catch (Throwable e) {
115             responseWrapper.cleanUp();
116             throw new RuntimeException("Failed to process request with: " + e.getMessage(), e);
117         }
118 
119         if (cachedEntry == null) {
120             // put null to unblock the cache
121             cache.put(key, null);
122             return;
123         }
124 
125         int timeToLiveInSeconds = cachedEntry.getTimeToLiveInSeconds();
126         if (timeToLiveInSeconds == 0) {
127             // put null to unblock the cache
128             cache.put(key, null);
129 
130             // stream the response directly
131             cachedEntry.replay(request, response, chain);
132             response.flushBuffer();
133 
134             return;
135         }
136 
137         // store cachedEntry to cachePolicyResult only when cachedEntry timeToLiveInSeconds is not 0, because when it is, Store will replay response directly (see code above)
138         cachePolicyResult.setCachedEntry(cachedEntry);
139 
140         if (timeToLiveInSeconds == -1) {
141             cache.put(key, cachedEntry);
142         } else {
143             cache.put(key, cachedEntry, timeToLiveInSeconds);
144         }
145 
146         // let policy know the uuid in case it wants to do something with it
147         final Content mainContent = MgnlContext.getAggregationState().getMainContent();
148         final Node content = mainContent != null ? mainContent.getJCRNode() : null;
149         try {
150             if (content != null && NodeUtil.isNodeType(content, "mix:referenceable")) {
151                 final String uuid = content.getIdentifier();
152                 String repo = content.getSession().getWorkspace().getName();
153                 getCachePolicy(cache).persistCacheKey(repo, uuid, key);
154             }
155         } catch (RepositoryException e) {
156             // TODO dlipp: apply consistent ExceptionHandling
157             throw new RuntimeException(e);
158         }
159     }
160 
161     protected CachedEntry makeCachedEntry(HttpServletRequest request, CacheResponseWrapper cachedResponse) throws IOException {
162         // query params are handled by the cache key
163         final String originalUrl = request.getRequestURL().toString();
164         int status = cachedResponse.getStatus();
165         int timeToLiveInSeconds = cachedResponse.getTimeToLiveInSeconds();
166 
167         // TODO : handle more of the 30x codes - although CacheResponseWrapper currently only sets the 302 or 304.
168         if (cachedResponse.getRedirectionLocation() != null) {
169             return new CachedRedirect(cachedResponse.getStatus(), cachedResponse.getRedirectionLocation(), originalUrl, timeToLiveInSeconds);
170         }
171 
172         if (cachedResponse.isError()) {
173             return new CachedError(cachedResponse.getStatus(), originalUrl, timeToLiveInSeconds);
174         }
175 
176         final long modificationDate = cachedResponse.getLastModified();
177         final String contentType = cachedResponse.getContentType();
178 
179         ContentCachedEntry cacheEntry;
180         if (!cachedResponse.isThresholdExceeded()) {
181             cacheEntry = new InMemoryCachedEntry(cachedResponse.getBufferedContent(),
182                     contentType,
183                     cachedResponse.getCharacterEncoding(),
184                     status,
185                     cachedResponse.getHeaders(),
186                     modificationDate,
187                     originalUrl,
188                     timeToLiveInSeconds);
189         }
190         else {
191             cacheEntry = new DelegatingBlobCachedEntry(cachedResponse.getContentLength(),
192                     contentType,
193                     cachedResponse.getCharacterEncoding(),
194                     status,
195                     cachedResponse.getHeaders(),
196                     modificationDate,
197                     originalUrl,
198                     timeToLiveInSeconds);
199 
200             // TODO remove this once we use a blob store
201             // the file will be deleted once served in this request
202             ((DelegatingBlobCachedEntry) cacheEntry).bindContentFileToCurrentRequest(request, cachedResponse.getContentFile());
203             cachedResponse.getThresholdingOutputStream().close();
204         }
205 
206         return cacheEntry;
207     }
208 
209     protected CachePolicy getCachePolicy(Cache cache) {
210         return cacheModule.getConfiguration(cache.getName()).getCachePolicy();
211     }
212 
213     /**
214      * @deprecated since 4.5, use {@link #cacheModule} instead.
215      */
216     @Deprecated
217     protected CacheModule getModule() {
218         return cacheModule;
219     }
220 }