Parse the given localeString into a java.util.Locale : Locale « I18N « Java






Parse the given localeString into a java.util.Locale

   
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;

/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

public class Main {

  /**
   * Parse the given localeString into a {@link java.util.Locale}.
   * 
   * This is the inverse operation of
   * {@link java.util.Locale#toString Locale's toString}.
   * 
   * @param localeString
   *          the locale string
   * @return a corresponding Locale instance
   */
  public static Locale parseLocaleString(String localeString) {
    String[] parts = tokenizeToStringArray(localeString, "_ ", false, false);
    String language = (parts.length > 0 ? parts[0] : "");
    String country = (parts.length > 1 ? parts[1] : "");
    String variant = "";
    if (parts.length >= 2) {
      // There is definitely a variant, and it is everything after the country
      // code sans the separator between the country code and the variant.
      int endIndexOfCountryCode = localeString.indexOf(country) + country.length();
      // Strip off any leading '_' and whitespace, what's left is the variant.
      variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));
      if (variant.startsWith("_")) {
        variant = trimLeadingCharacter(variant, '_');
      }
    }
    return (language.length() > 0 ? new Locale(language, country, variant) : null);
  }

  /**
   * Tokenize the given String into a String array via a StringTokenizer.
   * 
   * The given delimiters string is supposed to consist of any number of
   * delimiter characters. Each of those characters can be used to separate
   * tokens. A delimiter is always a single character; for multi-character
   * delimiters, consider using delimitedListToStringArray
   * 
   * @param str
   *          the String to tokenize
   * @param delimiters
   *          the delimiter characters, assembled as String (each of those
   *          characters is individually considered as delimiter)
   * @param trimTokens
   *          trim the tokens via String's trim
   * @param ignoreEmptyTokens
   *          omit empty tokens from the result array (only applies to tokens
   *          that are empty after trimming; StringTokenizer will not consider
   *          subsequent delimiters as token in the first place).
   * @return an array of the tokens (null if the input String was null)
   */
  public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens,
      boolean ignoreEmptyTokens) {
    if (str == null) {
      return null;
    }
    StringTokenizer st = new StringTokenizer(str, delimiters);
    List<String> tokens = new ArrayList<String>();
    while (st.hasMoreTokens()) {
      String token = st.nextToken();
      if (trimTokens) {
        token = token.trim();
      }
      if (!ignoreEmptyTokens || token.length() > 0) {
        tokens.add(token);
      }
    }
    return tokens.toArray(new String[tokens.size()]);
  }

  /**
   * Trim leading whitespace from the given String.
   * 
   * @param str
   *          the string to check
   * @return the trimmed String
   * @see java.lang.Character#isWhitespace(char)
   */
  public static String trimLeadingWhitespace(String str) {
    return trimLeadingCharacter(str, CharacterChecker.WHITESPACE);
  }

  /**
   * Trim all occurences of the supplied leading character from the given
   * String.
   * 
   * @param str
   *          the string to check
   * @param leadingCharacter
   *          the leading character to be trimmed
   * @return the trimmed String
   */
  public static String trimLeadingCharacter(String str, final char leadingCharacter) {
    return trimLeadingCharacter(str, new CharacterChecker() {
      public boolean isCharacterLegal(char character) {
        return character == leadingCharacter;
      }
    });
  }

  /**
   * Trim all occurences of the supplied leading character from the given
   * String.
   * 
   * @param str
   *          the string to check
   * @param checker
   *          the character checker
   * @return the trimmed String
   */
  public static String trimLeadingCharacter(String str, CharacterChecker checker) {
    if (hasLength(str) == false) {
      return str;
    }

    if (checker == null)
      throw new IllegalArgumentException("Null character checker");

    StringBuffer buf = new StringBuffer(str);
    while (buf.length() > 0 && checker.isCharacterLegal(buf.charAt(0))) {
      buf.deleteCharAt(0);
    }
    return buf.toString();
  }

  /**
   * Check that the given string param is neither null nor of length 0.
   * 
   * @param string
   *          the string
   * @return true if the String is not null and has length
   */
  public static boolean hasLength(String string) {
    return (string != null && string.length() > 0);
  }

}

   
    
    
  








Related examples in the same category

1.List Locales from Locale.getAvailableLocales()List Locales from Locale.getAvailableLocales()
2.List all Locale from SimpleDateFormatList all Locale from SimpleDateFormat
3.Locale Constant
4.Country Language CodesCountry Language Codes
5.Get Days Of The Week for different localeGet Days Of The Week for different locale
6.Get Display Country for default localeGet Display Country for default locale
7.Get ISO3 Language for default localeGet ISO3 Language for default locale
8.Get Display Name for default localeGet Display Name for default locale
9.Get Display Variant for default localeGet Display Variant for default locale
10.Get the 2-letter country code; may be equal to ""
11.List Locale OrientationList Locale Orientation
12.Get localized name suitable for display to the user
13.Setting the Default Locale on the command line
14.Set language and country code on the command line
15.Change the default locale is to call Locale.setDefault():
16.Set the default locale to pre-defined locale
17.Set the default locale to custom locale
18.format date for a Locale
19.Get a list of country names
20.Set only language code on the command line
21.Set a default Locale
22.Disable localization
23.Set of convenience routines for internationalized code
24.Print the default locale
25.Change the default locale
26.iso639-2-language-code.csv
27.iso3166-country-codes.csv
28.Converts a String to a Locale
29.Converts the double value to locale-independent string representation
30.Calculate the postfix to append to a filename to load the correct single filename for that Locale.
31.Calculate the postfixes along the search path from the base bundle to the bundle specified by baseName and locale.
32.Concat postfix to the name. Take care of existing filename extension.
33.Convert a string based locale into a Locale Object
34.Obtains an unmodifiable set of installed locales.
35.Obtains the list of languages supported for a given country.
36.Obtains the list of locales to search through when performing a locale search.
37.Returns the parent locale of a given locale.
38.This program demonstrates collating strings under various locales.This program demonstrates collating strings under various locales.
39.This program demonstrates formatting dates under various locales.This program demonstrates formatting dates under various locales.
40.This program demonstrates formatting numbers under various locales.This program demonstrates formatting numbers under various locales.
41.Builds a Locale instance from the passed string.
42.Utility class providing methods to access the Locale of the current thread and to get Localised strings.