Example usage for java.util Locale getVariant

List of usage examples for java.util Locale getVariant

Introduction

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

Prototype

public String getVariant() 

Source Link

Document

Returns the variant code for this locale.

Usage

From source file:org.openmrs.Concept.java

/**
 * Returns concept name, the look up for the appropriate name is done in the following order;
 * <ul>/*from w  w w  .  j av  a2 s . c  o  m*/
 * <li>First name found in any locale that is explicitly marked as preferred while searching
 * available locales in order of preference (the locales are traversed in their order as they
 * are listed in the 'locale.allowed.list' including english global property).</li>
 * <li>First "Fully Specified" name found while searching available locales in order of
 * preference.</li>
 * <li>The first fully specified name found while searching through all names for the concept</li>
 * <li>The first synonym found while searching through all names for the concept.</li>
 * <li>The first random name found(except index terms) while searching through all names.</li>
 * </ul>
 * 
 * @return {@link ConceptName} in the current locale or any locale if none found
 * @since 1.5
 * @see Concept#getNames(Locale) to get all the names for a locale
 * @see Concept#getPreferredName(Locale) for the preferred name (if any)
 * @should return the name explicitly marked as locale preferred if any is present
 * @should return the fully specified name in a locale if no preferred name is set
 * @should return null if the only added name is an index term
 * @should return name in broader locale incase none is found in specific one
 */
public ConceptName getName() {
    if (getNames().size() == 0) {
        if (log.isDebugEnabled()) {
            log.debug("there are no names defined for: " + conceptId);
        }
        return null;
    }

    for (Locale currentLocale : LocaleUtility.getLocalesInOrder()) {
        ConceptName preferredName = getPreferredName(currentLocale);
        if (preferredName != null) {
            return preferredName;
        }

        ConceptName fullySpecifiedName = getFullySpecifiedName(currentLocale);
        if (fullySpecifiedName != null) {
            return fullySpecifiedName;
        }

        //if the locale has an variants e.g en_GB, try names in the locale excluding the country code i.e en
        if (!StringUtils.isBlank(currentLocale.getCountry())
                || !StringUtils.isBlank(currentLocale.getVariant())) {
            Locale broaderLocale = new Locale(currentLocale.getLanguage());
            ConceptName prefNameInBroaderLoc = getPreferredName(broaderLocale);
            if (prefNameInBroaderLoc != null) {
                return prefNameInBroaderLoc;
            }

            ConceptName fullySpecNameInBroaderLoc = getFullySpecifiedName(broaderLocale);
            if (fullySpecNameInBroaderLoc != null) {
                return fullySpecNameInBroaderLoc;
            }
        }
    }

    for (ConceptName cn : getNames()) {
        if (cn.isFullySpecifiedName()) {
            return cn;
        }
    }

    if (getSynonyms().size() > 0) {
        return getSynonyms().iterator().next();
    }

    //we dont expect to get here since every concept name must have atleast
    //one fully specified name, but just in case(probably inconsistent data)

    return null;
}

From source file:org.opencms.workplace.commons.CmsPreferences.java

/**
 * Builds the html for the language select box of the start settings.<p>
 * //  www .  java  2  s.  co m
 * @param htmlAttributes optional html attributes for the &lgt;select&gt; tag
 * @return the html for the language select box
 */
public String buildSelectLanguage(String htmlAttributes) {

    // get available locales from the workplace manager
    List locales = OpenCms.getWorkplaceManager().getLocales();
    List options = new ArrayList(locales.size());
    List values = new ArrayList(locales.size());
    int checkedIndex = 0;
    int counter = 0;
    Iterator i = locales.iterator();
    Locale setLocale = getSettings().getUserSettings().getLocale();
    while (i.hasNext()) {
        Locale currentLocale = (Locale) i.next();
        // add all locales to the select box
        String language = currentLocale.getDisplayLanguage(setLocale);
        if (CmsStringUtil.isNotEmpty(currentLocale.getCountry())) {
            language = language + " (" + currentLocale.getDisplayCountry(setLocale) + ")";
        }
        if (CmsStringUtil.isNotEmpty(currentLocale.getVariant())) {
            language = language + " (" + currentLocale.getDisplayVariant(setLocale) + ")";
        }
        options.add(language);
        values.add(currentLocale.toString());
        if (getParamTabWpLanguage().equals(currentLocale.toString())) {
            // mark the currently active locale
            checkedIndex = counter;
        }
        counter++;
    }
    return buildSelect(htmlAttributes, options, values, checkedIndex);
}

