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:gwtupload.server.UploadServlet.java

/**
 * Returns the localized text of a key.// w  ww  .  j  a  va 2 s .c  om
 */
public static String getMessage(String key, Object... pars) {
    Locale loc = getThreadLocalRequest() == null || getThreadLocalRequest().getLocale() == null
            ? new Locale("en")
            : getThreadLocalRequest().getLocale();

    ResourceBundle res = ResourceBundle.getBundle(UploadServlet.class.getName(), loc);

    String msg = res.getString(key);
    if ("zh".equals(loc.getLanguage()) && "CN".equals(loc.getCountry())) {
        msg = convertEncodingFormat(msg, "ISO-8859-1", "UTF-8");
    }
    return new MessageFormat(msg, loc).format(pars);
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.WebappDaoFactorySparqlPrep.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if (request.getAttribute("WebappDaoFactorySDBPrep.setup") != null) {
        // don't run multiple times
        filterChain.doFilter(request, response);
        return;/* w w w  . j  a  va  2 s  . co  m*/
    }

    for (Pattern skipPattern : skipPatterns) {
        Matcher match = skipPattern.matcher(((HttpServletRequest) request).getRequestURI());
        if (match.matches()) {
            log.debug("request matched a skipPattern, skipping VitroRequestPrep");
            filterChain.doFilter(request, response);
            return;
        }
    }

    javax.sql.DataSource ds = JenaDataSourceSetupBase.getApplicationDataSource(_ctx);
    StoreDesc storeDesc = (StoreDesc) _ctx.getAttribute("storeDesc");
    OntModelSelector oms = (OntModelSelector) _ctx.getAttribute("unionOntModelSelector");
    String defaultNamespace = (String) _ctx.getAttribute("defaultNamespace");
    Connection sqlConn = null;
    SDBConnection conn = null;
    Store store = null;
    Dataset dataset = null;
    WebappDaoFactory wadf = null;

    try {
        if (ds == null || storeDesc == null || oms == null) {
            throw new RuntimeException("SDB store not property set up");
        }

        try {
            sqlConn = ds.getConnection();
            conn = new SDBConnection(sqlConn);
        } catch (SQLException sqe) {
            throw new RuntimeException("Unable to connect to database", sqe);
        }
        if (conn != null) {
            store = SDBFactory.connectStore(conn, storeDesc);
            dataset = SDBFactory.connectDataset(store);
            VitroRequest vreq = new VitroRequest((HttpServletRequest) request);

            log.info("---------");

            Enumeration<String> headStrs = vreq.getHeaderNames();
            while (headStrs.hasMoreElements()) {
                String head = headStrs.nextElement();
                log.info(head + " : " + vreq.getHeader(head));
            }

            List<String> langs = new ArrayList<String>();

            log.info("Accept-Language: " + vreq.getHeader("Accept-Language"));
            Enumeration<Locale> locs = vreq.getLocales();
            while (locs.hasMoreElements()) {
                Locale locale = locs.nextElement();
                langs.add(locale.toString().replace("_", "-"));
                log.info(locale.toString() + " / " + locale.getLanguage() + " + " + locale.getCountry() + " : "
                        + locale.getDisplayCountry() + " | " + locale.getLanguage() + " : "
                        + locale.getDisplayLanguage());
            }
            WebappDaoFactoryConfig config = new WebappDaoFactoryConfig();
            config.setDefaultNamespace(defaultNamespace);
            config.setPreferredLanguages(langs);

            //okay let's make a graph-backed model
            String endpointURI = ConfigurationProperties.getBean(request)
                    .getProperty("VitroConnection.DataSource.endpointURI");

            Graph g = new SparqlGraphMultilingual(endpointURI, langs);
            //Graph g = new SparqlGraph(endpointURI);

            Model m = ModelFactory.createModelForGraph(g);
            OntModel om = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, m);
            oms = new SingleContentOntModelSelector(om, oms.getDisplayModel(), oms.getUserAccountsModel());

            dataset = DatasetFactory.create(new SparqlDatasetGraph(endpointURI));

            //DataSource datasource = DatasetFactory.create();
            //datasource.addNamedModel("fake:fake", m);
            //dataset = datasource;         

            vreq.setAssertionsWebappDaoFactory(wadf);

            wadf = new WebappDaoFactoryJena(oms, config);
            //wadf = new WebappDaoFactorySDB(oms, dataset, config);
            vreq.setWebappDaoFactory(wadf);
            vreq.setFullWebappDaoFactory(wadf);
            vreq.setUnfilteredWebappDaoFactory(wadf);
            vreq.setWebappDaoFactory(wadf);
            vreq.setDataset(dataset);
            vreq.setJenaOntModel(om);
            vreq.setOntModelSelector(oms);
        }
    } catch (Throwable t) {
        log.error("Unable to filter request to set up SDB connection", t);
    }

    request.setAttribute("WebappDaoFactorySDBPrep.setup", 1);

    try {
        filterChain.doFilter(request, response);
        return;
    } finally {
        if (conn != null) {
            conn.close();
        }
        if (dataset != null) {
            dataset.close();
        }
        if (store != null) {
            store.close();
        }
        if (wadf != null) {
            wadf.close();
        }
    }

}

