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.springframework.roo.addon.creator.CreatorOperationsImpl.java

public void createI18nAddon(final JavaPackage topLevelPackage, String language, final Locale locale,
        final File messageBundle, final File flagGraphic, String description, final String projectName) {
    Validate.notNull(topLevelPackage, "Top Level Package required");
    Validate.notNull(locale, "Locale required");
    Validate.notNull(messageBundle, "Message Bundle required");

    if (StringUtils.isBlank(language)) {
        language = "";
        final InputStream inputStream = FileUtils.getInputStream(getClass(),
                Type.I18N.name().toLowerCase() + "/iso3166.txt");
        try {//from   ww w .ja  v  a  2  s  . c o  m
            for (String line : IOUtils.readLines(inputStream)) {
                final String[] split = line.split(";");
                if (split[1].startsWith(locale.getCountry().toUpperCase())) {
                    if (split[0].contains(",")) {
                        split[0] = split[0].substring(0, split[0].indexOf(",") - 1);
                    }
                    final String[] langWords = split[0].split("\\s");
                    final StringBuilder b = new StringBuilder();
                    for (final String word : langWords) {
                        b.append(StringUtils.capitalize(word.toLowerCase())).append(" ");
                    }
                    language = b.toString().substring(0, b.length() - 1);
                }
            }
        } catch (final IOException e) {
            throw new IllegalStateException(
                    "Could not parse ISO 3166 language list, please use --language option in command");
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }

    final String[] langWords = language.split("\\s");
    final StringBuilder builder = new StringBuilder();
    for (final String word : langWords) {
        builder.append(StringUtils.capitalize(word.toLowerCase()));
    }
    final String languageName = builder.toString();
    final String packagePath = topLevelPackage.getFullyQualifiedPackageName().replace('.', separatorChar);

    if (StringUtils.isBlank(description)) {
        description = languageName + " language support for Spring Roo Web MVC JSP Scaffolding";
    }
    if (!description.contains("#mvc") || !description.contains("#localization")
            || !description.contains("locale:")) {
        description = description + "; #mvc,#localization,locale:" + locale.getCountry().toLowerCase();
    }
    createProject(topLevelPackage, Type.I18N, description, projectName);

    install("assembly.xml", topLevelPackage, Path.ROOT, Type.I18N, projectName);

    OutputStream outputStream = null;
    try {
        outputStream = fileManager.createFile(pathResolver.getFocusedIdentifier(Path.SRC_MAIN_RESOURCES,
                packagePath + separatorChar + messageBundle.getName())).getOutputStream();
        org.apache.commons.io.FileUtils.copyFile(messageBundle, outputStream);
        if (flagGraphic != null) {
            outputStream = fileManager.createFile(pathResolver.getFocusedIdentifier(Path.SRC_MAIN_RESOURCES,
                    packagePath + separatorChar + flagGraphic.getName())).getOutputStream();
            org.apache.commons.io.FileUtils.copyFile(flagGraphic, outputStream);
        } else {
            installFlagGraphic(locale, packagePath);
        }
    } catch (final IOException e) {
        throw new IllegalStateException("Could not copy addon resources into project", e);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    final String destinationFile = pathResolver.getFocusedIdentifier(Path.SRC_MAIN_JAVA,
            packagePath + separatorChar + languageName + "Language.java");

    if (!fileManager.exists(destinationFile)) {
        final InputStream templateInputStream = FileUtils.getInputStream(getClass(),
                Type.I18N.name().toLowerCase() + "/Language.java-template");
        try {
            // Read template and insert the user's package
            String input = IOUtils.toString(templateInputStream);
            input = input.replace("__TOP_LEVEL_PACKAGE__", topLevelPackage.getFullyQualifiedPackageName());
            input = input.replace("__APP_NAME__", languageName);
            input = input.replace("__LOCALE__", locale.getLanguage());
            input = input.replace("__LANGUAGE__", StringUtils.capitalize(language));
            if (flagGraphic != null) {
                input = input.replace("__FLAG_FILE__", flagGraphic.getName());
            } else {
                input = input.replace("__FLAG_FILE__", locale.getCountry().toLowerCase() + ".png");
            }
            input = input.replace("__MESSAGE_BUNDLE__", messageBundle.getName());

            // Output the file for the user
            final MutableFile mutableFile = fileManager.createFile(destinationFile);
            outputStream = mutableFile.getOutputStream();
            IOUtils.write(input, outputStream);
        } catch (final IOException ioe) {
            throw new IllegalStateException("Unable to create '" + languageName + "Language.java'", ioe);
        } finally {
            IOUtils.closeQuietly(templateInputStream);
            IOUtils.closeQuietly(outputStream);
        }
    }
}

From source file:org.squale.welcom.taglib.aide.Aide.java

/**
 * Accesseur/*w  w w. ja  va  2 s  .c  om*/
 * 
 * @param key la cle
 * @param locale la locale
 * @return le default url
 * @throws AideException exception susceptible d'etre levee
 */
public String getUrlDefault(final String key, final Locale locale) throws AideException {
    String value = "";

    try {
        // if (getAideRessource(locale)==null)
        // {
        // addAideRessource(locale);
        // }
        final ResourceBundle ressourceBundle = java.util.ResourceBundle.getBundle(fileBundle, locale);

        try {
            value = ressourceBundle.getString(AideRessource.KEY_DEFAULT);
        } catch (final MissingResourceException e) {
            // Catch de l'exception pour pas quelle soir gere par le systeme
            // cf finnnaly
        } finally {
            if ((value == null) || value.equals("")) {
                throw new AideException(
                        "Pas de valeur associ a la clef " + key + " pour la locale " + locale + "!!!");
            }
        }

        // String value = getAideRessource(locale).getString(AideRessource.KEY_DEFAULT);
        log.warn("NOTFOUND : use key :" + AideRessource.KEY_DEFAULT + ", pour la Locale (" + locale.getCountry()
                + "_" + locale.getLanguage() + ") Key : " + key + " Value :" + value);
    } catch (final AideException ae) {
        log.warn("NOTFOUND : default key :" + AideRessource.KEY_DEFAULT
                + ", impossible d'afficher une page d'aide");

        throw new AideException("Aide non disponible");
    }

    return value;
}

From source file:org.acmsl.commons.BundleI14able.java

/**
 * Fourth attempt to retrieve the bundle.
 * @param bundleName the bundle name.//from   w  w  w.  j  a  va2s. c  om
 * @param locale the locale.
 * @return the bundle.
 * @throws MissingResourceException if the resource is missing.
 */
@Nullable
protected final ResourceBundle fourthTry(@NotNull final String bundleName, @NotNull final Locale locale)
        throws MissingResourceException {
    @Nullable
    ResourceBundle result = null;

    Throwable exceptionThrown = null;

    MissingResourceException exceptionToThrow = null;

    try {
        result = new PropertyResourceBundle(new FileInputStream(
                bundleName + "_" + locale.getLanguage() + "_ " + locale.getCountry() + Literals.PROPERTIES));
    } catch (final FileNotFoundException secondFileNotFoundException) {
        exceptionThrown = secondFileNotFoundException;
    } catch (final IOException secondIOException) {
        exceptionThrown = secondIOException;
    } finally {
        if (exceptionThrown != null) {
            try {
                result = fifthTry(bundleName, locale);
            } catch (final MissingResourceException missingResource) {
                exceptionToThrow = missingResource;
            }
        }
    }

    if (exceptionToThrow != null) {
        throw exceptionToThrow;
    }

    return result;
}

From source file:com.sun.faces.application.ViewHandlerImpl.java

/**
 * Attempts to find a matching locale based on <code>perf</code> and
 * list of supported locales, using the matching algorithm
 * as described in JSTL 8.3.2.//from www  .  ja va 2s  .c  om
 */
protected Locale findMatch(FacesContext context, Locale perf) {
    Locale result = null;
    Iterator it = context.getApplication().getSupportedLocales();
    while (it.hasNext()) {
        Locale supportedLocale = (Locale) it.next();

        if (perf.equals(supportedLocale)) {
            // exact match
            result = supportedLocale;
            break;
        } else {
            // Make sure the preferred locale doesn't have country
            // set, when doing a language match, For ex., if the
            // preferred locale is "en-US", if one of supported
            // locales is "en-UK", even though its language matches
            // that of the preferred locale, we must ignore it.
            if (perf.getLanguage().equals(supportedLocale.getLanguage())
                    && supportedLocale.getCountry().equals("")) {
                result = supportedLocale;
            }
        }
    }
    // if it's not in the supported locales,
    if (null == result) {
        Locale defaultLocale = context.getApplication().getDefaultLocale();
        if (defaultLocale != null) {
            if (perf.equals(defaultLocale)) {
                // exact match
                result = defaultLocale;
            } else {
                // Make sure the preferred locale doesn't have country
                // set, when doing a language match, For ex., if the
                // preferred locale is "en-US", if one of supported
                // locales is "en-UK", even though its language matches
                // that of the preferred locale, we must ignore it.
                if (perf.getLanguage().equals(defaultLocale.getLanguage())
                        && defaultLocale.getCountry().equals("")) {
                    result = defaultLocale;
                }
            }
        }
    }

    return result;
}

From source file:com.frameworkset.platform.cms.driver.i18n.CmsLocaleManager.java

/**
 * Adds a locale to the list of available locales.<p>
 * // ww w.  j av  a 2s.  c  o  m
 * @param localeName the locale to add
 */
public void addAvailableLocale(String localeName) {

    Locale locale = getLocale(localeName);
    // add full variation (language / country / variant)
    if (!m_availableLocales.contains(locale)) {
        m_availableLocales.add(locale);
        //            if (CmsLog.INIT.isInfoEnabled()) {
        //                CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_I18N_CONFIG_ADD_LOCALE_1, locale));
        //            }
    }
    // add variation with only language and country
    locale = new Locale(locale.getLanguage(), locale.getCountry());
    if (!m_availableLocales.contains(locale)) {
        m_availableLocales.add(locale);
        //            if (CmsLog.INIT.isInfoEnabled()) {
        //                CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_I18N_CONFIG_ADD_LOCALE_1, locale));
        //            }
    }
    // add variation with language only
    locale = new Locale(locale.getLanguage());
    if (!m_availableLocales.contains(locale)) {
        m_availableLocales.add(locale);
        //            if (CmsLog.INIT.isInfoEnabled()) {
        //                CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_I18N_CONFIG_ADD_LOCALE_1, locale));
        //            }
    }
}

From source file:com.frameworkset.platform.cms.driver.i18n.CmsLocaleManager.java

/**
 * Returns the first matching locale (eventually simplified) from the available locales.<p>
 * /*from  w w w  .  j a v  a 2s .  c  o m*/
 * @param locales must be an ascending sorted list of locales in order of preference
 * @param available the available locales to find a match in
 * 
 * @return the first precise or simplified match
 */
public Locale getFirstMatchingLocale(List locales, Collection available) {

    Iterator i;
    // first try a precise match
    i = locales.iterator();
    while (i.hasNext()) {
        Locale locale = (Locale) i.next();
        if (available.contains(locale)) {
            // precise match
            return locale;
        }
    }

    // now try a match only with language and country
    i = locales.iterator();
    while (i.hasNext()) {
        Locale locale = (Locale) i.next();
        if (locale.getVariant().length() > 0) {
            // the locale has a variant, try to match without the variant
            locale = new Locale(locale.getLanguage(), locale.getCountry(), "");
            if (available.contains(locale)) {
                // match
                return locale;
            }
        }
    }

    // finally try a match only with language
    i = locales.iterator();
    while (i.hasNext()) {
        Locale locale = (Locale) i.next();
        if (locale.getCountry().length() > 0) {
            // the locale has a country, try to match without the country
            locale = new Locale(locale.getLanguage(), "", "");
            if (available.contains(locale)) {
                // match
                return locale;
            }
        }
    }

    // no match
    return null;
}

From source file:net.sourceforge.subsonic.service.SettingsService.java

/**
 * Sets the locale (for language, date format etc.)
 *
 * @param locale The locale./*from w  ww .j a v  a2 s .  c  o  m*/
 */
public void setLocale(Locale locale) {
    setProperty(KEY_LOCALE_LANGUAGE, locale.getLanguage());
    setProperty(KEY_LOCALE_COUNTRY, locale.getCountry());
    setProperty(KEY_LOCALE_VARIANT, locale.getVariant());
}

From source file:org.apache.logging.log4j.core.util.datetime.FastDateParserTest.java

private void validateSdfFormatFdpParseEquality(final String format, final Locale locale, final TimeZone tz,
        final DateParser fdp, final Date in, final int year, final Date cs) throws ParseException {
    final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
    sdf.setTimeZone(tz);/*from   www. j  a  va  2s.c  o  m*/
    if (format.equals(SHORT_FORMAT)) {
        sdf.set2DigitYearStart(cs);
    }
    final String fmt = sdf.format(in);
    try {
        final Date out = fdp.parse(fmt);
        assertEquals(locale.toString() + " " + in + " " + format + " " + tz.getID(), in, out);
    } catch (final ParseException pe) {
        if (year >= 1868 || !locale.getCountry().equals("JP")) {// LANG-978
            throw pe;
        }
    }
}

From source file:org.acmsl.commons.BundleI14able.java

/**
 * Third attempt to retrieve the bundle.
 * @param bundleName the bundle name./* w  ww .jav a 2 s .co m*/
 * @param locale the locale.
 * @return the bundle.
 * @throws MissingResourceException if the resource is missing.
 */
@Nullable
protected final ResourceBundle thirdTry(@NotNull final String bundleName, @NotNull final Locale locale)
        throws MissingResourceException {
    @Nullable
    ResourceBundle result = null;

    Throwable exceptionThrown = null;

    MissingResourceException exceptionToThrow = null;

    try {
        // treating bundle name as the first part of the file.
        result = new PropertyResourceBundle(new FileInputStream(bundleName + "_" + locale.getLanguage() + "_"
                + locale.getCountry() + "_" + locale.getVariant() + Literals.PROPERTIES));
    } catch (final FileNotFoundException firstFileNotFoundException) {
        exceptionThrown = firstFileNotFoundException;
    } catch (final IOException firstIOException) {
        exceptionThrown = firstIOException;
    } finally {
        if (exceptionThrown != null) {
            try {
                result = fourthTry(bundleName, locale);
            } catch (final MissingResourceException missingResource) {
                exceptionToThrow = missingResource;
            }
        }
    }

    if (exceptionToThrow != null) {
        throw exceptionToThrow;
    }

    return result;
}

From source file:org.openmrs.api.db.hibernate.HibernateOrderDAO.java

/**
 * @see OrderDAO#getOrderFrequencies(String, java.util.Locale, boolean, boolean)
 */// w w  w. j a  v a  2  s .  c  om
@Override
public List<OrderFrequency> getOrderFrequencies(String searchPhrase, Locale locale, boolean exactLocale,
        boolean includeRetired) {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(OrderFrequency.class, "orderFreq");
    criteria.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);

    //match on the concept names of the concepts
    criteria.createAlias("orderFreq.concept", "concept");
    criteria.createAlias("concept.names", "conceptName");
    criteria.add(Restrictions.ilike("conceptName.name", searchPhrase, MatchMode.ANYWHERE));
    if (locale != null) {
        List<Locale> locales = new ArrayList<Locale>(2);
        locales.add(locale);
        //look in the broader locale too if exactLocale is false e.g en for en_GB
        if (!exactLocale && StringUtils.isNotBlank(locale.getCountry())) {
            locales.add(new Locale(locale.getLanguage()));
        }
        criteria.add(Restrictions.in("conceptName.locale", locales));
    }

    if (!includeRetired) {
        criteria.add(Restrictions.eq("orderFreq.retired", false));
    }

    return criteria.list();
}