View Javadoc

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