From source file:info.magnolia.cms.i18n.AbstractI18nContentSupport.java

/**
 * Returns the closest locale for which {@link #isLocaleSupported(Locale)} is true.
 * <ul>/*from  www.j a  v a2s  . c  o  m*/
 * <li>If the locale has a country specified (fr_CH) the locale without country (fr) will be returned.</li>
 * <li>If the locale has no country specified (fr) the first locale with the same language but specific country (fr_CH) will be returned.</li>
 * <li>If this fails the fall-back locale is returned</li>
 * </ul>
 * Warning: if you have configured both (fr and fr_CH) this method will jiter between this two values.
 */
protected Locale getNextLocale(Locale locale) {
    // if this locale defines a country
    if (StringUtils.isNotEmpty(locale.getCountry())) {
        // try to use the language only
        Locale langOnlyLocale = new Locale(locale.getLanguage());
        if (isLocaleSupported(langOnlyLocale)) {
            return langOnlyLocale;
        }
    }
    // try to find a locale with the same language (ignore the country)
    for (Iterator<Locale> iter = getLocales().iterator(); iter.hasNext();) {
        Locale otherCountryLocale = iter.next();
        // same lang, but not the same country as well or we end up in the loop
        if (locale.getLanguage().equals(otherCountryLocale.getLanguage())
                && !locale.equals(otherCountryLocale)) {
            return otherCountryLocale;
        }
    }
    return getFallbackLocale();
}

From source file:com.android.quicksearchbox.google.GoogleSuggestClient.java

/**
 * Queries for a given search term and returns a cursor containing
 * suggestions ordered by best match.//from  w ww  .ja  v  a  2  s .  co  m
 */
