1 /* 2 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /* 27 * @(#)$Id: EncoderFactory.java,v 1.3 2005/09/10 19:07:33 kohsuke Exp $ 28 */ 29 package com.sun.codemodel.internal.util; 30 31 import java.lang.reflect.Constructor; 32 import java.nio.charset.Charset; 33 import java.nio.charset.CharsetEncoder; 34 35 /** 36 * Creates {@link CharsetEncoder} from a charset name. 37 * 38 * Fixes a MS1252 handling bug in JDK1.4.2. 39 * 40 * @author 41 * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) 42 */ 43 public class EncoderFactory { 44 45 public static CharsetEncoder createEncoder( String encodin ) { 46 Charset cs = Charset.forName(System.getProperty("file.encoding")); 47 CharsetEncoder encoder = cs.newEncoder(); 48 49 if( cs.getClass().getName().equals("sun.nio.cs.MS1252") ) { 50 try { 51 // at least JDK1.4.2_01 has a bug in MS1252 encoder. 52 // specifically, it returns true for any character. 53 // return a correct encoder to workaround this problem 54 55 // statically binding to MS1252Encoder will cause a Link error 56 // (at least in IBM JDK1.4.1) 57 @SuppressWarnings("unchecked") 58 Class<? extends CharsetEncoder> ms1252encoder = (Class<? extends CharsetEncoder>) Class.forName("com.sun.codemodel.internal.util.MS1252Encoder"); 59 Constructor<? extends CharsetEncoder> c = ms1252encoder.getConstructor(new Class[]{ 60 Charset.class 61 }); 62 return c.newInstance(new Object[]{cs}); 63 } catch( Throwable t ) { 64 // if something funny happens, ignore it and fall back to 65 // a broken MS1252 encoder. It's probably still better 66 // than choking here. 67 return encoder; 68 } 69 } 70 71 return encoder; 72 } 73 }