001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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[] bytes) {
030                    return decode(charsetName, ByteBuffer.wrap(bytes));
031            }
032    
033            public static CharBuffer decode(
034                    String charsetName, byte[] bytes, int offset, int length) {
035    
036                    return decode(charsetName, ByteBuffer.wrap(bytes, 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    }