private SourceResult query(String query) {
    if (TextUtils.isEmpty(query)) {
        return null;
    }
    if (!isNetworkConnected()) {
        Log.i(LOG_TAG, "Not connected to network.");
        return null;
    }
    try {
        query = URLEncoder.encode(query, "UTF-8");
        // NOTE:  This code uses resources to optionally select the search Uri, based on the
        // MCC value from the SIM.  iThe default string will most likely be fine.  It is
        // paramerterized to accept info from the Locale, the language code is the first
        // parameter (%1$s) and the country code is the second (%2$s).  This code *must*
        // function in the same way as a similar lookup in
        // com.android.browser.BrowserActivity#onCreate().  If you change
        // either of these functions, change them both.  (The same is true for the underlying
        // resource strings, which are stored in mcc-specific xml files.)
        if (mSuggestUri == null) {
            Locale l = Locale.getDefault();
            String language = l.getLanguage();
            String country = l.getCountry().toLowerCase();
            // Chinese and Portuguese have two langauge variants.
            if ("zh".equals(language)) {
                if ("cn".equals(country)) {
                    language = "zh-CN";
                } else if ("tw".equals(country)) {
                    language = "zh-TW";
                }
            } else if ("pt".equals(language)) {
                if ("br".equals(country)) {
                    language = "pt-BR";
                } else if ("pt".equals(country)) {
                    language = "pt-PT";
                }
            }
            mSuggestUri = getContext().getResources().getString(R.string.google_suggest_base, language,
                    country);
        }

        String suggestUri = mSuggestUri + query;
        if (DBG)
            Log.d(LOG_TAG, "Sending request: " + suggestUri);
        HttpGet method = new HttpGet(suggestUri);
        HttpResponse response = mHttpClient.execute(method);
        if (response.getStatusLine().getStatusCode() == 200) {

            /* Goto http://www.google.com/complete/search?json=true&q=foo
             * to see what the data format looks like. It's basically a json
             * array containing 4 other arrays. We only care about the middle
             * 2 which contain the suggestions and their popularity.
             */
            JSONArray results = new JSONArray(EntityUtils.toString(response.getEntity()));
            JSONArray suggestions = results.getJSONArray(1);
            JSONArray popularity = results.getJSONArray(2);
            if (DBG)
                Log.d(LOG_TAG, "Got " + suggestions.length() + " results");
            return new GoogleSuggestCursor(this, query, suggestions, popularity);
        } else {
            if (DBG)
                Log.d(LOG_TAG, "Request failed " + response.getStatusLine());
        }
    } catch (UnsupportedEncodingException e) {
        Log.w(LOG_TAG, "Error", e);
    } catch (IOException e) {
        Log.w(LOG_TAG, "Error", e);
    } catch (JSONException e) {
        Log.w(LOG_TAG, "Error", e);
    }
    return null;
}

From source file:net.sourceforge.jaulp.lang.PropertiesUtils.java

/**
 * Load the properties file from the given class object. The filename from the properties file
 * is the same as the simple name from the class object and it looks at the same path as the
 * given class object. If locale is not null than the language will be added to the filename
 * from the properties file.//from   w ww .ja va 2s  . c  o m
 * 
 * @param clazz
 *            the clazz
 * @param locale
 *            the locale
 * @return the properties
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Properties loadPropertiesFromClassObject(Class<?> clazz, Locale locale) throws IOException {
    if (null == clazz) {
        throw new IllegalArgumentException("Class object must not be null!!!");
    }
    StringBuilder propertiesName = new StringBuilder();
    Properties properties = null;
    String language = null;
    String filename = null;
    String pathAndFilename = null;
    File propertiesFile = null;
    String absoluteFilename = null;
    String packagePath = PackageUtils.getPackagePathWithSlash(clazz);
    List<String> missedFiles = new ArrayList<>();
    if (null != locale) {
        propertiesName.append(clazz.getSimpleName());
        language = locale.getLanguage();
        if (null != language && !language.isEmpty()) {
            propertiesName.append("_").append(language);
        }

        String country = locale.getCountry();
        if (null != country && !country.isEmpty()) {
            propertiesName.append("_").append(country);
        }
        propertiesName.append(FileExtension.PROPERTIES.getExtension());
        filename = propertiesName.toString().trim();
        pathAndFilename = packagePath + filename;
        URL url = ClassUtils.getResource(clazz, filename);

        if (url != null) {
            absoluteFilename = url.getFile();
        } else {
            missedFiles.add("File with filename '" + filename + "' does not exists.");
        }

        if (null != absoluteFilename) {
            propertiesFile = new File(absoluteFilename);
        }

        if (null != propertiesFile && propertiesFile.exists()) {
            properties = PropertiesUtils.loadProperties(pathAndFilename);
        } else {
            propertiesName = new StringBuilder();
            if (null != locale) {
                propertiesName.append(clazz.getSimpleName());
                language = locale.getLanguage();
                if (null != language && !language.isEmpty()) {
                    propertiesName.append("_").append(language);
                }
                propertiesName.append(FileExtension.PROPERTIES.getExtension());
                filename = propertiesName.toString().trim();
                pathAndFilename = packagePath + filename;
                url = ClassUtils.getResource(clazz, filename);

                if (url != null) {
                    absoluteFilename = url.getFile();
                } else {
                    missedFiles.add("File with filename '" + filename + "' does not exists.");
                }
                if (null != absoluteFilename) {
                    propertiesFile = new File(absoluteFilename);
                }
                if (null != propertiesFile && propertiesFile.exists()) {
                    properties = PropertiesUtils.loadProperties(pathAndFilename);
                }
            }
        }
    }

    if (null == properties) {
        propertiesName = new StringBuilder();
        propertiesName.append(clazz.getSimpleName()).append(FileExtension.PROPERTIES.getExtension());
        filename = propertiesName.toString().trim();
        pathAndFilename = packagePath + filename;
        URL url = ClassUtils.getResource(clazz, filename);

        if (url != null) {
            absoluteFilename = url.getFile();
        } else {
            properties = PropertiesUtils.loadProperties(pathAndFilename);
            missedFiles.add("File with filename '" + filename + "' does not exists.");
        }

        if (null != absoluteFilename) {
            propertiesFile = new File(absoluteFilename);
        }
        if (null != propertiesFile && propertiesFile.exists()) {
            properties = PropertiesUtils.loadProperties(pathAndFilename);
        }
    }
    if (properties == null) {
        for (String string : missedFiles) {
            LOGGER.info(string);
        }
    }

    return properties;
}

From source file:org.squale.welcom.addons.message.MessageResourcesAddons.java

/**
 * Get the parent Locale. e.g. en_US will return en
 * // ww w  .j  a v a  2 s.  c  o  m
 * @param currentLocale : Locale courante
 * @return locale
 */
