View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2014 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package io.wcm.handler.url.suffix.impl;
21  
22  import java.util.HashMap;
23  import java.util.Map;
24  
25  import org.apache.commons.lang3.StringUtils;
26  import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
27  import org.apache.commons.lang3.text.translate.EntityArrays;
28  import org.apache.commons.lang3.text.translate.LookupTranslator;
29  import org.apache.sling.api.resource.Resource;
30  
31  /**
32   * Static methods and constants for URL suffix handling.
33   */
34  @SuppressWarnings("deprecation")
35  public final class UrlSuffixUtil {
36  
37    /**
38     * Delimiter char for suffix parts and key/value pairs
39     */
40    public static final char SUFFIX_PART_DELIMITER = '/';
41  
42    /**
43     * Delimiter char for suffix parts and key and value
44     */
45    public static final char KEY_VALUE_DELIMITER = '=';
46  
47    /**
48     * Double escaping is necessary when constructing urls so that escaping is not resolved by the webserver
49     */
50    public static final String ESCAPE_DELIMITER = "~";
51  
52    /**
53     * Slash value within suffix part
54     */
55    public static final String ESCAPED_SLASH = ESCAPE_DELIMITER + hexCode('/');
56  
57    /**
58     * Map with special chars and their replacements that are escaped with special ~ and hexcode
59     */
60    private static final String[][] SPECIAL_CHARS_MAPPING = {
61      // escape delimiter chars
62      {
63        Character.toString(SUFFIX_PART_DELIMITER), ESCAPE_DELIMITER + hexCode(SUFFIX_PART_DELIMITER)
64      },
65      {
66        Character.toString(KEY_VALUE_DELIMITER), ESCAPE_DELIMITER + hexCode(KEY_VALUE_DELIMITER)
67      },
68      // '.' must be custom-escaped (if no file extension is added to suffix,
69      // anything after a dot would be interpreted as file extension during parsing)
70      {
71        Character.toString('.'), ESCAPE_DELIMITER + hexCode('.')
72      },
73      // escape '%' to avoid confusion with URL escaping
74      {
75        Character.toString('%'), ESCAPE_DELIMITER + hexCode('%')
76      },
77      // '/' must be custom-escaped (dispatcher/webserver may filter out/misinterpret urls with unescaped slashes)
78      {
79        Character.toString('/'), ESCAPE_DELIMITER + hexCode('/')
80      },
81      // escape ':'
82      {
83        Character.toString(':'), ESCAPE_DELIMITER + hexCode(':')
84      },
85      // escape ' ' as well (singular problem occurred once)
86      {
87        Character.toString(' '), ESCAPE_DELIMITER + hexCode(' ')
88      }
89    };
90  
91    /**
92     * Escape special chars for suffix.
93     */
94    private static final CharSequenceTranslator ESCAPE_SPECIAL_CHARS = new LookupTranslator(SPECIAL_CHARS_MAPPING);
95  
96    /**
97     * Unesacpe special chars in suffix.
98     */
99    private static final CharSequenceTranslator UNESCAPE_SPECIAL_CHARS = new LookupTranslator(EntityArrays.invert(SPECIAL_CHARS_MAPPING));
100 
101   private UrlSuffixUtil() {
102     // static methods only
103   }
104 
105   /**
106    * Convert to hex code
107    * @param c char
108    * @return Hex code
109    */
110   public static String hexCode(char c) {
111     return Integer.toString(c, 16).toUpperCase();
112   }
113 
114   /**
115    * Encode resource path part
116    * @param relativePath Relative path
117    * @return Encodes path part
118    */
119   public static String encodeResourcePathPart(String relativePath) {
120     return ESCAPE_SPECIAL_CHARS.translate(relativePath);
121   }
122 
123   /**
124    * Decode resource path part
125    * @param suffixPart Suffix part
126    * @return Decoded path part
127    */
128   public static String decodeResourcePathPart(String suffixPart) {
129     return UNESCAPE_SPECIAL_CHARS.translate(suffixPart);
130   }
131 
132   /**
133    * Encode key value part
134    * @param string String
135    * @return Encoded string
136    */
137   public static String encodeKeyValuePart(String string) {
138     return ESCAPE_SPECIAL_CHARS.translate(string);
139   }
140 
141   /**
142    * Decode value
143    * @param suffixPart Suffix part
144    * @return Decoded value
145    */
146   public static String decodeValue(String suffixPart) {
147     // value is the part *after* KEY_VALUE_DELIMITER
148     String value = StringUtils.substringAfter(suffixPart, Character.toString(KEY_VALUE_DELIMITER));
149     return UNESCAPE_SPECIAL_CHARS.translate(value);
150   }
151 
152   /**
153    * Decode key
154    * @param suffixPart Suffix part
155    * @return Decoded key
156    */
157   public static String decodeKey(String suffixPart) {
158     // key is the part *before* KEY_VALUE_DELIMITER
159     String key = StringUtils.substringBefore(suffixPart, Character.toString(KEY_VALUE_DELIMITER));
160     return UNESCAPE_SPECIAL_CHARS.translate(key);
161   }
162 
163   /**
164    * Split suffix
165    * @param suffix Suffix
166    * @return Suffix parts
167    */
168   public static String[] splitSuffix(String suffix) {
169     String theSuffix = suffix;
170 
171     String[] parts;
172     if (StringUtils.isBlank(theSuffix)) {
173       // no suffix given - return empty list
174       parts = new String[0];
175     }
176     else {
177       // remove leading slash
178       if (theSuffix.startsWith(ESCAPED_SLASH)) {
179         theSuffix = theSuffix.substring(ESCAPED_SLASH.length());
180       }
181 
182       // remove file extension
183       theSuffix = StringUtils.substringBeforeLast(theSuffix, ".");
184 
185       // split the suffix to extract the paths of the selected components
186       parts = StringUtils.split(theSuffix, SUFFIX_PART_DELIMITER);
187     }
188 
189     return parts;
190   }
191 
192   /**
193    * Convert key value pair to map
194    * @param key Key
195    * @param value Value
196    * @return Map
197    */
198   public static Map<String, Object> keyValuePairAsMap(String key, Object value) {
199     Map<String, Object> paramMap = new HashMap<>();
200     paramMap.put(key, value);
201     return paramMap;
202   }
203 
204   /**
205    * @param resource the resource being addressed by the relative path
206    * @param baseResource the resource used as base to resolve the relative path
207    * @return the relative path (without leading slash)
208    */
209   public static String getRelativePath(Resource resource, Resource baseResource) {
210     if (baseResource == null) {
211       throw new IllegalArgumentException("the base resource for constructing relative path must not be null");
212     }
213     if (resource == null) {
214       throw new IllegalArgumentException("the resource for constructing relative path must not be null");
215     }
216     String absolutePath = resource.getPath();
217     String basePath = baseResource.getPath();
218 
219     if (absolutePath.equals(basePath)) {
220       // relative path for the root resource is "."
221       return ".";
222     }
223 
224     // be picky about resources not located beneath the base resource
225     if (!absolutePath.startsWith(basePath + "/")) {
226       throw new IllegalArgumentException("the resource " + resource + " is not a descendent of the base resource " + baseResource);
227     }
228 
229     // return relative path
230     return StringUtils.substringAfter(absolutePath, basePath + "/");
231   }
232 
233 }