1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
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  }