private Locale getParentLocale(final Locale currentLocale) {
    Locale theReturnLocale = null;
    if (null == currentLocale) {
        theReturnLocale = null;
    } else if (!currentLocale.getVariant().equals("")) {
        theReturnLocale = new Locale(currentLocale.getLanguage(), currentLocale.getCountry());
    } else if (!currentLocale.getCountry().equals("")) {
        theReturnLocale = new Locale(currentLocale.getLanguage(), "");
    }

    return theReturnLocale;
}

From source file:net.rrm.ehour.ui.admin.config.panel.LocaleConfigPanel.java

@SuppressWarnings("serial")
@Override//from   w  w  w  .j  a  v  a 2s  .c  o  m
protected void addFormComponents(Form<?> configForm) {
    final DropDownChoice<Locale> localeDropDownChoice;
    final DropDownChoice<Locale> languageDropDownChoice;
    final AjaxCheckBox onlyTranslationsBox;
    final DropDownChoice<Locale> currencyDropDownChoice;
    final Label dateFormat;

    final MainConfigBackingBean configBackingBean = getPanelModelObject();

    configForm.setOutputMarkupId(true);

    // currency dropdown
    currencyDropDownChoice = new DropDownChoice<>("config.currency",
            new PropertyModel<List<Locale>>(configBackingBean, "availableCurrencies"),
            new LocaleChoiceRenderer(2));
    currencyDropDownChoice.setOutputMarkupId(true);
    configForm.add(currencyDropDownChoice);

    // date format example
    dateFormat = new Label("dateFormat", new DateModel(new Model<>(new Date()),
            configBackingBean.getLocaleCountry(), DateModel.DATESTYLE_LONG));
    dateFormat.setOutputMarkupId(true);
    configForm.add(dateFormat);

    // language selection
    languageDropDownChoice = new DropDownChoice<>("localeLanguage",
            new PropertyModel<Locale>(configBackingBean, "localeLanguage"),
            new PropertyModel<List<Locale>>(configBackingBean, "availableLanguages"),
            new LocaleChoiceRenderer(1));

    // locale selection
    localeDropDownChoice = new DropDownChoice<>("localeCountry",
            new PropertyModel<Locale>(configBackingBean, "localeCountry"),
            new PropertyModel<List<Locale>>(configBackingBean, "availableLocales"),
            new LocaleChoiceRenderer(0));
    localeDropDownChoice.setOutputMarkupId(true);
    localeDropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            // update the date format example
            Locale localeCountry = configBackingBean.getLocaleCountry();
            dateFormat.setDefaultModel(
                    new DateModel(new Model<>(new Date()), localeCountry, DateModel.DATESTYLE_LONG));
            target.add(dateFormat);

            if (localeCountry.getCountry() != null) {
                // refresh currency
                configBackingBean.setCurrency(localeCountry);
                target.add(currencyDropDownChoice);

                // and langugae
                configBackingBean.setLocaleLanguage(localeCountry);
                target.add(languageDropDownChoice);
            }
        }
    });

    configForm.add(localeDropDownChoice);

    // behaviour for language selection
    languageDropDownChoice.setEnabled(!configBackingBean.getConfig().isDontForceLanguage());
    languageDropDownChoice.setOutputMarkupId(true);
    languageDropDownChoice.setRequired(true);
    languageDropDownChoice.setLabel(new ResourceModel("admin.config.locale.languageLabel"));

    configForm
            .add(new AjaxFormComponentFeedbackIndicator("localeLanguageValidationError", localeDropDownChoice));
    configForm.add(languageDropDownChoice);

    // only translations
    onlyTranslationsBox = new AjaxCheckBox("onlyTranslations",
            new PropertyModel<Boolean>(configBackingBean, "translationsOnly")) {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            target.add(languageDropDownChoice);
        }
    };
    onlyTranslationsBox.setOutputMarkupId(true);
    onlyTranslationsBox.setEnabled(!configBackingBean.getConfig().isDontForceLanguage());
    configForm.add(onlyTranslationsBox);

    // don't force locale checkbox
    configForm.add(new AjaxCheckBox("config.dontForceLanguage") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            languageDropDownChoice.setEnabled(!configBackingBean.getConfig().isDontForceLanguage());
            target.add(languageDropDownChoice);

            onlyTranslationsBox.setEnabled(!configBackingBean.getConfig().isDontForceLanguage());
            target.add(onlyTranslationsBox);
        }
    });
}

