Example usage for java.util Locale getLanguage

List of usage examples for java.util Locale getLanguage

Introduction

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

Prototype

public String getLanguage() 

Source Link

Document

Returns the language code of this Locale.

Usage

From source file:alfio.controller.EventController.java

@RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String listEvents(Model model, Locale locale) {
    List<Event> events = eventManager.getPublishedEvents();
    if (events.size() == 1) {
        return REDIRECT + "/event/" + events.get(0).getShortName() + "/";
    } else {/*from  www.ja v  a 2 s  .  co m*/
        model.addAttribute("events", events.stream().map(e -> {
            String eventDescription = eventDescriptionRepository
                    .findDescriptionByEventIdTypeAndLocale(e.getId(),
                            EventDescription.EventDescriptionType.DESCRIPTION, locale.getLanguage())
                    .orElse("");
            return new EventDescriptor(e, eventDescription);
        }).collect(Collectors.toList()));
        model.addAttribute("pageTitle", "event-list.header.title");
        model.addAttribute("event", null);

        model.addAttribute("showAvailableLanguagesInPageTop", true);
        model.addAttribute("availableLanguages", i18nManager.getSupportedLanguages());
        return "/event/event-list";
    }
}

From source file:net.sf.click.jquery.behavior.JQBehavior.java

/**
 * Returns the <tt>Locale</tt> that should be used in this behavior. The
 * returned locale must be present in the list of {@link #SUPPORTED_LANGUAGES}.
 * <p/>//from w w w .j a  va  2  s .  c  o  m
 * If a locale is not currently supported you can set the
 * {@link #SUPPORTED_LANGUAGES} manually.
 *
 * @return the locale that should be used in this behavior
 */
protected Locale getLocale() {
    Locale locale = null;

    locale = getContext().getLocale();
    String lang = locale.getLanguage();
    if (Arrays.binarySearch(SUPPORTED_LANGUAGES, lang) >= 0) {
        return locale;
    }

    locale = Locale.getDefault();
    lang = locale.getLanguage();
    if (Arrays.binarySearch(SUPPORTED_LANGUAGES, lang) >= 0) {
        return locale;
    }

    return Locale.ENGLISH;
}

From source file:hudson.model.Descriptor.java

private InputStream getHelpStream(Class c, String suffix) {
    Locale locale = Stapler.getCurrentRequest().getLocale();
    String base = c.getName().replace('.', '/') + "/help" + suffix;

    ClassLoader cl = c.getClassLoader();
    if (cl == null)
        return null;

    InputStream in;//from   w ww.j ava 2  s  . c  o m
    in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_'
            + locale.getVariant() + ".html");
    if (in != null)
        return in;
    in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html");
    if (in != null)
        return in;
    in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + ".html");
    if (in != null)
        return in;

    // default
    return cl.getResourceAsStream(base + ".html");
}

From source file:com.haulmont.cuba.web.sys.CubaApplicationServlet.java

