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:CurrLocaleServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    //Get the client's Locale
    Locale locale = request.getLocale();
    ResourceBundle bundle = ResourceBundle.getBundle("i18n.WelcomeBundle", locale);
    String welcome = bundle.getString("Welcome");

    NumberFormat nft = NumberFormat.getCurrencyInstance(locale);
    String formatted = nft.format(1000000);

    //Display the locale
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>" + welcome + "</title></head><body>");

    out.println("<h2>" + bundle.getString("Hello") + " " + bundle.getString("and") + " " + welcome + "</h2>");

    out.println("Locale: ");
    out.println(locale.getLanguage() + "_" + locale.getCountry());

    out.println("<br /><br />");
    out.println(formatted);//from  ww w  . ja  va2  s  .co m

    out.println("</body></html>");
    out.close();

}

From source file:org.primeframework.mvc.control.form.LocaleSelect.java

/**
 * Adds the countries Map and then calls super.
 *//*from w  ww  .j a v  a  2  s  . com*/
@Override
protected Map<String, Object> makeParameters() {
    LinkedHashMap<String, String> locales = new LinkedHashMap<>();
    String preferred = (String) attributes.get("preferredLocales");
    if (preferred != null) {
        String[] parts = preferred.split(",");
        for (String part : parts) {
            Locale locale = LocaleUtils.toLocale(part);
            locales.put(locale.toString(), locale.getDisplayName(locale));
        }
    }

    boolean includeCountries = attributes.containsKey("includeCountries")
            ? (Boolean) attributes.get("includeCountries")
            : true;
    List<Locale> allLocales = new ArrayList<>();
    Collections.addAll(allLocales, Locale.getAvailableLocales());
    allLocales.removeIf((locale) -> locale.getLanguage().isEmpty() || locale.hasExtensions()
            || !locale.getScript().isEmpty() || !locale.getVariant().isEmpty()
            || (!includeCountries && !locale.getCountry().isEmpty()));
    allLocales.sort((one, two) -> one.getDisplayName(locale).compareTo(two.getDisplayName(locale)));

    for (Locale locale : allLocales) {
        if (!locales.containsKey(locale.getCountry())) {
            locales.put(locale.toString(), locale.getDisplayName(this.locale));
        }
    }

    attributes.put("items", locales);

    return super.makeParameters();
}

From source file:com.haulmont.cuba.desktop.LoginDialog.java

protected Locale resolveLocale() {
    Locale appLocale;
    String lastLocale = this.loginProperties.loadLastLocale();
    if (StringUtils.isNotEmpty(lastLocale)) {
        appLocale = LocaleUtils.toLocale(lastLocale);
    } else {/* w  w w. ja  va 2s.co m*/
        appLocale = Locale.getDefault();
    }

    for (Locale locale : locales.values()) {
        if (locale.equals(appLocale)) {
            return locale;
        }
    }

    // if not found and application locale contains country, try to match by language only
    if (StringUtils.isNotEmpty(appLocale.getCountry())) {
        Locale languageTagLocale = Locale.forLanguageTag(appLocale.getLanguage());
        for (Locale locale : locales.values()) {
            if (Locale.forLanguageTag(locale.getLanguage()).equals(languageTagLocale)) {
                return locale;
            }
        }
    }

    // return first locale set in the cuba.availableLocales app property
    return locales.values().iterator().next();
}

From source file:org.jahia.bin.WelcomeServlet.java

protected String resolveLanguage(HttpServletRequest request, final JCRSiteNode site, JCRUserNode user,
        boolean userRedirect) throws JahiaException {
    List<Locale> siteLanguages = null;
    if (!userRedirect && site != null && !JahiaSitesService.SYSTEM_SITE_KEY.equals(site.getSiteKey())) {
        try {/*from   w  w  w.  j a  va2 s .c  o m*/
            siteLanguages = site.getActiveLiveLanguagesAsLocales();
        } catch (Exception t) {
            logger.debug("Exception while getting language settings as locales", t);
            siteLanguages = Collections.emptyList();
        }
    }

    // first we will check the preferred user locale (if it is among the
    Locale preferredLocale = UserPreferencesHelper.getPreferredLocale(user);
    if (preferredLocale != null && isLocaleSupported(site, siteLanguages, preferredLocale)) {
        return preferredLocale.toString();
    }

    // retrieve the browser locales, but if Accept-Language header is missing we won't fallback to the default system locale
    for (Enumeration<?> requestLocales = Util.getRequestLocales(request); requestLocales.hasMoreElements();) {
        final Locale curLocale = (Locale) requestLocales.nextElement();
        if (curLocale != null) {
            // check that the site contains the language and the home page exists in live for that language
            if (isLocaleSupported(site, siteLanguages, curLocale)) {
                return curLocale.toString();
            }
            if (!StringUtils.isEmpty(curLocale.getCountry())) {
                // check the same but for language only
                final Locale langOnlyLocale = LanguageCodeConverters
                        .languageCodeToLocale(curLocale.getLanguage());
                if (isLocaleSupported(site, siteLanguages, langOnlyLocale)) {
                    return langOnlyLocale.toString();
                }
            }
        }
    }

    String lang = site.getDefaultLanguage();
    if (lang != null) {
        // use site's default language
        return lang;
    }

    // nothing matches -> fallback to default
    return StringUtils.defaultIfEmpty(SettingsBean.getInstance().getDefaultLanguageCode(), DEFAULT_LOCALE);
}

