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.CharsetEncoder;
022    import java.nio.charset.CodingErrorAction;
023    
024    /**
025     * @author Shuyang Zhou
026     */
027    public class CharsetEncoderUtil {
028    
029            public static ByteBuffer encode(
030                    String charsetName, char[] chars, int offset, int length) {
031    
032                    return encode(charsetName, CharBuffer.wrap(chars, offset, length));
033            }
034    
035            public static ByteBuffer encode(String charsetName, CharBuffer charBuffer) {
036                    try {
037                            CharsetEncoder charsetEncoder = getCharsetEncoder(charsetName);
038    
039                            return charsetEncoder.encode(charBuffer);
040                    }
041                    catch (CharacterCodingException cce) {
042                            throw new Error(cce);
043                    }
044            }
045    
046            public static ByteBuffer encode(String charsetName, String string) {
047                    return encode(charsetName, CharBuffer.wrap(string));
048            }
049    
050            public static CharsetEncoder getCharsetEncoder(String charsetName) {
051                    Charset charset = Charset.forName(charsetName);
052    
053                    CharsetEncoder charsetEncoder = charset.newEncoder();
054    
055                    charsetEncoder.onMalformedInput(CodingErrorAction.REPLACE);
056                    charsetEncoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
057    
058                    return charsetEncoder;
059            }
060    
061    }