protected Locale resolveLocale(HttpServletRequest req, Messages messages, GlobalConfig globalConfig) {
    Map<String, Locale> locales = globalConfig.getAvailableLocales();

    if (globalConfig.getLocaleSelectVisible()) {
        String lastLocale = getCookieValue(req, "LAST_LOCALE");
        if (lastLocale != null) {
            for (Locale locale : locales.values()) {
                if (locale.toLanguageTag().equals(lastLocale)) {
                    return locale;
                }/*from  w  ww . ja va2 s. co  m*/
            }
        }
    }

    Locale requestLocale = req.getLocale();
    if (requestLocale != null) {
        Locale requestTrimmedLocale = messages.getTools().trimLocale(requestLocale);
        if (locales.containsValue(requestTrimmedLocale)) {
            return requestTrimmedLocale;
        }

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

    return messages.getTools().getDefaultLocale();
}

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

@Override
public void savePrefs() {
    if (form.getValidator() == null || form.getValidator().hasChanged()) {
        super.savePrefs();

        ValCheckBox chk = form.getCompById("2");
        localPrefs.putBoolean(VERSION_CHECK, (Boolean) chk.getValue());

        chk = form.getCompById("3");
        remotePrefs.putBoolean(SEND_STATS, (Boolean) chk.getValue());

        chk = form.getCompById("9");
        remotePrefs.putBoolean(SEND_ISA_STATS, (Boolean) chk.getValue());

        /* remove if worldwind is broken*/chk = form.getCompById(USE_WORLDWIND);
        /* remove if worldwind is broken*/localPrefs.putBoolean(USE_WORLDWIND, (Boolean) chk.getValue());
        //            
        /* remove if worldwind is broken*/chk = form.getCompById(SYSTEM_HasOpenGL);
        /* remove if worldwind is broken*/localPrefs.putBoolean(SYSTEM_HasOpenGL, (Boolean) chk.getValue());
        //            
        /* remove if worldwind is broken*/chk = form.getCompById(USE_WORLDWIND);
        /* remove if worldwind is broken*/localPrefs.putBoolean(USE_WORLDWIND, (Boolean) chk.getValue());

        //chk = form.getCompById(ALWAYS_ASK_COLL);
        //localPrefs.putBoolean(ALWAYS_ASK_COLL, (Boolean)chk.getValue());

        ValComboBox localeCBX = form.getCompById("5");
        Locale item = (Locale) localeCBX.getComboBox().getSelectedItem();
        if (item != null) {
            if (item.equals(UIRegistry.getPlatformLocale())) {
                localPrefs.remove("locale.lang");
                localPrefs.remove("locale.country");
                localPrefs.remove("locale.var");

                //System.out.println("["+localPrefs.get("locale.lang", null)+"]");
                Locale.setDefault(UIRegistry.getPlatformLocale());

            } else {
                if (item.getLanguage() == null) {
                    localPrefs.remove("locale.lang");
                } else {
                    localPrefs.put("locale.lang", item.getLanguage());
                }//from  w w w .j  av a 2s  . c  om

                if (item.getCountry() == null) {
                    localPrefs.remove("locale.country");
                } else {
                    localPrefs.put("locale.country", item.getCountry());
                }

                if (item.getVariant() == null) {
                    localPrefs.remove("locale.var");
                } else {
                    localPrefs.put("locale.var", item.getVariant());
                }
            }

            ValBrowseBtnPanel browse = form.getCompById("7");
            if (browse != null) {
                String newSplashPath = browse.getValue().toString();
                if (newSplashPath != null && (oldSplashPath == null || !oldSplashPath.equals(newSplashPath))) {
                    if (newSplashPath.isEmpty()) {
                        resetSplashImage();
                        localPrefs.remove(SPECIFY_BG_IMG_PATH);

                    } else {
                        localPrefs.put(SPECIFY_BG_IMG_PATH, newSplashPath);
                        changeSplashImage();
                    }
                }
            }
            File cp = JasperReportsCache.getImagePath();

            try {
                localPrefs.flush();

            } catch (BackingStoreException ex) {
            }
        }
    }
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String getLocalization(String xml, String requestedLanguageId, boolean useDefault) {

    String value = _getCachedValue(xml, requestedLanguageId, useDefault);

    if (value != null) {
        return value;
    } else {//from   w  w w . j a  v  a 2s .  c  o  m
        value = StringPool.BLANK;
    }

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    String priorityLanguageId = null;

    Locale requestedLocale = LocaleUtil.fromLanguageId(requestedLanguageId);

    if (useDefault && LanguageUtil.isDuplicateLanguageCode(requestedLocale.getLanguage())) {

        Locale priorityLocale = LanguageUtil.getLocale(requestedLocale.getLanguage());

        if (!requestedLanguageId.equals(priorityLanguageId)) {
            priorityLanguageId = LocaleUtil.toLanguageId(priorityLocale);
        }
    }

    if (!Validator.isXml(xml)) {
        if (useDefault || requestedLanguageId.equals(systemDefaultLanguageId)) {

            value = xml;
        }

        _setCachedValue(xml, requestedLanguageId, useDefault, value);

        return value;
    }

    XMLStreamReader xmlStreamReader = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String defaultLanguageId = StringPool.BLANK;

        // Skip root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        // Find specified language and/or default language

        String defaultValue = StringPool.BLANK;
        String priorityValue = StringPool.BLANK;

        while (xmlStreamReader.hasNext()) {
            int event = xmlStreamReader.next();

            if (event == XMLStreamConstants.START_ELEMENT) {
                String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

                if (Validator.isNull(languageId)) {
                    languageId = defaultLanguageId;
                }

                if (languageId.equals(defaultLanguageId) || languageId.equals(priorityLanguageId)
                        || languageId.equals(requestedLanguageId)) {

                    String text = xmlStreamReader.getElementText();

                    if (languageId.equals(defaultLanguageId)) {
                        defaultValue = text;
                    }

                    if (languageId.equals(priorityLanguageId)) {
                        priorityValue = text;
                    }

                    if (languageId.equals(requestedLanguageId)) {
                        value = text;
                    }

                    if (Validator.isNotNull(value)) {
                        break;
                    }
                }
            } else if (event == XMLStreamConstants.END_DOCUMENT) {
                break;
            }
        }

        if (useDefault && Validator.isNotNull(priorityLanguageId) && Validator.isNull(value)
                && Validator.isNotNull(priorityValue)) {

            value = priorityValue;
        }

        if (useDefault && Validator.isNull(value)) {
            value = defaultValue;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }
    }

    _setCachedValue(xml, requestedLanguageId, useDefault, value);

    return value;
}

From source file:org.ng200.openolympus.controller.task.TaskViewController.java

@RequestMapping(method = RequestMethod.POST)
public String submitSolution(final HttpServletRequest request, final Model model, final Locale locale,
        @PathVariable("task") final Task task, final Principal principal, @Valid final SolutionDto solutionDto,
        final BindingResult bindingResult) throws IllegalStateException, IOException, ArchiveException {
    Assertions.resourceExists(task);/* ww w  .jav a2 s.c om*/

    this.assertSuperuserOrTaskAllowed(principal, task);

    final User user = this.userRepository.findByUsername(principal.getName());

    this.solutionDtoValidator.validate(solutionDto, bindingResult);
    if (bindingResult.hasErrors()) {
        model.addAttribute("taskDescriptionUUID", task.getDescriptionFile());
        model.addAttribute("taskDescriptionURI", MessageFormat
                .format(TaskViewController.TASK_DESCRIPTION_PATH_TEMPLATE, task.getDescriptionFile()));
        model.addAttribute("localisedDescriptionFragment", "taskDescription_" + locale.getLanguage());
        model.addAttribute("task", task);
        return "tasks/task";
    }

    final UUID uuid = UUID.randomUUID();
    final String solutionPath = MessageFormat.format(TaskViewController.SOLUTION_PATH_TEMPLATE,
            StorageSpace.STORAGE_PREFIX, uuid.toString(),
            solutionDto.getTaskFile().getOriginalFilename().replaceAll("[^a-zA-Z0-9-\\._]", ""));

    final File solutionFile = new File(solutionPath);
    solutionFile.getParentFile().mkdirs();

    solutionDto.getTaskFile().transferTo(solutionFile);

    Solution solution = new Solution(task, user, solutionFile.getAbsolutePath(), Date.from(Instant.now()));
    solution = this.solutionRepository.save(solution);
    this.testingService.testSolutionOnAllTests(solution);

    return MessageFormat.format("redirect:/solution?id={0}", Long.toString(solution.getId()));
}

From source file:edu.ku.brc.specify.tools.schemalocale.SchemaLocalizerDlg.java

@Override
public Vector<Locale> getLocalesInUse() {
    Hashtable<String, Boolean> localeHash = new Hashtable<String, Boolean>();

    // Add any from the Database
    Vector<Locale> localeList = getLocalesInUseInDB(schemaType);
    for (Locale locale : localeList) {
        localeHash.put(SchemaLocalizerXMLHelper.makeLocaleKey(locale.getLanguage(), locale.getCountry(),
                locale.getVariant()), true);
    }/*from w w w  .  j a  v  a  2s . c o m*/

    for (SpLocaleContainer container : tables) {
        SchemaLocalizerXMLHelper.checkForLocales(container, localeHash);
        for (LocalizableItemIFace f : container.getContainerItems()) {
            SchemaLocalizerXMLHelper.checkForLocales(f, localeHash);
        }
    }

    localeList.clear();
    for (String key : localeHash.keySet()) {
        String[] toks = StringUtils.split(key, "_");
        localeList.add(new Locale(toks[0], "", ""));
    }
    return localeList;
}

From source file:fr.paris.lutece.portal.web.admin.AdminMenuJspBean.java

/**
 * Returns the Administration header menu
 *
 * @param request The HttpServletRequest
 * @return The html code of the header//from www. j a  va2  s.  com
 */
public String getAdminMenuHeader(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    String strVersion = AppInfo.getVersion();
    String strSiteName = PortalService.getSiteName();
    AdminUser user = AdminUserService.getAdminUser(request);
    Locale locale = user.getLocale();
    List<FeatureGroup> aFeaturesGroupList = getFeatureGroupsList(user);

    // Displays the menus accroding to the rights of the users
    model.put(Markers.VERSION, strVersion);
    model.put(MARK_SITE_NAME, strSiteName);
    model.put(MARK_FEATURE_GROUP_LIST, aFeaturesGroupList);
    model.put(MARK_ADMIN_URL, AppPathService.getBaseUrl(request) + AppPathService.getAdminMenuUrl());
    model.put(MARK_USER, user);
    model.put(MARK_LANGUAGES_LIST, I18nService.getAdminLocales(locale));
    model.put(MARK_CURRENT_LANGUAGE, locale.getLanguage());

    String strLogoutUrl = AppPropertiesService.getProperty(PROPERTY_LOGOUT_URL);
    model.put(MARK_ADMIN_LOGOUT_URL, (strLogoutUrl == null) ? "" : strLogoutUrl);

    String strDocumentationUrl = AppPropertiesService.getProperty(PROPERTY_DOCUMENTATION_SUMMARY_URL);
    model.put(MARK_ADMIN_SUMMARY_DOCUMENTATION_URL, (strDocumentationUrl == null) ? null : strDocumentationUrl);

    int nZoneMax = AppPropertiesService.getPropertyInt(PROPERTY_DASHBOARD_ZONES,
            PROPERTY_DASHBOARD_ZONES_DEFAULT);
    setDashboardData(model, user, request, nZoneMax);

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_ADMIN_MENU_HEADER, user.getLocale(), model);

    return template.getHtml();
}

