001/**
002 *  Copyright (C) 2016 Gary Gregory. All rights reserved.
003 *
004 *  See the NOTICE.txt file distributed with this work for additional
005 *  information regarding copyright ownership.
006 *  
007 *  Licensed under the Apache License, Version 2.0 (the "License");
008 *  you may not use this file except in compliance with the License.
009 *  You may obtain a copy of the License at
010 *  
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *  
013 *  Unless required by applicable law or agreed to in writing, software
014 *  distributed under the License is distributed on an "AS IS" BASIS,
015 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 *  See the License for the specific language governing permissions and
017 *  limitations under the License.
018 */
019
020package com.garygregory.jcommander.converters.util;
021
022import java.util.Locale;
023
024import com.garygregory.jcommander.converters.AbstractBaseConverter;
025
026/**
027 * Converts a {@link String} into a {@link Locale}.
028 * <p>
029 * For a description of the format, see {@link Locale} and IETF BCP 47.
030 * </p>
031 * 
032 * <p>
033 * Example:
034 * </p>
035 * 
036 * <pre class="prettyprint">
037 * <code class="language-java">&#64;Parameter(names = { "--locale" }, converter = LocaleConverter.class)
038 * private Locale locale;</code>
039 * </pre>
040 * <p>
041 * 
042 * @see Locale
043 * 
044 * @since 1.0.0
045 * @author <a href="mailto:ggregory@garygregory.com">Gary Gregory</a>
046 */
047public class LocaleConverter extends AbstractBaseConverter<Locale> {
048
049    /**
050     * Constructs a converter.
051     * 
052     * @param optionName
053     *            The option name, may be null.
054     */
055    public LocaleConverter(final String optionName) {
056        super(optionName, Locale.class);
057    }
058
059    @Override
060    protected Locale convertImpl(final String value) {
061        // We do NOT use Locale.forLanguageTag(String) which does not fail on bad input.
062        return new Locale.Builder().setLanguageTag(value).build();
063    }
064
065}