01: /*
02: * The contents of this file are subject to the terms
03: * of the Common Development and Distribution License
04: * (the "License"). You may not use this file except
05: * in compliance with the License.
06: *
07: * You can obtain a copy of the license at
08: * https://jwsdp.dev.java.net/CDDLv1.0.html
09: * See the License for the specific language governing
10: * permissions and limitations under the License.
11: *
12: * When distributing Covered Code, include this CDDL
13: * HEADER in each file and include the License file at
14: * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable,
15: * add the following below this CDDL HEADER, with the
16: * fields enclosed by brackets "[]" replaced with your
17: * own identifying information: Portions Copyright [yyyy]
18: * [name of copyright owner]
19: */
20: package com.sun.codemodel.util;
21:
22: import java.io.FilterWriter;
23: import java.io.IOException;
24: import java.io.Writer;
25:
26: /**
27: * {@link Writer} that escapes non US-ASCII characters into
28: * Java Unicode escape \\uXXXX.
29: *
30: * This process is necessary if the method names or field names
31: * contain non US-ASCII characters.
32: *
33: * @author
34: * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
35: */
36: public class UnicodeEscapeWriter extends FilterWriter {
37:
38: public UnicodeEscapeWriter(Writer next) {
39: super (next);
40: }
41:
42: public final void write(int ch) throws IOException {
43: if (!requireEscaping(ch))
44: out.write(ch);
45: else {
46: // need to escape
47: out.write("\\u");
48: String s = Integer.toHexString(ch);
49: for (int i = s.length(); i < 4; i++)
50: out.write('0');
51: out.write(s);
52: }
53: }
54:
55: /**
56: * Can be overrided. Return true if the character
57: * needs to be escaped.
58: */
59: protected boolean requireEscaping(int ch) {
60: if (ch >= 128)
61: return true;
62:
63: // control characters
64: if (ch < 0x20 && " \t\r\n".indexOf(ch) == -1)
65: return true;
66:
67: return false;
68: }
69:
70: public final void write(char[] buf, int off, int len)
71: throws IOException {
72: for (int i = 0; i < len; i++)
73: write(buf[off + i]);
74: }
75:
76: public final void write(char[] buf) throws IOException {
77: write(buf, 0, buf.length);
78: }
79:
80: public final void write(String buf, int off, int len)
81: throws IOException {
82: write(buf.toCharArray(), off, len);
83: }
84:
85: public final void write(String buf) throws IOException {
86: write(buf.toCharArray(), 0, buf.length());
87: }
88:
89: }
|