View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.lang3;
19  
20  import java.nio.charset.Charset;
21  import java.nio.charset.UnsupportedCharsetException;
22  
23  /**
24   * Internal use only.
25   * <p>
26   * Provides utilities for {@link Charset}.
27   * </p>
28   * <p>
29   * Package private since Apache Commons IO already provides a Charsets because {@link Charset} is in
30   * {@code java.nio.charset}.
31   * </p>
32   *
33   * @since 3.10
34   */
35  final class Charsets {
36  
37      /**
38       * Returns the given {@code charset} or the default Charset if {@code charset} is null.
39       *
40       * @param charset A Charset or null.
41       * @return The given {@code charset} or the default Charset if {@code charset} is null.
42       */
43      static Charset toCharset(final Charset charset) {
44          return charset == null ? Charset.defaultCharset() : charset;
45      }
46  
47      /**
48       * Returns the given {@code charset} or the default Charset if {@code charset} is null.
49       *
50       * @param charsetName A Charset or null.
51       * @return The given {@code charset} or the default Charset if {@code charset} is null.
52       * @throws UnsupportedCharsetException Thrown if no support for the named charset is available in this instance of the Java virtual machine.
53       */
54      static Charset toCharset(final String charsetName) {
55          return charsetName == null ? Charset.defaultCharset() : Charset.forName(charsetName);
56      }
57  
58      /**
59       * Returns the given {@code charset} or the default Charset if {@code charset} is null.
60       *
61       * @param charsetName A Charset or null.
62       * @return The given {@code charset} or the default Charset if {@code charset} is null.
63       */
64      static String toCharsetName(final String charsetName) {
65          return charsetName == null ? Charset.defaultCharset().name() : charsetName;
66      }
67  
68  }