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.CharsetDecoder;
22  import java.nio.charset.CodingErrorAction;
23  
24  /**
25   * <a href="CharsetDecoderUtil.java.html"><b><i>View Source</i></b></a>
26   *
27   * @author Shuyang Zhou
28   */
29  public class CharsetDecoderUtil {
30  
31      public static CharBuffer decode(String charsetName, byte[] byteArray) {
32          return decode(charsetName, ByteBuffer.wrap(byteArray));
33      }
34  
35      public static CharBuffer decode(
36          String charsetName, byte[] byteArray, int offset, int length) {
37  
38          return decode(charsetName, ByteBuffer.wrap(byteArray, offset, length));
39      }
40  
41      public static CharBuffer decode(String charsetName, ByteBuffer byteBuffer) {
42          try {
43              CharsetDecoder charsetDecoder = getCharsetDecoder(charsetName);
44  
45              return charsetDecoder.decode(byteBuffer);
46          }
47          catch (CharacterCodingException cce) {
48              throw new Error(cce);
49          }
50      }
51  
52      public static CharsetDecoder getCharsetDecoder(String charsetName) {
53          Charset charset = Charset.forName(charsetName);
54  
55          CharsetDecoder charsetDecoder = charset.newDecoder();
56  
57          charsetDecoder.onMalformedInput(CodingErrorAction.REPLACE);
58          charsetDecoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
59  
60          return charsetDecoder;
61      }
62  
63  }