Example usage for java.util Locale toString

List of usage examples for java.util Locale toString

Introduction

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

Prototype

@Override
public final String toString() 

Source Link

Document

Returns a string representation of this Locale object, consisting of language, country, variant, script, and extensions as below:
language + "_" + country + "_" + (variant + "_#" | "#") + script + "_" + extensions
Language is always lower case, country is always upper case, script is always title case, and extensions are always lower case.

Usage

From source file:com.haulmont.cuba.core.global.MessageTools.java

/**
 * Locale representation depending on {@code cuba.useLocaleLanguageOnly} application property.
 *
 * @param locale locale instance/* ww  w.j  ava2s  .c o m*/
 * @return language code if {@code cuba.useLocaleLanguageOnly=true}, or full locale representation otherwise
 */
public String localeToString(Locale locale) {
    return useLocaleLanguageOnly() ? locale.getLanguage() : locale.toString();
}

From source file:marytts.http.controllers.MaryController.java

/**
 *  Method used to set the current locale
 *
 *    @param locale the new locale to set (format is the standard one like en_US for example)
 *    @throws Exception in case of unexisting local
 *///from w  w  w  .  j  ava2 s.  co m
@RequestMapping("/setLanguage")
public void setLanguage(@RequestParam(value = "language") String language) throws Exception {
    HashSet<String> result = new HashSet<String>();

    // List voices and only retrieve the names
    for (Locale l : localMary.getAvailableLocales()) {
        String[] elts = l.toString().split("_");
        if (elts.length < 2) {
            if (elts[0].equals(language)) {
                localMary.setLocale(l);
                break;
            }
        } else if (elts[0].equals(language)) {
            localMary.setLocale(l);
            break;
        }
    }

    // FIXME: how to find the default region !

    current_language = language;
}

From source file:marytts.server.http.InfoRequestHandler.java

