001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017package org.apache.logging.log4j.core.helpers;
018
019import java.nio.charset.Charset;
020
021import org.apache.logging.log4j.status.StatusLogger;
022
023/**
024 * Charset utilities.
025 */
026public final class Charsets {
027
028    /**
029     * UTF-8 Charset.
030     */
031    public static final Charset UTF_8 = Charset.forName("UTF-8");
032
033    /**
034     * Returns a Charset, if possible the Charset for the specified {@code charsetName}, otherwise (if the specified
035     * {@code charsetName} is {@code null} or not supported) this method returns the platform default Charset.
036     *
037     * @param charsetName
038     *            name of the preferred charset or {@code null}
039     * @return a Charset, not null.
040     */
041    public static Charset getSupportedCharset(final String charsetName) {
042        return getSupportedCharset(charsetName, Charset.defaultCharset());
043    }
044
045    /**
046     * Returns a Charset, if possible the Charset for the specified {@code charsetName}, otherwise (if the specified
047     * {@code charsetName} is {@code null} or not supported) this method returns the platform default Charset.
048     *
049     * @param charsetName
050     *            name of the preferred charset or {@code null}
051     * @param defaultCharset
052     *            returned if {@code charsetName} is null or is not supported.
053     * @return a Charset, never null.
054     */
055    public static Charset getSupportedCharset(final String charsetName, final Charset defaultCharset) {
056        Charset charset = null;
057        if (charsetName != null && Charset.isSupported(charsetName)) {
058            charset = Charset.forName(charsetName);
059        }
060        if (charset == null) {
061            charset = defaultCharset;
062            if (charsetName != null) {
063                StatusLogger.getLogger().error(
064                        "Charset " + charsetName + " is not supported for layout, using " + charset.displayName());
065            }
066        }
067        return charset;
068    }
069
070    private Charsets() {
071    }
072
073}