From source file:org.olat.core.util.i18n.I18nManager.java

/**
 * Calculate the locale key that identifies the given locale. Adds support for
 * the overlay mechanism.//from  w  ww  .  ja  v a 2  s.  c  o m
 * 
 * @param locale
 * @return
 */
public String getLocaleKey(Locale locale) {
    String key = localeToLocaleKey.get(locale);
    if (key == null) {
        String langKey = locale.getLanguage();
        String country = locale.getCountry();
        // Only add country when available - in case of an overlay country is
        // set to
        // an empty value
        if (StringHelper.containsNonWhitespace(country)) {
            langKey = langKey + "_" + country;
        }
        String variant = locale.getVariant();
        // Only add the _ separator if the variant contains something in
        // addition to
        // the overlay, otherways use the __ only
        if (StringHelper.containsNonWhitespace(variant)) {
            if (variant.startsWith("__" + I18nModule.getOverlayName())) {
                langKey += variant;
            } else {
                langKey = langKey + "_" + variant;
            }
        }

        key = localeToLocaleKey.putIfAbsent(locale, langKey);
        if (key == null) {
            key = langKey;
        }

    }
    return key;
}

From source file:org.olat.core.util.i18n.I18nManager.java

private final String getLocalizedString(String bundleName, String key, Object[] args, Locale locale,
        boolean overlayEnabled, boolean fallBackToDefaultLocale, boolean fallBackToFallbackLocale,
        boolean resolveRecursively, boolean allowDecoration, int recursionLevel) {
    String msg = null;//from w  w w  . ja  v  a 2  s.  c om
    Properties properties = null;
    // a) If the overlay is enabled, lookup first in the overlay property
    // file
    if (overlayEnabled) {

        Locale overlayLocale = I18nModule.getOverlayLocales().get(locale);
        if (overlayLocale != null) {
            properties = getProperties(overlayLocale, bundleName, resolveRecursively, recursionLevel);
            if (properties != null) {
                msg = properties.getProperty(key);
                //               if (log.isDebug() && msg == null) {
                //                  log.debug("Key::" + key + " not found in overlay::" + I18nModule.getOverlayName() + " for bundle::" + bundleName
                //                        + " and locale::" + locale.toString(), null);
                //               }
            }
        }
    }
    // b) Otherwhise lookup in the regular bundle
    if (msg == null) {
        properties = getProperties(locale, bundleName, resolveRecursively, recursionLevel);
        // if LocalStrings File does not exist -> return error msg on screen
        // / fallback to default language
        if (properties == null) {
            if (Settings.isDebuging()) {
                log.warn(FILE_NOT_FOUND_ERROR_PREFIX + "! locale::" + locale.toString() + ", path::"
                        + bundleName, null);
            }
        } else {
            msg = properties.getProperty(key);
        }
    }

    // The following fallback behaviour is similar to
    // java.util.ResourceBundle
    if (msg == null) {
        if (log.isDebug()) {
            log.debug("Key::" + key + " not found for bundle::" + bundleName + " and locale::"
                    + locale.toString(), null);
        }
        // Fallback on the language if the locale has a country and/or a
        // variant
        // de_DE_variant -> de_DE -> de
        // Only after having all those checked we will fallback to the
        // default language
        // 1. Check on variant
        String variant = locale.getVariant();
        if (!variant.equals("")) {
            Locale newLoc = I18nModule.getAllLocales().get(locale.getLanguage() + "_" + locale.getCountry());
            if (newLoc != null)
                msg = getLocalizedString(bundleName, key, args, newLoc, overlayEnabled, false,
                        fallBackToFallbackLocale, resolveRecursively, recursionLevel);
        }
        if (msg == null) {
            // 2. Check on country
            String country = locale.getCountry();
            if (!country.equals("")) {
                Locale newLoc = I18nModule.getAllLocales().get(locale.getLanguage());
                if (newLoc != null)
                    msg = getLocalizedString(bundleName, key, args, newLoc, overlayEnabled, false,
                            fallBackToFallbackLocale, resolveRecursively, recursionLevel);
            }
            // else we have an original locale with only a language given ->
            // no language specific fallbacks anymore
        }
    }

    if (msg == null) {
        // Message still empty? Use fallback to default language?
        // yes: return the call applied with the olatcore default locale
        // no: return null to indicate nothing was found so that callers may
        // use fallbacks
        if (fallBackToDefaultLocale) {
            return getLocalizedString(bundleName, key, args, I18nModule.getDefaultLocale(), overlayEnabled,
                    false, fallBackToFallbackLocale, resolveRecursively, recursionLevel);
        } else {
            if (fallBackToFallbackLocale) {
                // fallback to fallback locale
                Locale fallbackLocale = I18nModule.getFallbackLocale();
                if (fallbackLocale.equals(locale)) {
                    // finish when when already in fallback locale
                    if (isLogDebugEnabled()) {
                        logWarn("Could not find translation for bundle::" + bundleName + " and key::" + key
                                + " ; not even in default or fallback packages", null);
                    }
                    return null;
                } else {
                    return getLocalizedString(bundleName, key, args, fallbackLocale, overlayEnabled, false,
                            false, resolveRecursively, recursionLevel);
                }
            } else {
                return null;
            }
        }
    }
    // When caching not enabled we need to check for keys contained in this
    // value. In caching mode this is already done while loading the
    // properties
    // file
    if (resolveRecursively && (!cachingEnabled || properties != null)) {
        msg = resolveValuesInternalKeys(locale, bundleName, key, properties, overlayEnabled, recursionLevel,
                msg);
    }

    // Add markup code to identify translated strings
    if (allowDecoration && isCurrentThreadMarkLocalizedStringsEnabled()
            && !bundleName.startsWith(BUNDLE_INLINE_TRANSLATION_INTERCEPTOR)
            && !bundleName.startsWith(BUNDLE_EXCEPTION) && isInlineTranslationEnabledForKey(bundleName, key)) {
        // identifyer consists of bundle name and key and an id to
        // distinguish multiple translations of the same key
        String identifyer = bundleName + ":" + key + ":" + CodeHelper.getRAMUniqueID();
        msg = IDENT_PREFIX + identifyer + IDENT_START_POSTFIX + msg + IDENT_PREFIX + identifyer
                + IDENT_END_POSTFIX;
    }
    // Add the the {0},{1} arguments to the GUI message
    if (args == null) {
        return msg;
    } else {
        // Escape single quotes with single quotes. Single quotes have special meaning in MessageFormat
        // See OLAT-5107, OLAT-5756
        if (msg.indexOf("'") > -1) {
            msg = msg.replaceAll("'", "''");
        }
        return MessageFormat.format(msg, args);
    }
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java

/**
 * Set the given value as a parameter to the statement.
 *//*from   ww w . j a v  a 2s  .c o m*/
public void setLocale(PreparedStatement stmnt, int idx, Locale val, Column col) throws SQLException {
    setString(stmnt, idx, val.getLanguage() + "_" + val.getCountry() + "_" + val.getVariant(), col);
}

From source file:org.apache.maven.plugin.javadoc.AbstractJavadocMojo.java

/**
 * Checks for the validity of the Javadoc options used by the user.
 *
 * @throws MavenReportException if error
 *//*  w w w .  j ava  2  s .  c o m*/
private void validateJavadocOptions() throws MavenReportException {
    // encoding
    if (StringUtils.isNotEmpty(getEncoding()) && !JavadocUtil.validateEncoding(getEncoding())) {
        throw new MavenReportException("Unsupported option <encoding/> '" + getEncoding() + "'");
    }

    // locale
    if (StringUtils.isNotEmpty(this.locale)) {
        StringTokenizer tokenizer = new StringTokenizer(this.locale, "_");
        final int maxTokens = 3;
        if (tokenizer.countTokens() > maxTokens) {
            throw new MavenReportException(
                    "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant.");
        }

        Locale localeObject = null;
        if (tokenizer.hasMoreTokens()) {
            String language = tokenizer.nextToken().toLowerCase(Locale.ENGLISH);
            if (!Arrays.asList(Locale.getISOLanguages()).contains(language)) {
                throw new MavenReportException(
                        "Unsupported language '" + language + "' in option <locale/> '" + this.locale + "'");
            }
            localeObject = new Locale(language);

            if (tokenizer.hasMoreTokens()) {
                String country = tokenizer.nextToken().toUpperCase(Locale.ENGLISH);
                if (!Arrays.asList(Locale.getISOCountries()).contains(country)) {
                    throw new MavenReportException(
                            "Unsupported country '" + country + "' in option <locale/> '" + this.locale + "'");
                }
                localeObject = new Locale(language, country);

                if (tokenizer.hasMoreTokens()) {
                    String variant = tokenizer.nextToken();
                    localeObject = new Locale(language, country, variant);
                }
            }
        }

        if (localeObject == null) {
            throw new MavenReportException(
                    "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant.");
        }

        this.locale = localeObject.toString();
        final List<Locale> availableLocalesList = Arrays.asList(Locale.getAvailableLocales());
        if (StringUtils.isNotEmpty(localeObject.getVariant()) && !availableLocalesList.contains(localeObject)) {
            StringBuilder sb = new StringBuilder();
            sb.append("Unsupported option <locale/> with variant '").append(this.locale);
            sb.append("'");

            localeObject = new Locale(localeObject.getLanguage(), localeObject.getCountry());
            this.locale = localeObject.toString();

            sb.append(", trying to use <locale/> without variant, i.e. '").append(this.locale).append("'");
            if (getLog().isWarnEnabled()) {
                getLog().warn(sb.toString());
            }
        }

        if (!availableLocalesList.contains(localeObject)) {
            throw new MavenReportException("Unsupported option <locale/> '" + this.locale + "'");
        }
    }
}

From source file:de.innovationgate.webgate.api.WGDatabase.java

/**
 * Retrieves the best matching language definition for the given locale.
 * Language definitions are searched in descending details order:
 * language_COUNTRY_VARIANT language_COUNTRY language
 * //from   www.j  a va2  s .c  om
 * @param locale
 *            The locale to match
 * @return The language that matches the locale best, null if none could be
 *         found
 * @throws WGAPIException
 */
public WGLanguage getLanguageForLocale(Locale locale) throws WGAPIException {

    if (locale == null) {
        return getLanguage(getDefaultLanguage());
    }

    String langKey;
    WGLanguage lang;
    if (!WGUtils.isEmpty(locale.getCountry()) && !WGUtils.isEmpty(locale.getVariant())) {
        langKey = locale.getLanguage() + "_" + locale.getCountry() + "_" + locale.getVariant();
        lang = getLanguage(langKey);
        if (lang != null && !lang.isDummy()) {
            return lang;
        }
    }

    if (!WGUtils.isEmpty(locale.getCountry())) {
        langKey = locale.getLanguage() + "_" + locale.getCountry();
        lang = getLanguage(langKey);
        if (lang != null && !lang.isDummy()) {
            return lang;
        }
    }

    langKey = locale.getLanguage();
    lang = getLanguage(langKey);
    if (lang != null && !lang.isDummy()) {
        return lang;
    }

    return null;

}

From source file:com.clark.func.Functions.java

/**
 * <p>//  w w w. j a  va 2s  . co m
 * Obtains the list of languages supported for a given country.
 * </p>
 * 
 * <p>
 * This method takes a country code and searches to find the languages
 * available for that country. Variant locales are removed.
 * </p>
 * 
 * @param countryCode
 *            the 2 letter country code, null returns empty
 * @return an unmodifiable List of Locale objects, never null
 */
public static List<Locale> languagesByCountry(String countryCode) {
    List<Locale> langs = cLanguagesByCountry.get(countryCode); // syncd
    if (langs == null) {
        if (countryCode != null) {
            langs = new ArrayList<Locale>();
            List<Locale> locales = availableLocaleList();
            for (int i = 0; i < locales.size(); i++) {
                Locale locale = locales.get(i);
                if (countryCode.equals(locale.getCountry()) && locale.getVariant().length() == 0) {
                    langs.add(locale);
                }
            }
            langs = Collections.unmodifiableList(langs);
        } else {
            langs = Collections.emptyList();
        }
        cLanguagesByCountry.put(countryCode, langs); // syncd
    }
    return langs;
}