Example usage for java.util Locale getCountry

List of usage examples for java.util Locale getCountry

Introduction

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

Prototype

public String getCountry() 

Source Link

Document

Returns the country/region code for this locale, which should either be the empty string, an uppercase ISO 3166 2-letter code, or a UN M.49 3-digit code.

Usage

From source file:org.apache.cordova.globalization.Globalization.java

private String toBcp47Language(Locale loc) {
    final char SEP = '-'; // we will use a dash as per BCP 47
    String language = loc.getLanguage();
    String region = loc.getCountry();
    String variant = loc.getVariant();

    // special case for Norwegian Nynorsk since "NY" cannot be a variant as per BCP 47
    // this goes before the string matching since "NY" wont pass the variant checks
    if (language.equals("no") && region.equals("NO") && variant.equals("NY")) {
        language = "nn";
        region = "NO";
        variant = "";
    }/* w  w  w  . ja v  a  2 s  . c om*/

    if (language.isEmpty() || !language.matches("\\p{Alpha}{2,8}")) {
        language = "und"; // Follow the Locale#toLanguageTag() implementation 
                          // which says to return "und" for Undetermined
    } else if (language.equals("iw")) {
        language = "he"; // correct deprecated "Hebrew"
    } else if (language.equals("in")) {
        language = "id"; // correct deprecated "Indonesian"
    } else if (language.equals("ji")) {
        language = "yi"; // correct deprecated "Yiddish"
    }

    // ensure valid country code, if not well formed, it's omitted
    if (!region.matches("\\p{Alpha}{2}|\\p{Digit}{3}")) {
        region = "";
    }

    // variant subtags that begin with a letter must be at least 5 characters long
    if (!variant.matches("\\p{Alnum}{5,8}|\\p{Digit}\\p{Alnum}{3}")) {
        variant = "";
    }

    StringBuilder bcp47Tag = new StringBuilder(language);
    if (!region.isEmpty()) {
        bcp47Tag.append(SEP).append(region);
    }
    if (!variant.isEmpty()) {
        bcp47Tag.append(SEP).append(variant);
    }

    return bcp47Tag.toString();
}

From source file:de.austinpadernale.holidays.Holiday.java

public String getName(Locale locale) {
    String result;/*from ww w.j a v  a2s.  c o  m*/
    if (names == null || names.isEmpty()) {
        result = createName();
    } else if (locale == null || locale.equals(Locale.ROOT)) {
        HolidayName hn = null;
        for (HolidayName n : names) {
            if (n.getLanguage() == null || n.getLanguage().equals(Locale.ROOT)) {
                hn = n;
                break;
            }
        }
        result = holidayNameToName(hn);
    } else {
        HolidayName rn = null;
        HolidayName ln2 = null;
        HolidayName ln = null;
        HolidayName cn = null;
        for (HolidayName n : names) {
            Locale l = n.getLanguage();
            if (l == null || l.equals(Locale.ROOT)) {
                if (rn == null) {
                    rn = n;
                }
                continue;
            }
            if (equals(l.getLanguage(), locale.getLanguage()) && StringUtils.isEmpty(l.getCountry())) {
                if (ln == null) {
                    ln = n;
                }
                continue;
            }
            if (equals(l.getLanguage(), locale.getLanguage()) && !StringUtils.isEmpty(l.getCountry())) {
                if (ln2 == null) {
                    ln2 = n;
                }
                continue;
            }
            if (equals(l.getLanguage(), locale.getLanguage()) && equals(l.getCountry(), locale.getCountry())) {
                if (cn == null) {
                    cn = n;
                }
            }
        }
        if (cn != null) {
            result = holidayNameToName(cn);
        } else if (ln != null) {
            result = holidayNameToName(ln);
        } else if (ln2 != null) {
            result = holidayNameToName(ln2);
        } else if (rn != null) {
            result = holidayNameToName(rn);
        } else {
            result = createName();
        }
    }
    return result;
}

From source file:edu.uchicago.duo.web.DuoEnrollController.java

/**
 * *********************************************************************
 * Below are ALL FOR creating the International Dial Code Drop Down list
 *
 * Used in: DuoEnrollStep3.jsp/*from  w  w  w  .j  a  v  a2  s . c  o  m*/
 * *********************************************************************
 */
