01: /*
02: * Enhydra Java Application Server Project
03: *
04: * The contents of this file are subject to the Enhydra Public License
05: * Version 1.1 (the "License"); you may not use this file except in
06: * compliance with the License. You may obtain a copy of the License on
07: * the Enhydra web site ( http://www.enhydra.org/ ).
08: *
09: * Software distributed under the License is distributed on an "AS IS"
10: * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11: * the License for the specific terms governing rights and limitations
12: * under the License.
13: *
14: * The Initial Developer of the Enhydra Application Server is Lutris
15: * Technologies, Inc. The Enhydra Application Server and portions created
16: * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17: * All Rights Reserved.
18: *
19: * Contributor(s):
20: *
21: * $Id: HtmlEncoder.java,v 1.2 2006-06-15 13:47:01 sinisa Exp $
22: */
23:
24: package com.lutris.util;
25:
26: /**
27: * This class contains a utility method for encoding a
28: * <code>String</code> so that it may be safely embedded within
29: * a HTML document without affecting the formatting of the
30: * document.<p>
31: *
32: * The following characters are encoded:
33: * <p>
34: * <ul>
35: * <li> <
36: * <li> >
37: * <li> &
38: * <li> '
39: * <li> "
40: * <li> \
41: * <li> …
42: * </ul>
43: *
44: * @author Kyle Clark
45: */
46: public final class HtmlEncoder {
47:
48: /**
49: * Translates a string into a HTML safe format.
50: *
51: * @param s the string to encode
52: * @return the encoded string
53: */
54: public static String encode(String s) {
55: char[] htmlChars = s.toCharArray();
56: StringBuffer encodedHtml = new StringBuffer();
57: for (int i = 0; i < htmlChars.length; i++) {
58: switch (htmlChars[i]) {
59: case '<':
60: encodedHtml.append("<");
61: break;
62: case '>':
63: encodedHtml.append(">");
64: break;
65: case '&':
66: encodedHtml.append("&");
67: break;
68: case '\'':
69: encodedHtml.append("'");
70: break;
71: case '"':
72: encodedHtml.append(""");
73: break;
74: case '\\':
75: encodedHtml.append("\");
76: break;
77: case (char) 133:
78: encodedHtml.append("…");
79: break;
80: default:
81: encodedHtml.append(htmlChars[i]);
82: break;
83: }
84: }
85: return encodedHtml.toString();
86: }
87: }
|