Example usage for java.util Locale Locale

List of usage examples for java.util Locale Locale

Introduction

In this page you can find the example usage for java.util Locale Locale.

Prototype

public Locale(String language, String country, String variant) 

Source Link

Document

Construct a locale from language, country and variant.

Usage

From source file:architecture.common.util.LocaleUtils.java

/**
 * Converts a locale string like "en", "en_US" or "en_US_win" to a Java
 * locale object. If the conversion fails, null is returned.
 *
 * @param localeCode/*from w  w  w. j  a v  a 2  s . co  m*/
 *            the locale code for a Java locale. See the
 *            {@link java.util.Locale} class for more details.
 * @return The Java Locale that matches the locale code, or <tt>null</tt>.
 */
public static Locale localeCodeToLocale(String localeCode) {
    Locale locale = null;
    if (localeCode != null) {
        String language = null;
        String country = null;
        String variant = null;
        StringTokenizer tokenizer = new StringTokenizer(localeCode, "_");
        if (tokenizer.hasMoreTokens()) {
            language = tokenizer.nextToken();
            if (tokenizer.hasMoreTokens()) {
                country = tokenizer.nextToken();
                if (tokenizer.hasMoreTokens()) {
                    variant = tokenizer.nextToken();
                }
            }
        }
        locale = new Locale(language, ((country != null) ? country : ""), ((variant != null) ? variant : ""));
    }
    return locale;
}

From source file:es.tunelator.Start.java

/**
 * Tests if the default locale has specific support
 *//* w w w  . j av a2s. co  m*/
private static boolean isLocaleSupported() {
    Locale defaultLocale = Locale.getDefault();
    String[] supportedLangs = Constants.SUPPORTED_LANGS;
    for (int i = 0; i < supportedLangs.length; i++) {
        if (defaultLocale.getLanguage().equals(new Locale(supportedLangs[i], "", "").getLanguage())) {
            return true;
        }
    }
    return false;
}

From source file:Main.java

/**
 * Parse the given {@code localeString} value into a {@link Locale}.
 * <p>This is the inverse operation of {@link Locale#toString Locale's toString}.
 * @param localeString the locale String, following {@code Locale's}
 * {@code toString()} format ("en", "en_UK", etc);
 * also accepts spaces as separators, as an alternative to underscores
 * @return a corresponding {@code Locale} instance
 * @throws IllegalArgumentException in case of an invalid locale specification
 *///from   w  ww  .  j  a  va 2  s . co  m
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] : "");
    validateLocalePart(language);
    validateLocalePart(country);
    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, language.length()) + 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);
}

From source file:org.intelligentsia.dowsers.core.serializers.jackson.LocaleJsonDeserializer.java

/**
 * Parse locale.// ww  w.j  a  v  a 2s.c  o  m
 * 
 * @param locale
 * @return {@link Locale} instance.
 */
static Locale parse(final String locale) {
    final String[] localeSplitted = locale.split(LocaleJsonDeserializer.SEPARATOR);
    if ((localeSplitted.length == 0) || (localeSplitted.length > 3)) { // malFormed
        return Locale.ENGLISH; // default Language
    }
    // load locale component
    final String language = localeSplitted[0];
    final String country = localeSplitted.length >= 2 ? localeSplitted[1] : "";
    final String variant = localeSplitted.length == 3 ? localeSplitted[2] : "";
    // default Language
    if (language.equals("")) {
        return Locale.ENGLISH;
    }
    return new Locale(language, country, variant);
}

From source file:com.googlecode.jsfFlex.myFaces.LocaleUtils.java

/**
 * Converts a locale string to <code>Locale</code> class. Accepts both
 * '_' and '-' as separators for locale components.
 *
 * @param localeString string representation of a locale
 * @return Locale instance, compatible with the string representation
 *//*from  www .  j  a va  2s  .  c om*/
public static Locale toLocale(String localeString) {
    if ((localeString == null) || (localeString.length() == 0)) {
        Locale locale = Locale.getDefault();
        if (log.isWarnEnabled())
            log.warn("Locale name in faces-config.xml null or empty, setting locale to default locale : "
                    + locale.toString());
        return locale;
    }

    int separatorCountry = localeString.indexOf('_');
    char separator;
    if (separatorCountry >= 0) {
        separator = '_';
    } else {
        separatorCountry = localeString.indexOf('-');
        separator = '-';
    }

    String language, country, variant;
    if (separatorCountry < 0) {
        language = localeString;
        country = variant = "";
    } else {
        language = localeString.substring(0, separatorCountry);

        int separatorVariant = localeString.indexOf(separator, separatorCountry + 1);
        if (separatorVariant < 0) {
            country = localeString.substring(separatorCountry + 1);
            variant = "";
        } else {
            country = localeString.substring(separatorCountry + 1, separatorVariant);
            variant = localeString.substring(separatorVariant + 1);
        }
    }

    return new Locale(language, country, variant);
}

From source file:Main.java

/**
 * Convert a string based locale into a Locale Object
 * <br>//from w w w  .jav a  2  s. co  m
 * <br>Strings are formatted:
 * <br>
 * <br>language_contry_variant
 *
 **/
