01: /*
02: * @(#)$Id: EncoderFactory.java,v 1.3 2005/09/10 19:07:33 kohsuke Exp $
03: */
04:
05: /*
06: * The contents of this file are subject to the terms
07: * of the Common Development and Distribution License
08: * (the "License"). You may not use this file except
09: * in compliance with the License.
10: *
11: * You can obtain a copy of the license at
12: * https://jwsdp.dev.java.net/CDDLv1.0.html
13: * See the License for the specific language governing
14: * permissions and limitations under the License.
15: *
16: * When distributing Covered Code, include this CDDL
17: * HEADER in each file and include the License file at
18: * https://jwsdp.dev.java.net/CDDLv1.0.html If applicable,
19: * add the following below this CDDL HEADER, with the
20: * fields enclosed by brackets "[]" replaced with your
21: * own identifying information: Portions Copyright [yyyy]
22: * [name of copyright owner]
23: */
24: package com.sun.codemodel.util;
25:
26: import java.lang.reflect.Constructor;
27: import java.nio.charset.Charset;
28: import java.nio.charset.CharsetEncoder;
29:
30: /**
31: * Creates {@link CharsetEncoder} from a charset name.
32: *
33: * Fixes a MS1252 handling bug in JDK1.4.2.
34: *
35: * @author
36: * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
37: */
38: public class EncoderFactory {
39: public static CharsetEncoder createEncoder(String encodin) {
40: Charset cs = Charset.forName(System
41: .getProperty("file.encoding"));
42: CharsetEncoder encoder = cs.newEncoder();
43:
44: if (cs.getClass().getName().equals("sun.nio.cs.MS1252")) {
45: try {
46: // at least JDK1.4.2_01 has a bug in MS1252 encoder.
47: // specifically, it returns true for any character.
48: // return a correct encoder to workaround this problem
49:
50: // statically binding to MS1252Encoder will cause a Link error
51: // (at least in IBM JDK1.4.1)
52: Class ms1252encoder = Class
53: .forName("com.sun.codemodel.util.MS1252Encoder");
54: Constructor c = ms1252encoder
55: .getConstructor(new Class[] { Charset.class });
56: return (CharsetEncoder) c
57: .newInstance(new Object[] { cs });
58: } catch (Throwable t) {
59: // if something funny happens, ignore it and fall back to
60: // a broken MS1252 encoder. It's probably still better
61: // than choking here.
62: return encoder;
63: }
64: }
65:
66: return encoder;
67: }
68: }
|