private String handleInfoRequest(String absPath, Map<String, String> queryItems, HttpResponse response) {
    logger.debug("New info request: " + absPath);
    if (queryItems != null) {
        for (String key : queryItems.keySet()) {
            logger.debug("    " + key + "=" + queryItems.get(key));
        }//from  w  w w. j av  a 2  s . c o m
    }

    assert absPath.startsWith("/") : "Absolute path '" + absPath + "' does not start with a slash!";
    String request = absPath.substring(1); // without the initial slash

    if (request.equals("version"))
        return MaryRuntimeUtils.getMaryVersion();
    else if (request.equals("datatypes"))
        return MaryRuntimeUtils.getDataTypes();
    else if (request.equals("locales"))
        return MaryRuntimeUtils.getLocales();
    else if (request.equals("voices"))
        return MaryRuntimeUtils.getVoices();
    else if (request.equals("audioformats"))
        return MaryRuntimeUtils.getAudioFileFormatTypes();
    else if (request.equals("exampletext")) {
        if (queryItems != null) {
            // Voice example text
            String voice = queryItems.get("voice");
            if (voice != null) {
                return MaryRuntimeUtils.getVoiceExampleText(voice);
            }
            String datatype = queryItems.get("datatype");
            String locale = queryItems.get("locale");
            if (datatype != null && locale != null) {
                Locale loc = MaryUtils.string2locale(locale);
                return MaryRuntimeUtils.getExampleText(datatype, loc);
            }
        }
        MaryHttpServerUtils.errorMissingQueryParameter(response, "'datatype' and 'locale' or 'voice'");
        return null;
    } else if (request.equals("audioeffects"))
        return MaryRuntimeUtils.getDefaultAudioEffects();
    else if (request.equals("audioeffect-default-param")) {
        if (queryItems != null) {
            String effect = queryItems.get("effect");
            if (effect != null)
                return MaryRuntimeUtils.getAudioEffectDefaultParam(effect);
        }
        MaryHttpServerUtils.errorMissingQueryParameter(response, "'effect'");
        return null;
    } else if (request.equals("audioeffect-full")) {
        if (queryItems != null) {
            String effect = queryItems.get("effect");
            String params = queryItems.get("params");
            if (effect != null && params != null) {
                return MaryRuntimeUtils.getFullAudioEffect(effect, params);
            }
        }
        MaryHttpServerUtils.errorMissingQueryParameter(response, "'effect' and 'params'");
        return null;
    } else if (request.equals("audioeffect-help")) {
        if (queryItems != null) {
            String effect = queryItems.get("effect");
            if (effect != null) {
                return MaryRuntimeUtils.getAudioEffectHelpText(effect);
            }
        }
        MaryHttpServerUtils.errorMissingQueryParameter(response, "'effect'");
        return null;
    } else if (request.equals("audioeffect-is-hmm-effect")) {
        if (queryItems != null) {
            String effect = queryItems.get("effect");
            if (effect != null) {
                return MaryRuntimeUtils.isHmmAudioEffect(effect);
            }
        }
        MaryHttpServerUtils.errorMissingQueryParameter(response, "'effect'");
        return null;
    } else if (request.equals("features") || request.equals("features-discrete")) {
        if (queryItems != null) {
            // List of features that can be computed for the voice
            FeatureProcessorManager mgr = null;
            String voiceName = queryItems.get("voice");
            String localeName = queryItems.get("locale");
            if (voiceName != null) {
                Voice voice = Voice.getVoice(voiceName);
                if (voice == null) {
                    MaryHttpServerUtils.errorWrongQueryParameterValue(response, "voice", voiceName,
                            "No voice with that name");
                    return null;
                }
                mgr = FeatureRegistry.getFeatureProcessorManager(voice);
                if (mgr == null) {
                    mgr = FeatureRegistry.getFeatureProcessorManager(voice.getLocale());
                }
                if (mgr == null) {
                    mgr = FeatureRegistry
                            .getFeatureProcessorManager(new Locale(voice.getLocale().getLanguage()));
                }
                if (mgr == null) {
                    mgr = FeatureRegistry.getFallbackFeatureProcessorManager();
                }
            } else if (localeName != null) {
                Locale locale = MaryUtils.string2locale(localeName);
                mgr = FeatureRegistry.getFeatureProcessorManager(locale);
                if (mgr == null) {
                    mgr = FeatureRegistry.getFeatureProcessorManager(new Locale(locale.getLanguage()));
                }
                if (mgr == null) {
                    StringBuilder localeList = new StringBuilder();
                    for (Locale l : FeatureRegistry.getSupportedLocales()) {
                        if (localeList.length() > 0)
                            localeList.append(",");
                        localeList.append(l.toString());
                    }
                    MaryHttpServerUtils.errorWrongQueryParameterValue(response, "locale", localeName,
                            "The locale is not supported.<br />" + "Supported locales: <code>" + localeList
                                    + "</code>");
                    return null;
                }
            }
            if (mgr != null)
                if (request.equals("features-discrete")) {
                    String discreteFeatureNames = mgr.listByteValuedFeatureProcessorNames()
                            + mgr.listShortValuedFeatureProcessorNames();
                    return discreteFeatureNames;
                }
            return mgr.listFeatureProcessorNames();
        }
        MaryHttpServerUtils.errorMissingQueryParameter(response, "'voice' or 'locale'");
        return null;
    } else if (request.equals("vocalizations")) {
        if (queryItems != null) {
            String voice = queryItems.get("voice");
            if (voice != null) {
                return MaryRuntimeUtils.getVocalizations(voice);
            }
        }
        MaryHttpServerUtils.errorMissingQueryParameter(response, "'voice'");
        return null;
    } else if (request.equals("styles")) {
        if (queryItems != null) {
            String voice = queryItems.get("voice");
            if (voice != null) {
                return MaryRuntimeUtils.getStyles(voice);
            }
        }
        MaryHttpServerUtils.errorMissingQueryParameter(response, "'voice'");
        return null;
    }
    MaryHttpServerUtils.errorFileNotFound(response, request);
    return null;
}

From source file:it.cnr.icar.eric.client.xml.registry.infomodel.InternationalStringImpl.java

private String getKey(Locale l, String charSetName) {
    return charSetName + "_" + l.toString();
}

From source file:org.hoteia.qalingo.core.i18n.message.CoreMessageSource.java

public String getMessage(final String code, final Object args[], final Locale locale)
        throws NoSuchMessageException {
    try {//from ww  w  .  j  ava  2 s  .c  o  m
        return messageSource.getMessage(code, args, locale);
    } catch (Exception e) {
        logger.info("This message key doesn't exist: " + code + ", for this locale: " + locale.toString());
        if (BooleanUtils.negate(locale.toString().equalsIgnoreCase(Constants.DEFAULT_LOCALE_CODE))) {
            return getMessage(code, args, new Locale(Constants.DEFAULT_LOCALE_CODE));
        }
    }
    return null;
}

From source file:org.dspace.app.webui.discovery.DiscoverySearchRequestProcessor.java

private Map<String, String> getLabels(HttpServletRequest request) {
    // Get access to the localized resource bundle
    Locale locale = UIUtil.getSessionLocale(request);
    Map<String, String> labelMap = localeLabels.get(locale.toString());
    if (labelMap == null) {
        labelMap = getLocaleLabels(locale);
        localeLabels.put(locale.toString(), labelMap);
    }/*from w  w  w .j  a  v  a 2 s .c o m*/
    return labelMap;
}

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  .ja  va 2  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.npower.dm.util.MessageResources.java