From source file:org.openmrs.module.emrapi.concept.HibernateEmrConceptDAO.java

@Override
@Transactional(readOnly = true)/*w  w  w  .  j av  a 2s  .  c  o  m*/
public List<ConceptSearchResult> conceptSearch(String query, Locale locale, Collection<ConceptClass> classes,
        Collection<Concept> inSets, Collection<ConceptSource> sources, Integer limit) {
    List<String> uniqueWords = getUniqueWords(query, locale);
    if (uniqueWords.size() == 0) {
        return Collections.emptyList();
    }

    List<ConceptSearchResult> results = new ArrayList<ConceptSearchResult>();

    // find matches based on name
    {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptName.class, "cn");
        criteria.add(Restrictions.eq("voided", false));
        if (StringUtils.isNotBlank(locale.getCountry()) || StringUtils.isNotBlank(locale.getVariant())) {
            Locale[] locales = new Locale[] { locale, new Locale(locale.getLanguage()) };
            criteria.add(Restrictions.in("locale", locales));
        } else {
            criteria.add(Restrictions.eq("locale", locale));
        }
        criteria.setMaxResults(limit);

        Criteria conceptCriteria = criteria.createCriteria("concept");
        conceptCriteria.add(Restrictions.eq("retired", false));
        if (classes != null) {
            conceptCriteria.add(Restrictions.in("conceptClass", classes));
        }
        if (inSets != null) {
            DetachedCriteria allowedSetMembers = DetachedCriteria.forClass(ConceptSet.class);
            allowedSetMembers.add(Restrictions.in("conceptSet", inSets));
            allowedSetMembers.setProjection(Projections.property("concept"));
            criteria.add(Subqueries.propertyIn("concept", allowedSetMembers));
        }

        for (String word : uniqueWords) {
            criteria.add(Restrictions.ilike("name", word, MatchMode.ANYWHERE));
        }

        Set<Concept> conceptsMatchedByPreferredName = new HashSet<Concept>();
        for (ConceptName matchedName : (List<ConceptName>) criteria.list()) {
            results.add(new ConceptSearchResult(null, matchedName.getConcept(), matchedName,
                    calculateMatchScore(query, uniqueWords, matchedName)));
            if (matchedName.isLocalePreferred()) {
                conceptsMatchedByPreferredName.add(matchedName.getConcept());
            }
        }

        // don't display synonym matches if the preferred name matches too
        for (Iterator<ConceptSearchResult> i = results.iterator(); i.hasNext();) {
            ConceptSearchResult candidate = i.next();
            if (!candidate.getConceptName().isLocalePreferred()
                    && conceptsMatchedByPreferredName.contains(candidate.getConcept())) {
                i.remove();
            }
        }
    }

    // find matches based on mapping
    if (sources != null) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptMap.class);
        criteria.setMaxResults(limit);

        Criteria conceptCriteria = criteria.createCriteria("concept");
        conceptCriteria.add(Restrictions.eq("retired", false));
        if (classes != null) {
            conceptCriteria.add(Restrictions.in("conceptClass", classes));
        }

        Criteria mappedTerm = criteria.createCriteria("conceptReferenceTerm");
        mappedTerm.add(Restrictions.eq("retired", false));
        mappedTerm.add(Restrictions.in("conceptSource", sources));
        mappedTerm.add(Restrictions.ilike("code", query, MatchMode.EXACT));

        for (ConceptMap mapping : (List<ConceptMap>) criteria.list()) {
            results.add(new ConceptSearchResult(null, mapping.getConcept(), null,
                    calculateMatchScore(query, mapping)));
        }
    }

    Collections.sort(results, new Comparator<ConceptSearchResult>() {
        @Override
        public int compare(ConceptSearchResult left, ConceptSearchResult right) {
            return right.getTransientWeight().compareTo(left.getTransientWeight());
        }
    });

    if (results.size() > limit) {
        results = results.subList(0, limit);
    }
    return results;
}