@ModelAttribute("countryDialList")
public Map<String, String> populatecountryDialList() {

    List<DuoEnrollController.Country> countries = new ArrayList<>();
    Map<String, String> dialCodes = new LinkedHashMap<>();
    Map<String, String> sortedDialCodes = new LinkedHashMap<>();

    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();

    //
    // Get ISO countries, create Country object and
    // store in the collection.
    //
    String[] isoCountries = Locale.getISOCountries();
    for (String country : isoCountries) {
        Locale locale = new Locale("en", country);
        String code = locale.getCountry();
        String name = locale.getDisplayCountry();

        if (!"".equals(code) && !"".equals(name)) {
            try {
                int dialCode = phoneUtil.parse("1112223333", code).getCountryCode();
                countries.add(new DuoEnrollController.Country(code, name, dialCode));
            } catch (Exception e) {
            }
        }
    }

    Collections.sort(countries, new DuoEnrollController.CountryComparator());

    for (DuoEnrollController.Country country : countries) {
        dialCodes.put("+" + String.valueOf(country.dialCode), country.name);
        //dialCodes.put("+"+String.valueOf(country.code), country.name);
    }

    sortedDialCodes = sortByValue(dialCodes);

    return sortedDialCodes;
}

From source file:org.parancoe.web.util.ReloadableResourceBundleMessageSource.java

/**
 * Calculate the filenames for the given bundle basename and Locale, appending language code,
 * country code, and variant code. E.g.: basename "messages", Locale "de_AT_oo" ->
 * "messages_de_AT_OO", "messages_de_AT", "messages_de". <p>Follows the rules defined by {@link java.util.Locale#toString()}.
 *
 * @param basename the basename of the bundle
 * @param locale the locale/*from  ww w  . j  a  v a 2 s .c o  m*/
 * @return the List of filenames to check
 */
protected List<String> calculateFilenamesForLocale(String basename, Locale locale) {
    List<String> result = new ArrayList<String>(3);
    String language = locale.getLanguage();
    String country = locale.getCountry();
    String variant = locale.getVariant();
    StringBuilder temp = new StringBuilder(basename);

    temp.append('_');
    if (language.length() > 0) {
        temp.append(language);
        result.add(0, temp.toString());
    }

    temp.append('_');
    if (country.length() > 0) {
        temp.append(country);
        result.add(0, temp.toString());
    }

    if (variant.length() > 0 && (language.length() > 0 || country.length() > 0)) {
        temp.append('_').append(variant);
        result.add(0, temp.toString());
    }

    return result;
}

From source file:org.exoplatform.wcm.webui.seo.UISEOForm.java

public List<SelectItemOption<String>> getLanguages() throws Exception {
    WebuiRequestContext rc = WebuiRequestContext.getCurrentInstance();
    Locale inLocale = WebuiRequestContext.getCurrentInstance().getLocale();
    // Get default locale
    Locale defaultLocale = Locale.getDefault();
    // set default locale to current user selected language
    Locale.setDefault(Util.getUIPortal().getAncestorOfType(UIPortalApplication.class).getLocale());

    LocaleConfigService localService = WCMCoreUtils.getService(LocaleConfigService.class);
    List<SelectItemOption<String>> languages = new ArrayList<SelectItemOption<String>>();
    Iterator<LocaleConfig> iter = localService.getLocalConfigs().iterator();
    ResourceBundle resourceBundle = rc.getApplicationResourceBundle();
    while (iter.hasNext()) {
        LocaleConfig localConfig = iter.next();
        Locale locale = localConfig.getLocale();
        String lang = locale.getLanguage();
        String country = locale.getCountry();
        if (StringUtils.isNotEmpty(country))
            lang += "_" + country;
        if (seoLanguages == null || !seoLanguages.contains(lang)) {
            try {
                languages.add(new SelectItemOption<String>(CapitalFirstLetters(locale.getDisplayName(inLocale)),
                        lang));//  ww w  . j  av a  2s .  c  o  m
            } catch (MissingResourceException mre) {
                languages.add(new SelectItemOption<String>(lang, lang));
            }
        }
    }

    // Set back to the default locale
    Locale.setDefault(defaultLocale);
    Collections.sort(languages, new ItemOptionComparator());
    languages.add(0, new SelectItemOption<String>(getLabel(resourceBundle, "select-language"), "language"));
    return languages;
}

From source file:com.bluexml.side.Framework.alfresco.notification.NotificationHelper.java

/**
 * This method loads the  file resourceCustomPaths+"/cm:"+propertyFileName.basename+<language>+propertyFileName.extension as InputStream
 * @param language the language to load; if not null the propertyFileName is modified in propertyFileName.basename+<language>+propertyFileName.extension; if null the propertyFileName is not modified
 * @param propertyFileName the property file name to load
 * @param resourceCustomPath the folder where the propertyFileName may be loaded (with the embedded language if not null)
 * @param classPath if true, the propertyFileName is loaded from the classpath (without resourceCustomPath)
 * @return the inputstream resourceCustomPaths+"/cm:"+propertyFileName.basename+<language>+propertyFileName.extension content
 *///w w  w . j  a v a 2s .c  o  m