From source file:com.liferay.portal.struts.PortalTilesDefinitionsFactory.java

/**
 * Calculate the suffixes based on the locale.
 * @param locale the locale//from ww  w .  ja  va  2s. com
 */
private List calculateSuffixes(Locale locale) {

    List suffixes = new ArrayList(3);
    String language = locale.getLanguage();
    String country = locale.getCountry();
    String variant = locale.getVariant();

    StringBuffer suffix = new StringBuffer();
    suffix.append('_');
    suffix.append(language);
    if (language.length() > 0) {
        suffixes.add(suffix.toString());
    }

    suffix.append('_');
    suffix.append(country);
    if (country.length() > 0) {
        suffixes.add(suffix.toString());
    }

    suffix.append('_');
    suffix.append(variant);
    if (variant.length() > 0) {
        suffixes.add(suffix.toString());
    }

    return suffixes;

}

From source file:org.auraframework.http.resource.InlineJs.java

private void appendLocaleDataJavascripts(PrintWriter out) {
    AuraLocale auraLocale = localizationAdapter.getAuraLocale();

    // Refer to the locale in LocaleValueProvider
    Locale langLocale = auraLocale.getLanguageLocale();
    Locale userLocale = auraLocale.getLocale();

    // This is for backward compatibility. At this moment, there are three locales
    // in Locale Value Provider. Keep them all available for now to avoid breaking consumers.
    String langMomentLocale = this.getMomentLocale(langLocale.toString());
    String userMomentLocale = this.getMomentLocale(userLocale.toString());
    String ltngMomentLocale = this.getMomentLocale(langLocale.getLanguage() + "_" + userLocale.getCountry());

    StringBuilder defineLocaleJs = new StringBuilder();
    // "en" data has been included in moment lib, no need to load locale data
    if (!"en".equals(langMomentLocale)) {
        String content = this.localeData.get(langMomentLocale);
        defineLocaleJs.append(content).append("\n");
    }//w ww. j  a v a 2s.  c om

    // if user locale is same as language locale, not need to load again
    if (!"en".equals(userMomentLocale) && userMomentLocale != null
            && !userMomentLocale.equals(langMomentLocale)) {
        String content = this.localeData.get(userMomentLocale);
        defineLocaleJs.append(content);
    }

    if (!"en".equals(ltngMomentLocale) && ltngMomentLocale != null && !ltngMomentLocale.equals(langMomentLocale)
            && !ltngMomentLocale.equals(userMomentLocale)) {
        String content = this.localeData.get(ltngMomentLocale);
        defineLocaleJs.append(content);
    }

    if (defineLocaleJs.length() > 0) {
        String loadLocaleDataJs = String.format("\n(function(){\n" + "    function loadLocaleData(){\n%s}\n"
                + "    window.moment? loadLocaleData() : (window.Aura || (window.Aura = {}), window.Aura.loadLocaleData=loadLocaleData);\n"
                + "})();\n", defineLocaleJs.toString());

        out.append(loadLocaleDataJs);
    }
}

From source file:edu.ku.brc.specify.prefs.SystemPrefs.java

/**
 * Constructor.//from   www  . j a v a2  s  .c  om
 */
