View Javadoc
1   package org.exoplatform.wcm.webui.reader;
2   
3   import org.apache.commons.lang.StringEscapeUtils;
4   import org.apache.commons.lang.StringUtils;
5   import org.exoplatform.services.jcr.util.Text;
6   
7   public class ContentReader {
8     /**
9      * <p>
10     * Gets the content compatibility with XSS problems. This method will do
11     * </p>
12     * - Unescapes previously escaped jcr chars - Escapes the characters in a the content using HTML entities
13     * 
14     * @param content the node
15     * 
16     * @return the content compatibility with XSS
17     * 
18     */
19    public static String getXSSCompatibilityContent(String content) {
20      if (content != null)
21        content = StringEscapeUtils.escapeHtml(Text.unescapeIllegalJcrChars(content));
22      return content;
23    }
24    /**
25     * <p>
26     * Escapes the characters in a content using HTML entities.
27     * </p>
28     * 
29     * <p>
30     * For example:
31     * </p>
32     * <p>
33     * <code>"bread" and "butter"</code>
34     * </p>
35     * becomes:
36     * <p>
37     * <code>&amp;quot;bread&amp;quot; &amp;amp; &amp;quot;butter&amp;quot;</code>
38     * </p>
39     * 
40     * @param content to escape, may be null
41     * 
42     * @return a new escaped content, null if null string input
43     * 
44     */
45    public static String getEscapeHtmlContent(String content) {
46      if (content != null) {
47        content = StringEscapeUtils.unescapeHtml(content);
48        content = StringEscapeUtils.escapeHtml(content);
49      }
50      return content;
51    }
52    /**
53     * <p>
54     * Unescapes previously escaped jcr chars.
55     * </p>
56     * 
57     * @param content the content to unescape
58     * 
59     * @return the unescaped content
60     * 
61     */
62    public static String getUnescapeIllegalJcrContent(String content) {
63      if (content != null)
64        content = Text.unescapeIllegalJcrChars(content);
65      return content;
66    }
67  
68    /**
69     * Escape html avoid XSS
70     * @param value
71     * @return
72     */
73    public static String simpleEscapeHtml(String value) {
74      if (StringUtils.isEmpty(value)) return StringUtils.EMPTY;
75      int length = value.length();
76      StringBuilder result = new StringBuilder((int) (length * 1.5));
77      for (int i = 0; i < length; i++) {
78        char ch = value.charAt(i);
79        switch (ch) {
80          case '<':
81            result.append("&lt;");
82            break;
83          case '>':
84            result.append("&gt;");
85            break;
86          default:
87            result.append(ch);
88            break;
89        }
90      }
91      return result.toString();
92    }
93  }