View Javadoc

1   /**
2    * This file Copyright (c) 2010-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.cms.filters;
35  
36  import info.magnolia.cms.util.ServletUtil;
37  import info.magnolia.cms.util.SimpleUrlPattern;
38  import info.magnolia.context.MgnlContext;
39  import info.magnolia.context.WebContext;
40  import org.apache.commons.lang.StringUtils;
41  import org.slf4j.Logger;
42  import org.slf4j.LoggerFactory;
43  
44  import javax.servlet.http.HttpServletRequest;
45  import java.util.ArrayList;
46  import java.util.Collection;
47  import java.util.Iterator;
48  import java.util.regex.Matcher;
49  import java.util.regex.Pattern;
50  
51  
52  /**
53   * A URI mapping as configured for filters and servlets.
54   */
55  public class Mapping {
56  
57      private static Logger log = LoggerFactory.getLogger(Mapping.class);
58  
59      private static final String METACHARACTERS = "([\\^\\(\\)\\{\\}\\[\\]*$+])";
60  
61      protected static String escapeMetaCharacters(String str) {
62          return str.replaceAll(METACHARACTERS, "\\\\$1");
63      }
64  
65      protected Collection<Pattern> mappings = new ArrayList<Pattern>();
66  
67      public MatchingResult match(HttpServletRequest request) {
68          Matcher matcher = findMatcher(request);
69          boolean matches = matcher != null;
70          int matchingEndPosition = determineMatchingEnd(matcher);
71          return new MatchingResult(matcher, matches, matchingEndPosition);
72      }
73  
74      /**
75       * Determines the index of the first pathInfo character. If the uri does not match any mapping
76       * this method returns -1.
77       */
78      private int determineMatchingEnd(Matcher matcher) {
79          if (matcher == null) {
80              return -1;
81          }
82          if (matcher.groupCount() > 0) {
83              return matcher.end(1);
84          }
85          return matcher.end();
86      }
87  
88      private Matcher findMatcher(HttpServletRequest request) {
89          String uri = null;
90          WebContext ctx = MgnlContext.getWebContextOrNull();
91          if (ctx != null) {
92              uri = ctx.getAggregationState().getCurrentURI();
93          }
94          if (uri == null) {
95              // the web context is not available during installation
96              uri = ServletUtil.stripPathParameters(request.getRequestURI());
97              String contextPath = request.getContextPath();
98              // The requestUri should always start with the context path
99              if (uri.startsWith(contextPath + "/")) {
100                 uri = uri.substring(contextPath.length());
101             }
102         }
103         return findMatcher(uri);
104     }
105 
106     private Matcher findMatcher(String uri) {
107         for (Iterator iter = mappings.iterator(); iter.hasNext();) {
108             final Matcher matcher = ((Pattern) iter.next()).matcher(uri);
109 
110             if (matcher.find()) {
111                 return matcher;
112             }
113         }
114 
115         return null;
116     }
117 
118     public Collection<Pattern> getMappings() {
119         return mappings;
120     }
121 
122     public void setMappings(Collection<String> mappings) {
123         for (String mapping : mappings) {
124             this.addMapping(mapping);
125         }
126     }
127 
128     /**
129      * See SRV.11.2 Specification of Mappings in the Servlet Specification for the syntax of
130      * mappings. Additionally, you can also use plain regular expressions to map your servlets, by
131      * prefix the mapping by "regex:". (in which case anything in the request url following the
132      * expression's match will be the pathInfo - if your pattern ends with a $, extra pathInfo won't
133      * match)
134      */
135     public void addMapping(final String mapping) {
136         final String pattern;
137 
138         // we're building a Pattern with 3 groups: (1) servletPath (2) ignored (3) pathInfo
139 
140         if (isDefaultMapping(mapping)) {
141             // the mapping is exactly '/*', the servlet path should be
142             // an empty string and everything else should be the path info
143             pattern = "^()(/)(" + SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + ")";
144         }
145         else if (isPathMapping(mapping)) {
146             // the pattern ends with /*, escape out metacharacters for
147             // use in a regex, and replace the ending * with MULTIPLE_CHAR_PATTERN
148             final String mappingWithoutSuffix = StringUtils.removeEnd(mapping, "/*");
149             pattern = "^(" + escapeMetaCharacters(mappingWithoutSuffix) + ")(/)(" + SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + ")";
150         }
151         else if (isExtensionMapping(mapping)) {
152             // something like '*.jsp', everything should be the servlet path
153             // and the path info should be null
154             final String regexedMapping = StringUtils.replace(mapping, "*.", SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + "\\.");
155             pattern = "^(" + regexedMapping + ")$";
156         }
157         else if (isRegexpMapping(mapping)) {
158             final String mappingWithoutPrefix = StringUtils.removeStart(mapping, "regex:");
159             pattern = "^(" + mappingWithoutPrefix + ")($|/)(" + SimpleUrlPattern.MULTIPLE_CHAR_PATTERN + ")";
160         }
161         else {
162             // just literal text, ensure metacharacters are escaped, and that only
163             // the exact string is matched.
164             pattern = "^(" + escapeMetaCharacters(mapping) + ")$";
165         }
166         log.debug("Adding new mapping for {}", mapping);
167 
168         mappings.add(Pattern.compile(pattern));
169     }
170 
171     /**
172      * This is order specific, this method should not be called until after the isDefaultMapping()
173      * method else it will return true for a default mapping.
174      */
175     private boolean isPathMapping(String mapping) {
176         return mapping.startsWith("/") && mapping.endsWith("/*");
177     }
178 
179     private boolean isExtensionMapping(String mapping) {
180         return mapping.startsWith("*.");
181     }
182 
183     private boolean isDefaultMapping(String mapping) {
184         // TODO : default mapping per spec is "/" - do we really want to support this? is there a
185         // point ?
186         return mapping.equals("/");
187     }
188 
189     private boolean isRegexpMapping(String mapping) {
190         return mapping.startsWith("regex:");
191     }
192 
193     /**
194      * Result of {@link ThemeReader} {@link Mapping#match(HttpServletRequest)} method.
195      */
196     public static class MatchingResult {
197 
198         Matcher matcher;
199 
200         boolean matches;
201 
202         int matchingEndPosition;
203 
204         public MatchingResult(Matcher matcher, boolean matches, int matchingEndPosition) {
205             this.matcher = matcher;
206             this.matches = matches;
207             this.matchingEndPosition = matchingEndPosition;
208         }
209 
210         public Matcher getMatcher() {
211             return matcher;
212         }
213 
214         public boolean isMatching() {
215             return matches;
216         }
217 
218         public int getMatchingEndPosition() {
219             return matchingEndPosition;
220         }
221     }
222 
223 }