From source file:net.technicpack.ui.lang.ResourceLoader.java

private Locale matchClosestSupportedLocale(Locale definiteLocale) {
    Locale bestSupportedLocale = null;
    int bestLocaleScore = 0;
    for (int i = 0; i < locales.length; i++) {
        Locale testLocale = locales[i];
        int testScore = 0;

        if (testLocale.getLanguage().equals(definiteLocale.getLanguage())) {
            testScore++;/*  w w  w. jav  a  2  s  . com*/

            if (testLocale.getCountry().equals(definiteLocale.getCountry())) {
                testScore++;

                if (testLocale.getVariant().equals(definiteLocale.getVariant())) {
                    testScore++;
                }
            }
        }

        if (testScore != 0 && testScore > bestLocaleScore) {
            bestLocaleScore = testScore;
            bestSupportedLocale = testLocale;
        }
    }

    if (bestSupportedLocale != null) {
        return bestSupportedLocale;
    } else {
        return Locale.getDefault();
    }
}

From source file:com.android.screenspeak.eventprocessor.ProcessorPhoneticLetters.java

/**
 * Map a character to a phonetic letter.
 */// w  w w  .  j  a v a2  s  . co  m
private String getPhoneticLetter(String locale, String letter) {
    Locale bcp47_locale = parseLanguageTag(locale);

    String normalized_letter = letter.toLowerCase(bcp47_locale);
    String value = getPhoneticLetterMap(locale).get(normalized_letter);
    if (value == null) {
        if (bcp47_locale.getCountry().isEmpty()) {
            // As a last resort, fall back to English.
            value = getPhoneticLetterMap(FALLBACK_LOCALE).get(normalized_letter);
        } else {
            // Get the letter for the base language, if possible.
            value = getPhoneticLetter(bcp47_locale.getLanguage(), normalized_letter);
        }
    }
    return value;
}

From source file:edu.ku.brc.af.core.SchemaI18NService.java

/**
 * @param lang// w w w.j  a  va  2 s . c  o  m
 * @param country
 * @param variant
 * @return
 */
public Locale getLocaleByLangCountry(final String lang, final String country, final String variant) {
    if (lang != null) {
        for (Locale l : locales) {
            if (l.getLanguage().equals(lang)) {
                if (country == null && variant == null) {
                    return l;
                }

                if (l.getCountry() != null && l.getCountry().equals(country)) {
                    if (variant == null) {
                        return l;
                    }

                    if (l.getVariant() != null && l.getVariant().equals(variant)) {
                        return l;
                    }
                }
            }
        }
    }
    return null;
}