public SystemPrefs() {
    createForm("Preferences", "System");

    JButton clearCache = form.getCompById("clearcache");

    clearCache.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            clearCache();
        }
    });

    ValBrowseBtnPanel browse = form.getCompById("7");
    if (browse != null) {
        oldSplashPath = localPrefs.get(SPECIFY_BG_IMG_PATH, null);
        browse.setValue(oldSplashPath, null);
    }

    final ValComboBox localeCBX = form.getCompById("5");
    localeCBX.getComboBox().setRenderer(new LocaleRenderer());
    localeCBX.setEnabled(false);

    SwingWorker workerThread = new SwingWorker() {
        protected int inx = -1;

        @Override
        public Object construct() {

            Vector<Locale> locales = new Vector<Locale>();
            Collections.addAll(locales, Locale.getAvailableLocales());
            Collections.sort(locales, new Comparator<Locale>() {
                public int compare(Locale o1, Locale o2) {
                    return o1.getDisplayName().compareTo(o2.getDisplayName());
                }
            });

            int i = 0;
            String language = AppPreferences.getLocalPrefs().get("locale.lang",
                    Locale.getDefault().getLanguage());
            String country = AppPreferences.getLocalPrefs().get("locale.country",
                    Locale.getDefault().getCountry());
            String variant = AppPreferences.getLocalPrefs().get("locale.var", Locale.getDefault().getVariant());

            Locale prefLocale = new Locale(language, country, variant);

            int justLangIndex = -1;
            Locale cachedLocale = Locale.getDefault();
            for (Locale l : locales) {
                try {
                    Locale.setDefault(l);
                    ResourceBundle rb = ResourceBundle.getBundle("resources", l);

                    boolean isOK = (l.getLanguage().equals("en") && StringUtils.isEmpty(l.getCountry()))
                            || (l.getLanguage().equals("pt") && l.getCountry().equals("PT"));

                    if (isOK && rb.getKeys().hasMoreElements()) {
                        if (l.getLanguage().equals(prefLocale.getLanguage())) {
                            justLangIndex = i;
                        }
                        if (l.equals(prefLocale)) {
                            inx = i;
                        }
                        localeCBX.getComboBox().addItem(l);
                        i++;
                    }

                } catch (MissingResourceException ex) {
                }
            }

            if (inx == -1 && justLangIndex > -1) {
                inx = justLangIndex;
            }
            Locale.setDefault(cachedLocale);

            return null;
        }

        @Override
        public void finished() {
            UIValidator.setIgnoreAllValidation("SystemPrefs", true);
            localeCBX.setEnabled(true);
            localeCBX.getComboBox().setSelectedIndex(inx);
            JTextField loadingLabel = form.getCompById("6");
            if (loadingLabel != null) {
                loadingLabel.setText(UIRegistry.getResourceString("LOCALE_RESTART_REQUIRED"));
            }
            UIValidator.setIgnoreAllValidation("SystemPrefs", false);
        }
    };

    // start the background task
    workerThread.start();

    ValCheckBox chk = form.getCompById("2");
    chk.setValue(localPrefs.getBoolean(VERSION_CHECK, true), "true");

    chk = form.getCompById("3");
    chk.setValue(remotePrefs.getBoolean(SEND_STATS, true), "true");

    chk = form.getCompById("9");
    chk.setValue(remotePrefs.getBoolean(SEND_ISA_STATS, true), "true");
    chk.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Collection collection = AppContextMgr.getInstance().getClassObject(Collection.class);
            if (collection != null) {
                String isaNumber = collection.getIsaNumber();
                if (StringUtils.isNotEmpty(isaNumber) && !((JCheckBox) e.getSource()).isSelected()) {
                    UIRegistry.showLocalizedMsg("ISA_STATS_WARNING");
                }
            }
        }
    });

    // Not sure why the form isn't picking up the pref automatically
    /* remove if worldwind is broken*/ValCheckBox useWWChk = form.getCompById(USE_WORLDWIND);
    /* remove if worldwind is broken*/ValCheckBox hasOGLChk = form.getCompById(SYSTEM_HasOpenGL);

    /* remove if worldwind is broken*/useWWChk.setValue(localPrefs.getBoolean(USE_WORLDWIND, false), null);
    /* remove if worldwind is broken*/hasOGLChk.setValue(localPrefs.getBoolean(SYSTEM_HasOpenGL, false), null);
    /* remove if worldwind is broken*/hasOGLChk.setEnabled(false);

    //ValCheckBox askCollChk = form.getCompById(ALWAYS_ASK_COLL);
    //askCollChk.setValue(localPrefs.getBoolean(ALWAYS_ASK_COLL, false), null);
}

From source file:jp.terasoluna.fw.message.DataSourceMessageSource.java

