KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > taglibs > standard > lang > jpath > encoding > HtmlEncoder


1 /*
2  * Copyright 1999,2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.taglibs.standard.lang.jpath.encoding;
18
19 /**
20  *<p>The <tt>HtmlEncoder</tt> provides methods to encode output into html
21  */

22 public class HtmlEncoder {
23
24     private static final String JavaDoc[] htmlCode = new String JavaDoc[256];
25
26     static {
27                 for (int i = 0; i < 10; i++) {
28                         htmlCode[i] = "&#00" + i + ";";
29                 }
30
31                 for (int i = 10; i < 32; i++) {
32                         htmlCode[i] = "&#0" + i + ";";
33                 }
34
35                 for (int i = 32; i < 128; i++) {
36                         htmlCode[i] = String.valueOf((char)i);
37                 }
38
39                 // Special characters
40
htmlCode['\n'] = "<BR>\n";
41                 htmlCode['\"'] = "&quot;"; // double quote
42
htmlCode['&'] = "&amp;"; // ampersand
43
htmlCode['<'] = "&lt;"; // lower than
44
htmlCode['>'] = "&gt;"; // greater than
45

46                 for (int i = 128; i < 256; i++) {
47                         htmlCode[i] = "&#" + i + ";";
48                 }
49     }
50
51     /**
52      * <p>Encode the given text into html.</p>
53      *
54      * @param string the text to encode
55      * @return the encoded string
56      *
57      */

58     public static String JavaDoc encode(String JavaDoc string) {
59                 int n = string.length();
60                 char character;
61                 StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
62         // loop over all the characters of the String.
63
for (int i = 0; i < n; i++) {
64                         character = string.charAt(i);
65                         // the Htmlcode of these characters are added to a StringBuffer one by one
66
try {
67                                 buffer.append(htmlCode[character]);
68                         }
69                         catch(ArrayIndexOutOfBoundsException JavaDoc aioobe) {
70                                 buffer.append(character);
71                         }
72             }
73         return buffer.toString();
74     }
75
76 }
77
78
Popular Tags