View Javadoc

1   /**
2    * This file Copyright (c) 2003-2010 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.cms.filters;
35  
36  import info.magnolia.cms.beans.runtime.File;
37  import info.magnolia.cms.beans.runtime.FileProperties;
38  import info.magnolia.cms.core.AggregationState;
39  import info.magnolia.cms.core.Content;
40  import info.magnolia.cms.core.HierarchyManager;
41  import info.magnolia.cms.core.NodeData;
42  import info.magnolia.cms.security.AccessDeniedException;
43  import info.magnolia.context.MgnlContext;
44  
45  import java.io.IOException;
46  
47  import javax.jcr.PathNotFoundException;
48  import javax.jcr.PropertyType;
49  import javax.jcr.RepositoryException;
50  import javax.servlet.FilterChain;
51  import javax.servlet.ServletException;
52  import javax.servlet.http.HttpServletRequest;
53  import javax.servlet.http.HttpServletResponse;
54  
55  import org.apache.commons.lang.StringUtils;
56  import org.slf4j.Logger;
57  import org.slf4j.LoggerFactory;
58  
59  
60  /**
61   * @author philipp
62   * @version $Id: AggregatorFilter.java 34461 2010-05-13 11:00:59Z fgiust $
63   *
64   */
65  public class AggregatorFilter extends AbstractMgnlFilter{
66      private static final Logger log = LoggerFactory.getLogger(AggregatorFilter.class);
67  
68      private final String VERSION_NUMBER = "mgnlVersion"; //$NON-NLS-1$
69  
70  
71      public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException{
72  
73          boolean success;
74          try {
75              success = collect();
76          }
77          catch (AccessDeniedException e) {
78              // don't throw further, simply return error and break filter chain
79              log.debug(e.getMessage(), e);
80              if (!response.isCommitted()) {
81                  response.sendError(HttpServletResponse.SC_FORBIDDEN);
82              }
83              // stop the chain
84              return;
85          }
86          catch (RepositoryException e) {
87              log.error(e.getMessage(), e);
88              throw new ServletException(e.getMessage(), e);
89          }
90  
91          if (!success) {
92              log.debug("Resource not found, redirecting request for [{}] to 404 URI", request.getRequestURI());
93  
94              if (!response.isCommitted()) {
95                  response.sendError(HttpServletResponse.SC_NOT_FOUND);
96              }
97              else {
98                  log.info("Unable to redirect to 404 page, response is already committed. URI was {}", request.getRequestURI());
99              }
100             // stop the chain
101             return;
102         }
103         chain.doFilter(request, response);
104     }
105 
106     /**
107      * Collect content from the pre configured repository and attach it to the HttpServletRequest.
108      * @throws PathNotFoundException
109      * @throws RepositoryException
110      */
111     protected boolean collect() throws RepositoryException {
112         final AggregationState aggregationState = MgnlContext.getAggregationState();
113         final String handle = aggregationState.getHandle();
114         final String repository = aggregationState.getRepository();
115 
116         final HierarchyManager hierarchyManager = MgnlContext.getHierarchyManager(repository);
117 
118         Content requestedPage = null;
119         NodeData requestedData = null;
120         final String templateName;
121 
122         if (!isJcrPathValid(handle)) {
123             // avoid calling isExist if the path can't be valid
124             return false;
125         }
126         if (hierarchyManager.isExist(handle) && !hierarchyManager.isNodeData(handle)) {
127             requestedPage = hierarchyManager.getContent(handle);
128 
129             // check if its a request for a versioned page
130             if (MgnlContext.getAttribute(VERSION_NUMBER) != null) {
131                 // get versioned state
132                 try {
133                     requestedPage = requestedPage.getVersionedContent((String)MgnlContext.getAttribute(VERSION_NUMBER));
134                 }
135                 catch (RepositoryException re) {
136                     log.debug(re.getMessage(), re);
137                     log.error("Unable to get versioned state, rendering current state of {}", handle);
138                 }
139             }
140 
141             templateName = requestedPage.getMetaData().getTemplate();
142 
143             if (StringUtils.isBlank(templateName)) {
144                 log.error("No template configured for page [{}].", requestedPage.getHandle()); //$NON-NLS-1$
145             }
146         }
147         else {
148             if (hierarchyManager.isNodeData(handle)) {
149                 requestedData = hierarchyManager.getNodeData(handle);
150             }
151             else {
152                 // check again, resource might have different name
153                 int lastIndexOfSlash = handle.lastIndexOf("/"); //$NON-NLS-1$
154 
155                 if (lastIndexOfSlash > 0) {
156 
157                     final String handleToUse = StringUtils.substringBeforeLast(handle, "/"); //$NON-NLS-1$
158 
159                     try {
160                         requestedData = hierarchyManager.getNodeData(handleToUse);
161                         aggregationState.setHandle(handleToUse);
162 
163                         // this is needed for binary nodedata, e.g. images are found using the path:
164                         // /features/integration/headerImage instead of /features/integration/headerImage/header30_2
165 
166                     }
167                     catch (PathNotFoundException e) {
168                         // no page available
169                         return false;
170                     }
171                     catch (RepositoryException e) {
172                         log.debug(e.getMessage(), e);
173                         return false;
174                     }
175                 }
176             }
177 
178             if (requestedData != null) {
179                 templateName = requestedData.getAttribute(FileProperties.PROPERTY_TEMPLATE);
180             }
181             else {
182                 return false;
183             }
184         }
185 
186         // Attach all collected information to the HttpServletRequest.
187         if (requestedPage != null) {
188             aggregationState.setMainContent(requestedPage);
189             aggregationState.setCurrentContent(requestedPage);
190         }
191         if ((requestedData != null) && (requestedData.getType() == PropertyType.BINARY)) {
192             File file = new File(requestedData);
193             aggregationState.setFile(file);
194         }
195 
196         aggregationState.setTemplateName(templateName);
197 
198         return true;
199     }
200 
201     /**
202      * Check if the path *may be* a valid path before calling getItem, in order to avoid annoying logs.
203      * @param handle node handle
204      * @return true if the path is invalid
205      */
206     private boolean isJcrPathValid(String handle) {
207         if (StringUtils.isBlank(handle) || StringUtils.equals(handle, "/")) {
208             // empty path not allowed
209             return false;
210         }
211         if (StringUtils.containsAny(handle, new char[]{':', '*', '\n'})) {
212             // not allowed chars
213             return false;
214         }
215         if (StringUtils.contains(handle, " /")) {
216             // trailing slash not allowed
217             return false;
218         }
219         return true;
220     }
221 
222 }