/**
 * ???? ??/*ww w . ja v a  2s.  c om*/
 * ????????
 * locale??????
 * locale??????
 * ???????
 * ?????
 * ????
 * 
 * @param locale
 *            
 * 
 * @return ???
 */
protected List<Locale> getAlternativeLocales(Locale locale) {
    List<Locale> locales = new ArrayList<Locale>();
    // ?????
    if (locale.getVariant().length() > 0) {
        // Locale(language,country,"")
        locales.add(new Locale(locale.getLanguage(), locale.getCountry()));
    }
    // ????
    if (locale.getCountry().length() > 0) {
        // Locale(language,"","")
        locales.add(new Locale(locale.getLanguage()));
    }
    // ?????
    if (defaultLocale != null && !locale.equals(defaultLocale)) {
        if (defaultLocale.getVariant().length() > 0) {
            // Locale(language,country,"")
            locales.add(defaultLocale);
        }
        if (defaultLocale.getCountry().length() > 0) {
            // Locale(language,country,"")
            locales.add(new Locale(defaultLocale.getLanguage(), defaultLocale.getCountry()));
        }
        // ????
        if (defaultLocale.getLanguage().length() > 0) {
            // Locale(language,"","")
            locales.add(new Locale(defaultLocale.getLanguage()));
        }
    }
    return locales;
}

From source file:org.pentaho.platform.repository2.unified.jcr.JcrRepositoryFileUtils.java

public static String getLocalizedString(final Session session, final PentahoJcrConstants pentahoJcrConstants,
        final Node localizedStringNode, IPentahoLocale pentahoLocale) throws RepositoryException {
    Assert.isTrue(isLocalizedString(session, pentahoJcrConstants, localizedStringNode));

    boolean isLocaleNull = pentahoLocale == null;

    if (pentahoLocale == null) {
        pentahoLocale = new PentahoLocale();
    }// ww  w  .  ja va 2  s.  co  m

    Locale locale = pentahoLocale.getLocale();

    final String UNDERSCORE = "_"; //$NON-NLS-1$
    final String COLON = ":"; //$NON-NLS-1$
    boolean hasLanguage = StringUtils.hasText(locale.getLanguage());
    boolean hasCountry = StringUtils.hasText(locale.getCountry());
    boolean hasVariant = StringUtils.hasText(locale.getVariant());

    List<String> candidatePropertyNames = new ArrayList<String>(3);

    if (hasVariant) {
        candidatePropertyNames.add(
                locale.getLanguage() + UNDERSCORE + locale.getCountry() + UNDERSCORE + locale.getVariant());
    }
    if (hasCountry) {
        candidatePropertyNames.add(locale.getLanguage() + UNDERSCORE + locale.getCountry());
    }
    if (hasLanguage) {
        candidatePropertyNames.add(locale.getLanguage());
    }

    for (String propertyName : candidatePropertyNames) {
        if (localizedStringNode.hasProperty(propertyName)) {
            return localizedStringNode.getProperty(propertyName).getString();
        }
    }

    String prefix = session.getNamespacePrefix(PentahoJcrConstants.PHO_NS);
    Assert.hasText(prefix);

    String propertyStr = isLocaleNull ? pentahoJcrConstants.getPHO_ROOTLOCALE()
            : prefix + COLON + locale.getLanguage();

    return localizedStringNode.getProperty(propertyStr).getString();
}

From source file:de.iew.services.impl.MessageBundleServiceImpl.java

public void loadMessageBundle(Properties messageBundle, String basename, Locale locale) {
    if (log.isDebugEnabled()) {
        log.debug("Synchronisiere MessageBundle " + basename + " fr Locale " + locale + ".");
    }//from  w  ww  .j  a v  a 2s .  co m

    MessageBundle mb;
    for (String messageKey : messageBundle.stringPropertyNames()) {
        if (log.isTraceEnabled()) {
            log.trace(messageKey + " -> " + messageBundle.getProperty(messageKey));
        }
        mb = this.messageBundleDao.findByTextKeyAndLocale(messageKey, locale.getLanguage(),
                locale.getCountry());
        if (mb == null) {
            TextItem textItem = new TextItem();
            textItem.setLanguageCode(locale.getLanguage());
            textItem.setCountryCode(locale.getCountry());
            textItem.setContent(messageBundle.getProperty(messageKey));

            mb = new MessageBundle();
            mb.setTextKey(messageKey);
            mb.setBasename(basename);
            mb.setTextItem(textItem);

            this.messageBundleDao.save(mb);
        }
    }
}