01: package org.romaframework.aspect.view.echo2.util;
02:
03: import java.util.Hashtable;
04:
05: import au.id.jericho.lib.html.Source;
06: import au.id.jericho.lib.html.TextExtractor;
07:
08: /**
09: * Converts String in HTML markup replacing charachters,
10: *
11: * @author Giordano Maestro(giordano.maestro@assetdata.it) 12/nov/07
12: *
13: */
14:
15: public class HtmlEncoder {
16:
17: /**
18: * The list of characters to convert and convertion
19: */
20: private static final String[] ENTITIES = { ">", ">", "<",
21: "<", "&", "&", "\"", """, "'", "'", "\\",
22: "\", "\u00a9", "©", "\u00ae", "®" };
23:
24: private static Hashtable<String, String> entityTableEncode = null;
25:
26: /**
27: * Create an hashTable from ENTITIES
28: *
29: */
30: protected static synchronized void buildEntityTables() {
31: entityTableEncode = new Hashtable<String, String>(
32: ENTITIES.length);
33:
34: for (int i = 0; i < ENTITIES.length; i += 2) {
35: if (!entityTableEncode.containsKey(ENTITIES[i])) {
36: entityTableEncode.put(ENTITIES[i], ENTITIES[i + 1]);
37: }
38: }
39: }
40:
41: /**
42: *
43: * Converts a String to HTML by converting all special characters to
44: * HTML-entities.
45: *
46: * @param s The String to convert
47: * @return
48: */
49: public static String encode(String s) {
50: if (entityTableEncode == null) {
51: buildEntityTables();
52: }
53: if (s == null) {
54: return "";
55: }
56: StringBuffer sb = new StringBuffer(s.length() * 2);
57: char ch;
58: for (int i = 0; i < s.length(); ++i) {
59: ch = s.charAt(i);
60: if ((ch >= 63 && ch <= 90) || (ch >= 97 && ch <= 122)
61: || (ch == ' ')) {
62: sb.append(ch);
63: } else if (ch == '\n') {
64: sb.append("\n");
65: } else {
66: String chEnc = (String) entityTableEncode.get(ch);
67: if (chEnc != null) {
68: sb.append(chEnc);
69: } else {
70: // Not 7 Bit use the unicode system
71: sb.append("&#");
72: sb.append(new Integer(ch).toString());
73: sb.append(';');
74: }
75: }
76: }
77: return sb.toString();
78: }
79:
80: /**
81: * Decode HTML Markup in a java String
82: *
83: * @param toDecode
84: * @return
85: */
86: public static String decode(String toDecode) {
87: Source source = new Source(toDecode);
88: TextExtractor extractor = source.getTextExtractor();
89: return extractor.toString();
90: }
91:
92: }
|