001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.kernel.nio.charset;
016    
017    import java.nio.ByteBuffer;
018    import java.nio.CharBuffer;
019    import java.nio.charset.CharacterCodingException;
020    import java.nio.charset.Charset;
021    import java.nio.charset.CharsetDecoder;
022    import java.nio.charset.CodingErrorAction;
023    
024    /**
025     * @author Shuyang Zhou
026     */
027    public class CharsetDecoderUtil {
028    
029            public static CharBuffer decode(String charsetName, byte[] byteArray) {
030                    return decode(charsetName, ByteBuffer.wrap(byteArray));
031            }
032    
033            public static CharBuffer decode(
034                    String charsetName, byte[] byteArray, int offset, int length) {
035    
036                    return decode(charsetName, ByteBuffer.wrap(byteArray, offset, length));
037            }
038    
039            public static CharBuffer decode(String charsetName, ByteBuffer byteBuffer) {
040                    try {
041                            CharsetDecoder charsetDecoder = getCharsetDecoder(charsetName);
042    
043                            return charsetDecoder.decode(byteBuffer);
044                    }
045                    catch (CharacterCodingException cce) {
046                            throw new Error(cce);
047                    }
048            }
049    
050            public static CharsetDecoder getCharsetDecoder(String charsetName) {
051                    Charset charset = Charset.forName(charsetName);
052    
053                    CharsetDecoder charsetDecoder = charset.newDecoder();
054    
055                    charsetDecoder.onMalformedInput(CodingErrorAction.REPLACE);
056                    charsetDecoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
057    
058                    return charsetDecoder;
059            }
060    
061    }