01: /*
02:
03: This software is OSI Certified Open Source Software.
04: OSI Certified is a certification mark of the Open Source Initiative.
05:
06: The license (Mozilla version 1.0) can be read at the MMBase site.
07: See http://www.MMBase.org/license
08:
09: */
10: package org.mmbase.util.transformers;
11:
12: import java.io.Reader;
13: import java.io.Writer;
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.4 2007/08/04 08:09:14 michiel Exp $
23: */
24:
25: public class UnicodeEscaper extends ReaderTransformer implements
26: CharTransformer {
27: private static final Logger log = Logging
28: .getLoggerInstance(UnicodeEscaper.class);
29:
30: public Writer transform(Reader r, Writer w) {
31: try {
32: while (true) {
33: int c = r.read();
34: if (c == -1)
35: break;
36: if (c > 127) {
37: String hex = Integer.toHexString(c);
38: int i = hex.length();
39: w.write("\\u");
40: while (i < 4) {
41: w.write('0');
42: i++;
43: }
44: w.write(hex);
45: } else {
46: w.write(c);
47: }
48: }
49: } catch (Exception e) {
50: log.error(e.toString());
51: }
52: return w;
53: }
54:
55: public Writer transformBack(Reader r, Writer w) {
56: try {
57: while (true) {
58: int c = r.read();
59: if (c == -1)
60: break;
61: if (c == '\\') {
62: c = r.read();
63: if (c == -1) {
64: w.write('\\');
65: break;
66: }
67: if (c == 'u') {
68: // read 4 hexadecimal digits.
69: StringBuilder hex = new StringBuilder(4);
70: while (c != -1 && hex.length() < 4) {
71: c = r.read();
72: hex.append((char) c);
73: }
74: w.write((char) Integer.parseInt(hex.toString(),
75: 16));
76: } else {
77: w.write("\\" + (char) c);
78: }
79: } else {
80: w.write((char) c);
81: }
82: }
83: } catch (java.io.IOException e) {
84: log.error(e.toString());
85: }
86: return w;
87: }
88:
89: public String toString() {
90: return "UnicodeEscaper";
91: }
92: }
|