View Javadoc

1   /**
2    * This file Copyright (c) 2003-2011 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.util;
35  
36  import info.magnolia.cms.core.AggregationState;
37  import info.magnolia.context.MgnlContext;
38  import info.magnolia.context.WebContext;
39  
40  import java.lang.reflect.InvocationTargetException;
41  import java.lang.reflect.Method;
42  import java.util.regex.Pattern;
43  
44  import org.apache.commons.lang.StringUtils;
45  import org.slf4j.Logger;
46  import org.slf4j.LoggerFactory;
47  
48  /**
49   * An implementation of URLPattern which matches strings using simple <code>*</code> or <code>?</code> wildcards.
50   * @author Sameer Charles
51   * @author Fabrizio Giustina
52   * TODO rewrite this class using ant-style path comparison and avoiding regexp. See
53   * org.springframework.util.AntPathMatcher in spring 1.2 for a nice implementation.
54   * @version $Revision $ ($Author $)
55   */
56  public final class SimpleUrlPattern implements UrlPattern {
57      
58      private static final Logger log = LoggerFactory.getLogger(SimpleUrlPattern.class);
59  
60      /**
61       * Stable serialVersionUID.
62       */
63      private static final long serialVersionUID = 223L;
64  
65      /**
66       * Any char, newline included.
67       */
68      public static final String URL_CHAR_PATTERN = "."; //$NON-NLS-1$
69  
70      /**
71       * Regexp pattern used for the simple keyword <code>*</code>. Matches 0 or more characters.
72       */
73      public static final String MULTIPLE_CHAR_PATTERN = URL_CHAR_PATTERN + "*"; //$NON-NLS-1$
74  
75      /**
76       * Regexp pattern used for the simple keyword <code>?</code>. Matches 0 or 1 character.
77       */
78      public static final String SINGLE_CHAR_PATTERN = URL_CHAR_PATTERN + "?"; //$NON-NLS-1$
79  
80      /**
81       * Regexp pattern used in match().
82       */
83      private Pattern pattern;
84  
85      /**
86       * Pattern length. Longer patterns have higher priority.
87       */
88      private int length;
89  
90      /**
91       * internal pattern string.
92       */
93      private String patternString;
94      
95      private String site;
96  
97      /**
98       * Compile a regexp pattern handling <code>*</code> and <code>?</code> chars.
99       * @param string input string
100      * @return a RegExp pattern
101      */
102     public SimpleUrlPattern(String string) {
103         String newPattern = string;
104         if(newPattern.startsWith("<")){
105             this.site = StringUtils.substringAfter(StringUtils.substringBefore(newPattern, ">"), "<");
106             newPattern = StringUtils.substringAfter(newPattern, ">");
107         }
108         this.length = StringUtils.removeEnd(newPattern, "*").length();
109         this.pattern = Pattern.compile(getEncodedString(newPattern), Pattern.DOTALL);
110         this.patternString = newPattern;
111     }
112 
113     /**
114      * Replace all "*" with <code>RegexWildcardPattern.MULTIPLE_CHAR_PATTERN</code>.
115      * @param str input string
116      * @return string where all the occurrences of <code>*</code> and <code>?</code> are replaced with a regexp
117      * pattern.
118      */
119     public static String getEncodedString(String str) {
120         StringBuffer stringBuffer = new StringBuffer();
121         char[] chars = str.toCharArray();
122         int i = 0, last = 0;
123         while (i < chars.length) {
124             char c = chars[i];
125             if (c == '*') {
126                 stringBuffer.append('(');
127                 stringBuffer.append(chars, last, i - last);
128                 stringBuffer.append(')');
129                 stringBuffer.append(MULTIPLE_CHAR_PATTERN);
130                 last = i + 1;
131             }
132             else if (c == '?') {
133                 stringBuffer.append('(');
134                 stringBuffer.append(chars, last, i - last);
135                 stringBuffer.append(')');
136                 stringBuffer.append(SINGLE_CHAR_PATTERN);
137                 last = i + 1;
138             }
139             i++;
140         }
141         stringBuffer.append(chars, last, i - last);
142         return stringBuffer.toString();
143     }
144 
145     public boolean shouldUseFullURI(String pattern, String fullURI){
146         //FullURI cannot be null
147         if(StringUtils.isBlank(fullURI)){
148             return false;
149         }
150         String patternWithoutLastSlash = StringUtils.removeEnd(pattern, "/");
151         //Has to contain pattern it should replace
152         if(!fullURI.contains(patternWithoutLastSlash)){
153             return false;
154         }
155         //FullURI should end with pattern if it's not just "/"
156         if(StringUtils.isNotBlank(StringUtils.substringAfter(fullURI, patternWithoutLastSlash)) && StringUtils.isNotBlank(patternWithoutLastSlash)){
157             return false;
158         }
159         //FullURI should add just first level node
160         if(StringUtils.countMatches(StringUtils.substringBefore(fullURI, patternWithoutLastSlash), "/") > 1){
161             return false;
162         }
163         return true;
164     }
165 
166     /**
167      * @see info.magnolia.cms.util.UrlPattern#match(java.lang.String)
168      */
169     public boolean match(String str) {
170         String domainName = getDomainName();
171         String siteName = getSiteNameBasedOnDomain(domainName);
172         if (StringUtils.isNotBlank(siteName)) {
173             // site aware request !!!! URI was shortened
174             String fullURI = getFullCurrentURI();
175             if(shouldUseFullURI(str, fullURI) && StringUtils.isNotBlank(this.site)){
176                 str = fullURI;
177             }
178         }
179         return this.pattern.matcher(str).matches() && matchSiteName(siteName);
180     }
181     
182     public boolean matchSiteName(String siteName){
183         // case 1 - no site configured and no site available
184         if(this.site == null && siteName == null){
185             return true;
186         }
187 
188         // case 2 - site is configured and we don't have site info
189         if(this.site != null && siteName == null){
190             return false;
191         }
192 
193         // case 4 - permission is NOT site aware, but we have determined the site and changed the URI
194         if (this.site == null && siteName != null) {
195             return true;
196         }
197 
198         // case 3 - site is configured and we have site info
199         return site.equals(siteName);
200     }
201 
202     private String getSiteNameBasedOnDomain(String domain) {
203         if(MgnlContext.getInstance() instanceof WebContext){
204             AggregationState aggregationState = MgnlContext.getAggregationState();
205             if (aggregationState == null) {
206                 return null;
207             }
208             // workaround until we move site to core
209             Method getSite;
210             try {
211                 getSite = aggregationState.getClass().getMethod("getSiteBasedOnDomain", String.class);
212                 Object siteName = getSite.invoke(aggregationState, domain);
213                 if(null != siteName){
214                     return siteName.toString();
215                 }
216                 return null;
217             } catch (NoSuchMethodException e) {
218                 log.debug("Not proper ExtendedAggregationState provided", e);
219             } catch (IllegalArgumentException e) {
220                 log.debug("Not proper ExtendedAggregationState provided", e);
221             } catch (IllegalAccessException e) {
222                 log.debug("Not proper ExtendedAggregationState provided", e);
223             } catch (InvocationTargetException e) {
224                 log.debug("Not proper ExtendedAggregationState provided", e);
225             }
226             return null;
227         }
228         return null;
229     }
230     
231     private String getFullCurrentURI() {
232         if(MgnlContext.getInstance() instanceof WebContext){
233             AggregationState aggregationState = MgnlContext.getAggregationState();
234             if (aggregationState == null) {
235                 return null;
236             }
237             // workaround until we move site to core
238             Method getFullCurrentURI;
239             try {
240                 getFullCurrentURI = aggregationState.getClass().getMethod("getFullCurrentURI");
241                 Object fullURI = getFullCurrentURI.invoke(aggregationState);
242                 if(null != fullURI){
243                     return fullURI.toString();
244                 }
245                 return null;
246             } catch (NoSuchMethodException e) {
247                 log.debug("Not proper ExtendedAggregationState provided", e);
248             } catch (IllegalArgumentException e) {
249                 log.debug("Not proper ExtendedAggregationState provided", e);
250             } catch (IllegalAccessException e) {
251                 log.debug("Not proper ExtendedAggregationState provided", e);
252             } catch (InvocationTargetException e) {
253                 log.debug("Not proper ExtendedAggregationState provided", e);
254             }
255             return null;
256         }
257         return null;
258     }
259     
260     private String getDomainName() {
261         if(MgnlContext.getInstance() instanceof WebContext){
262             AggregationState aggregationState = MgnlContext.getAggregationState();
263             if (aggregationState == null) {
264                 return null;
265             }
266             // workaround until we move site to core
267             Method getDomainName;
268             try {
269                 getDomainName = aggregationState.getClass().getMethod("getDomainName");
270                 Object domainName = getDomainName.invoke(aggregationState);
271                 if(null != domainName){
272                     return domainName.toString();
273                 }
274                 return null;
275             } catch (NoSuchMethodException e) {
276                 log.debug("Not proper ExtendedAggregationState provided", e);
277             } catch (IllegalArgumentException e) {
278                 log.debug("Not proper ExtendedAggregationState provided", e);
279             } catch (IllegalAccessException e) {
280                 log.debug("Not proper ExtendedAggregationState provided", e);
281             } catch (InvocationTargetException e) {
282                 log.debug("Not proper ExtendedAggregationState provided", e);
283             }
284             return null;
285         }
286         return null;
287     }
288 
289     /**
290      * @see info.magnolia.cms.util.UrlPattern#getLength()
291      */
292     public int getLength() {
293         return this.length;
294     }
295 
296     public String toString() {
297         // don't use pattern.pattern(), but keep the original string.
298         // The "compiled" pattern will display the ugly patterns like MULTIPLE_CHAR_PATTERN instead of simple *
299         return "SimpleUrlPattern{" + patternString + '}';
300     }
301 }