1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.kernel.nio.charset;
16  
17  import java.nio.ByteBuffer;
18  import java.nio.CharBuffer;
19  import java.nio.charset.CharacterCodingException;
20  import java.nio.charset.Charset;
21  import java.nio.charset.CharsetEncoder;
22  import java.nio.charset.CodingErrorAction;
23  
24  /**
25   * <a href="CharsetEncoderUtil.java.html"><b><i>View Source</i></b></a>
26   *
27   * @author Shuyang Zhou
28   */
29  public class CharsetEncoderUtil {
30  
31      public static ByteBuffer encode(
32          String charsetName, char[] charArray, int offset, int length) {
33  
34          return encode(charsetName, CharBuffer.wrap(charArray, offset, length));
35      }
36  
37      public static ByteBuffer encode(String charsetName, CharBuffer charBuffer) {
38          try {
39              CharsetEncoder charsetEncoder = getCharsetEncoder(charsetName);
40  
41              return charsetEncoder.encode(charBuffer);
42          }
43          catch (CharacterCodingException cce) {
44              throw new Error(cce);
45          }
46      }
47  
48      public static ByteBuffer encode(String charsetName, String string) {
49          return encode(charsetName, CharBuffer.wrap(string));
50      }
51  
52      public static CharsetEncoder getCharsetEncoder(String charsetName) {
53          Charset charset = Charset.forName(charsetName);
54  
55          CharsetEncoder charsetEncoder = charset.newEncoder();
56  
57          charsetEncoder.onMalformedInput(CodingErrorAction.REPLACE);
58          charsetEncoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
59  
60          return charsetEncoder;
61      }
62  
63  }