public InputStream getPropertiesInputStream(String language, String propertyFileName, String resourceCustomPath,
        boolean classPath) {
    InputStream s = null;
    // compute path with language
    String[] path_dictionary = propertyFileName.split("\\.");
    if (!resourceCustomPath.endsWith("/"))
        resourceCustomPath += "/";
    path_dictionary[0] = resourceCustomPath + TYPE_CONTENT_PREFIX + ":" + path_dictionary[0];
    String resourcePath_dictionary = path_dictionary[0];
    if (language != null)
        resourcePath_dictionary += "_" + language;
    resourcePath_dictionary += "." + path_dictionary[1];

    if (logger.isDebugEnabled()) {
        logger.debug("getPropertiesInputStream path_dictionary=" + path_dictionary);
        logger.debug("getPropertiesInputStream language=" + language);
        logger.debug("getPropertiesInputStream resourcePath_dictionary=" + resourcePath_dictionary);
    }

    try {
        // try to get the template that match the language (country[variant]?)
        s = getInputStream(resourcePath_dictionary);
    } catch (FileNotFoundException e) {
        s = null;
        String country = null;
        if (language != null) {
            logger.debug("no perfect match try on country");
            // no perfect match found, try to get template for country (without variant)
            Locale parseLocale = I18NUtil.parseLocale(language);
            logger.debug("local country :" + parseLocale.getCountry());
            logger.debug("local variant :" + parseLocale.getVariant());
            country = parseLocale.getCountry().toLowerCase();
            if (!language.equals(country)) {
                // try on country ?
                resourcePath_dictionary = path_dictionary[0] + "_" + country + "." + path_dictionary[1];
                try {
                    s = getInputStream(resourcePath_dictionary);
                } catch (FileNotFoundException e1) {
                    logger.debug("no match on country");
                }
            }
        }
        if (s == null && classPath) {
            // file not exist so go ahead, and search for the default configuration for this country
            if (country != null) {
                language = country;
                logger.debug("Load default configuration from classPath");
                // search in classPath (for default values)
                String[] path = PROPERTIES_PATH.split("\\.");
                String resourcePath = path[0] + "_" + language + "." + path[1];
                s = this.getClass().getResourceAsStream(resourcePath);
            }
            if (s == null) {
                // not found so we load default file
                s = this.getClass().getResourceAsStream(PROPERTIES_PATH);
                logger.debug("configuration for language :" + language + " not found, so use default language");
            }
        }
    }
    return s;
}

From source file:im.vector.VectorApp.java

/**
 * Save the new application locale./*from ww  w.  j ava 2s .com*/
 */
private static void saveApplicationLocale(Locale locale) {
    Context context = VectorApp.getInstance();
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

    SharedPreferences.Editor editor = preferences.edit();

    String language = locale.getLanguage();
    if (!TextUtils.isEmpty(language)) {
        editor.putString(APPLICATION_LOCALE_LANGUAGE_KEY, language);
    } else {
        editor.remove(APPLICATION_LOCALE_LANGUAGE_KEY);
    }

    String country = locale.getCountry();
    if (!TextUtils.isEmpty(country)) {
        editor.putString(APPLICATION_LOCALE_COUNTRY_KEY, country);
    } else {
        editor.remove(APPLICATION_LOCALE_COUNTRY_KEY);
    }

    String variant = locale.getVariant();
    if (!TextUtils.isEmpty(variant)) {
        editor.putString(APPLICATION_LOCALE_VARIANT_KEY, variant);
    } else {
        editor.remove(APPLICATION_LOCALE_VARIANT_KEY);
    }

    editor.commit();
}

From source file:org.sakaiproject.site.tool.SiteInfoToolServlet.java

/**
 * Takes a DOM structure and renders a PDF
 * //w  w w .ja  va 2  s. c  o  m
 * @param doc
 *        DOM structure
 * @param xslFileName
 *        XSL file to use to translate the DOM document to FOP
 */