public static Locale getLocaleFromString(String localeString) {
    if (localeString == null) {
        return null;
    }
    if (localeString.toLowerCase().equals("default")) {
        return Locale.getDefault();
    }
    int languageIndex = localeString.indexOf('_');
    if (languageIndex == -1) {
        return null;
    }
    int countryIndex = localeString.indexOf('_', languageIndex + 1);
    String country = null;
    if (countryIndex == -1) {
        if (localeString.length() > languageIndex) {
            country = localeString.substring(languageIndex + 1, localeString.length());
        } else {
            return null;
        }
    }
    int variantIndex = -1;
    if (countryIndex != -1) {
        countryIndex = localeString.indexOf('_', countryIndex + 1);
    }
    String language = localeString.substring(0, languageIndex);
    String variant = null;
    if (variantIndex != -1) {
        variant = localeString.substring(variantIndex + 1, localeString.length());
    }
    if (variant != null) {
        return new Locale(language, country, variant);
    } else {
        return new Locale(language, country);
    }
}

From source file:org.esco.web.servlet.ServerNameLocaleResolverAdaptor.java

@Override
public void setLocale(final HttpServletRequest request, final HttpServletResponse response,
        final Locale locale) {
    // Add the server name variant to the locale
    final String serverName = request.getServerName();
    Locale variantLocale = new Locale(locale.getLanguage(), locale.getCountry(), serverName);

    request.setAttribute(LOCALE_ATTRIBUTE_KEY, variantLocale);

    if (this.storeLocaleInSession) {
        // Store the locale in session
        request.getSession().setAttribute(LOCALE_ATTRIBUTE_KEY, variantLocale);
    }//from  w  ww. j  a va  2 s . c o  m
}

From source file:org.sacredscripturefoundation.commons.locale.LocaleStringUtils.java

/**
 * Parse the given <code>localeString</code> value into a {@link Locale}.
 * <p>//from  w ww  . j a v  a2 s.  c  om
 * This is the inverse operation of {@link Locale#toString Locale's
 * toString}.
 *
 * @param localeString the locale string, following <code>Locale's</code>
 * <code>toString()</code> format ("en", "en_UK", etc); also accepts spaces
 * as separators, as an alternative to underscores
 * @return a corresponding <code>Locale</code> instance
 */
public static Locale parseLocaleString(String localeString) {
    String[] parts = localeString.split("_");
    String language = (parts.length > 0 ? parts[0] : "");
    String country = (parts.length > 1 ? parts[1] : "");
    validateLocalePart(language);
    validateLocalePart(country);
    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 = localeString.substring(endIndexOfCountryCode).trim();
        if (variant.startsWith("_")) {
            int afterVariantIndex = variant.indexOf("_");
            if (afterVariantIndex >= 0) {
                variant = variant.substring(afterVariantIndex);
            }
        }
    }
    return (language.length() > 0 ? new Locale(language, country, variant) : null);
}

From source file:nz.co.senanque.localemanagement.XMLMessageSource.java

@Override
protected MessageFormat resolveCode(String code, Locale locale) {
    String ret = null;//from  www.  ja va  2s  .c  o m
    String country = locale.getCountry();
    String language = locale.getLanguage();
    String variant = locale.getVariant();
    logger.debug("Code {} Initial locale {}", code, locale.toString());
    Locale thisLocale = null;
    if (!StringUtils.isEmpty(variant)) {
        thisLocale = new Locale(language, country, variant);
        Map<String, String> m = m_map.get(thisLocale);
        if (m != null) {
            ret = m.get(code);
        }
        logger.debug("tried locale {} result: {}", thisLocale.toString(), ret);

    }
    if (ret == null) {
        if (!StringUtils.isEmpty(country)) {
            thisLocale = new Locale(language, country);
            Map<String, String> m = m_map.get(thisLocale);
            if (m != null) {
                ret = m.get(code);
            }
            logger.debug("tried locale {} result: {}", thisLocale.toString(), ret);
        }
    }
    if (ret == null) {
        if (!StringUtils.isEmpty(language)) {
            thisLocale = new Locale(language);
            Map<String, String> m = m_map.get(thisLocale);
            if (m != null) {
                ret = m.get(code);
            }
            logger.debug("tried locale {} result: {}", thisLocale.toString(), ret);
        }
    }
    if (ret == null) {
        thisLocale = Locale.getDefault();
        Map<String, String> m = m_map.get(thisLocale);
        if (m != null) {
            ret = m.get(code);
        }
        logger.debug("tried locale {} result: {}", thisLocale.toString(), ret);
    }
    if (ret == null) {
        return null;
    }
    return new MessageFormat(ret, locale);
}

From source file:com.googlecode.jsfFlex.myFaces.LocaleUtils.java

/**
 * Convert locale string used by converter tags to locale.
 *
 * @param name name of the locale/* ww w  . ja  v a  2s . co m*/
 * @return locale specified by the given String
 *
 * @see org.apache.myfaces.taglib.core.ConvertDateTimeTag#setConverterLocale
 * @see org.apache.myfaces.taglib.core.ConvertNumberTag#setConverterLocale
 */
public static Locale converterTagLocaleFromString(String name) {
    try {
        Locale locale;
        StringTokenizer st = new StringTokenizer(name, "_");
        String language = st.nextToken();

        if (st.hasMoreTokens()) {
            String country = st.nextToken();

            if (st.hasMoreTokens()) {
                String variant = st.nextToken();
                locale = new Locale(language, country, variant);
            } else {
                locale = new Locale(language, country);
            }
        } else {
            locale = new Locale(language);
        }

        return locale;
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Locale parsing exception - " + "invalid string representation '" + name + "'");
    }
}