/**
 * Compute and return a key to be used in caching information by a Locale.
 * <strong>NOTE</strong> - The locale key for the default Locale in our
 * environment is a zero length String.//from  w  ww  . j a  va 2  s.c o m
 *
 * @param locale The locale for which a key is desired
 */
protected String localeKey(Locale locale) {
    return (locale == null) ? "" : locale.toString();
}

From source file:org.openmrs.module.appointmentscheduling.web.controller.AppointmentBlockListController.java

@RequestMapping(value = "/module/appointmentscheduling/appointmentBlockList", method = RequestMethod.GET)
public void showForm(HttpServletRequest request, ModelMap model) throws ParseException {
    //Initializing the default properties of the appointment block list page.
    if (Context.isAuthenticated()) {
        //Set the location from the session
        if (request.getSession().getAttribute("chosenLocation") != null) {
            Location location = (Location) request.getSession().getAttribute("chosenLocation");
            model.addAttribute("chosenLocation", location);
        }/*ww w .  ja  va  2s .com*/
        //Set the provider from the session
        if (request.getSession().getAttribute("chosenProvider") != null) {
            Provider provider = Context.getProviderService()
                    .getProvider((Integer) request.getSession().getAttribute("chosenProvider"));
            model.addAttribute("chosenProvider", provider.getProviderId());
        }
        //Set the appointmentType from the session
        if (request.getSession().getAttribute("chosenType") != null) {
            AppointmentType appointmentType = Context.getService(AppointmentService.class)
                    .getAppointmentType((Integer) request.getSession().getAttribute("chosenType"));
            model.addAttribute("chosenType", appointmentType.getAppointmentTypeId());
        }
        //Set the date interval from the session
        String fromDate;
        String toDate;

        fromDate = (String) request.getSession().getAttribute("fromDate");
        toDate = (String) request.getSession().getAttribute("toDate");
        Calendar cal = Context.getDateTimeFormat().getCalendar();
        if (fromDate == null && toDate == null) {
            //In case the user loaded the page for the first time, we will set to default the time interval (1 week from today).
            fromDate = Context.getDateTimeFormat().format(OpenmrsUtil.firstSecondOfDay(new Date()));
            cal.setTime(OpenmrsUtil.getLastMomentOfDay(new Date()));
            cal.add(Calendar.DAY_OF_MONTH, 6);
            toDate = Context.getDateTimeFormat().format(cal.getTime());
        } else {
            //Session is not empty and we need to change the locale if we have to.
            Locale lastLocale = (Locale) request.getSession().getAttribute("lastLocale");
            Locale currentLocale = Context.getLocale();
            //check if the last locale equals to the current locale
            if (lastLocale != null && lastLocale.toString().compareTo(currentLocale.toString()) != 0) {
                //if the locals are different 
                fromDate = Context.getDateTimeFormat()
                        .format(OpenmrsUtil.getDateTimeFormat(lastLocale).parse(fromDate));
                toDate = Context.getDateTimeFormat()
                        .format(OpenmrsUtil.getDateTimeFormat(lastLocale).parse(toDate));
            }
        }
        //Update session variables - this will be updated in every locale change.
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("fromDate", fromDate);
        httpSession.setAttribute("toDate", toDate);
        httpSession.setAttribute("lastLocale", Context.getLocale());

        //Update model variables - what the page shows.
        model.addAttribute("fromDate", fromDate);
        model.addAttribute("toDate", toDate);
    }

}

From source file:com.aurel.track.lucene.search.listFields.LocalizedListSearcher.java

/**
 * Gets the lucene query when no field is specified,
 * that means search the entire localized index by label, default localized or locale 
 * @param analyzer//from   www.  j a  v  a  2 s.  co m
 * @param toBeProcessedString
 * @param fieldID
 * @param locale
 * @return
 */
@Override
protected Query getNoExlplicitFieldQuery(Analyzer analyzer, String toBeProcessedString, Locale locale) {
    QueryParser queryParser = new QueryParser(getLabelFieldName(), analyzer);
    Query query = null;
    try {
        //search for both localized and not localized value
        query = queryParser.parse(getLabelFieldName() + LuceneSearcher.FIELD_NAME_VALUE_SEPARATOR
                + toBeProcessedString + " OR " + locale.toString() + LuceneSearcher.FIELD_NAME_VALUE_SEPARATOR
                + toBeProcessedString + " OR " + LuceneUtil.LIST_INDEX_FIELDS_LOCALIZED.DEFAULT_LOCALIZED
                + LuceneSearcher.FIELD_NAME_VALUE_SEPARATOR + toBeProcessedString);
    } catch (ParseException e) {
        LOGGER.error("Parsing the no field query string for fieldValue '" + toBeProcessedString
                + "' failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    return query;
}