@SuppressWarnings("unchecked")
protected void generatePDF(Document doc, OutputStream streamOut) {
    String xslFileName = "participants-all-attrs.xsl";
    Locale currentLocale = rb.getLocale();
    if (currentLocale != null) {
        String fullLocale = currentLocale.toString();
        xslFileName = "participants-all-attrs_" + fullLocale + ".xsl";
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName);
        if (inputStream == null) {
            xslFileName = "participants-all-attrs_" + currentLocale.getCountry() + ".xsl";
            inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName);
            if (inputStream == null) {
                //We use the default file
                xslFileName = "participants-all-attrs.xsl";
            }
        }

        IOUtils.closeQuietly(inputStream);
    }
    String configFileName = "userconfig.xml";
    DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
    InputStream configInputStream = null;
    try {
        configInputStream = getClass().getClassLoader().getResourceAsStream(configFileName);
        Configuration cfg = cfgBuilder.build(configInputStream);

        FopFactory fopFactory = FopFactory.newInstance();
        fopFactory.setUserConfig(cfg);
        fopFactory.setStrictValidation(false);
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        if (!StringUtils.isEmpty(ServerConfigurationService.getString("pdf.default.font"))) {
            // this allows font substitution to support i18n chars in PDFs - SAK-21909
            FontQualifier fromQualifier = new FontQualifier();
            fromQualifier.setFontFamily("DEFAULT_FONT");
            FontQualifier toQualifier = new FontQualifier();
            toQualifier.setFontFamily(ServerConfigurationService.getString("pdf.default.font", "Helvetica"));
            FontSubstitutions result = new FontSubstitutions();
            result.add(new FontSubstitution(fromQualifier, toQualifier));
            fopFactory.getFontManager().setFontSubstitutions(result);
        }
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, streamOut);
        InputStream in = getClass().getClassLoader().getResourceAsStream(xslFileName);
        Transformer transformer = transformerFactory.newTransformer(new StreamSource(in));
        transformer.setParameter("titleName", rb.getString("sitegen.siteinfolist.title.name"));
        transformer.setParameter("titleSection", rb.getString("sitegen.siteinfolist.title.section"));
        transformer.setParameter("titleId", rb.getString("sitegen.siteinfolist.title.id"));
        transformer.setParameter("titleCredit", rb.getString("sitegen.siteinfolist.title.credit"));
        transformer.setParameter("titleRole", rb.getString("sitegen.siteinfolist.title.role"));
        transformer.setParameter("titleStatus", rb.getString("sitegen.siteinfolist.title.status"));

        Source src = new DOMSource(doc);
        transformer.transform(src, new SAXResult(fop.getDefaultHandler()));
    } catch (Exception e) {
        e.printStackTrace();
        log.warn(this + ".generatePDF(): " + e);
        return;
    } finally {
        IOUtils.closeQuietly(configInputStream);
    }
}

From source file:org.sakaiproject.metaobj.shared.mgt.home.StructuredArtifactHome.java

protected Content i18nFilterAnnotations(Element content) throws JDOMException {
    Locale locale = rl.getLocale();
    Map<String, Element> documentElements = new Hashtable<String, Element>();

    filterElements(documentElements, content, null);
    filterElements(documentElements, content, locale.getLanguage());
    filterElements(documentElements, content, locale.getLanguage() + "_" + locale.getCountry());
    filterElements(documentElements, content,
            locale.getLanguage() + "_" + locale.getCountry() + "_" + locale.getVariant());

    Element returned = (Element) content.clone();
    returned.removeChildren("documentation", content.getNamespace());

    for (Iterator<Element> i = documentElements.values().iterator(); i.hasNext();) {
        returned.addContent((Content) i.next().clone());
    }/*w  ww . java2s  . co  m*/

    return returned;
}

From source file:org.phenotips.vocabulary.internal.solr.AbstractSolrVocabularyTerm.java

@Override
public Collection<?> getTranslatedValues(String property) {
    Locale currentLocale = getCurrentLocale();
    if (StringUtils.isEmpty(currentLocale.getLanguage())) {
        return getValues(property);
    }/*from   ww w. j  a v a 2  s  .  c om*/
    Collection<Object> result = getValues(property + '_' + currentLocale.toString());
    // If the locale has language, country, and variant, try without the variant
    if (CollectionUtils.isEmpty(result)
            && StringUtils.isNoneEmpty(currentLocale.getVariant(), currentLocale.getCountry())) {
        result = getValues(property + '_' + currentLocale.getLanguage() + '_' + currentLocale.getCountry());
    }
    // If the locale has language and country, try without the country
    if (CollectionUtils.isEmpty(result)
            && StringUtils.isNoneEmpty(currentLocale.getLanguage(), currentLocale.getCountry())) {
        result = getValues(property + '_' + currentLocale.getLanguage());
    }
    // If the locale has no country, then the first call included the language only;
    // at this point, it's certain that no translation is available, return the untranslated default
    if (CollectionUtils.isEmpty(result)) {
        result = getValues(property);
    }
    return result;
}