pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / highlighter / src / java / org / apache / lucene / search / highlight / SimpleHTMLEncoder.java
1 package org.apache.lucene.search.highlight;
2 /**
3  * Copyright 2005 The Apache Software Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 /**
19  * Simple {@link Encoder} implementation to escape text for HTML output
20  *
21  */
22 public class SimpleHTMLEncoder implements Encoder
23 {
24         public SimpleHTMLEncoder()
25         {
26         }
27
28         public String encodeText(String originalText)
29         {
30                 return htmlEncode(originalText);
31         }
32         
33         /**
34          * Encode string into HTML
35          */
36         public final static String htmlEncode(String plainText) 
37         {
38                 if (plainText == null || plainText.length() == 0)
39                 {
40                         return "";
41                 }
42
43                 StringBuilder result = new StringBuilder(plainText.length());
44
45                 for (int index=0; index<plainText.length(); index++) 
46                 {
47                         char ch = plainText.charAt(index);
48
49                         switch (ch) 
50                         {
51                         case '"':
52                                 result.append("&quot;");
53                                 break;
54
55                         case '&':
56                                 result.append("&amp;");
57                                 break;
58
59                         case '<':
60                                 result.append("&lt;");
61                                 break;
62
63                         case '>':
64                                 result.append("&gt;");
65                                 break;
66
67                         default:
68                                    if (ch < 128) 
69                                    {
70                                    result.append(ch);
71                                } 
72                                    else 
73                                {
74                                    result.append("&#").append((int)ch).append(";");
75                                }
76                         }
77                 }
78
79                 return result.toString();
80         }
81 }