KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > util > transformers > UnicodeEscaper


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.util.transformers;
11
12 import java.io.Reader JavaDoc;
13 import java.io.Writer JavaDoc;
14
15 import org.mmbase.util.logging.*;
16
17 /**
18  * To escape from and to 'java' like unicode escaping. That is \\u<4 hex digits>.
19  *
20  * @author Michiel Meeuwissen
21  * @since MMBase-1.7.2
22  * @version $Id: UnicodeEscaper.java,v 1.3 2006/04/19 21:10:58 michiel Exp $
23  */

24
25 public class UnicodeEscaper extends ReaderTransformer implements CharTransformer {
26     private static final Logger log = Logging.getLoggerInstance(UnicodeEscaper.class);
27
28     public Writer JavaDoc transform(Reader JavaDoc r, Writer JavaDoc w) {
29         try {
30             while (true) {
31                 int c = r.read();
32                 if (c == -1) break;
33                 if (c > 127) {
34                     String JavaDoc hex = Integer.toHexString(c);
35                     int i = hex.length();
36                     w.write("\\u");
37                     while (i < 4) {
38                         w.write('0'); i++;
39                     }
40                     w.write(hex);
41                 } else {
42                     w.write(c);
43                 }
44             }
45         } catch (Exception JavaDoc e) {
46             log.error(e.toString());
47         }
48         return w;
49     }
50
51     public Writer JavaDoc transformBack(Reader JavaDoc r, Writer JavaDoc w) {
52         try {
53             while (true) {
54                 int c = r.read();
55                 if (c == -1) break;
56                 if (c == '\\') {
57                     c = r.read();
58                     if (c == -1) { w.write('\\'); break; }
59                     if (c == 'u') {
60                         // read 4 hexadecimal digits.
61
StringBuffer JavaDoc hex = new StringBuffer JavaDoc(4);
62                         while (c != -1 && hex.length() < 4) {
63                             c = r.read();
64                             hex.append((char) c);
65                         }
66                         w.write((char) Integer.parseInt(hex.toString(), 16));
67                     } else {
68                         w.write("\\" + (char) c);
69                     }
70                 } else {
71                     w.write((char) c);
72                 }
73             }
74         } catch (java.io.IOException JavaDoc e) {
75             log.error(e.toString());
76         }
77         return w;
78     }
79
80     public String JavaDoc toString() {
81         return "UnicodeEscaper";
82     }
83 }
84
Popular Tags