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:net.sourceforge.fenixedu.presentationTier.TagLib.sop.examsMapNew.renderers.ExamsMapContentRenderer.java

private String monthToString(int month, Locale locale) {
    switch (month) {

    case Calendar.JANUARY:
        if (locale.getLanguage().equals("pt")) {
            return "Janeiro";
        }//  w w  w  .j  a  v a 2s.  co m
        return "January";
    case Calendar.FEBRUARY:
        if (locale.getLanguage().equals("pt")) {
            return "Fevereiro";
        }
        return "February";
    case Calendar.MARCH:
        if (locale.getLanguage().equals("pt")) {
            return "Maro";
        }
        return "March";
    case Calendar.APRIL:
        if (locale.getLanguage().equals("pt")) {
            return "Abril";
        }
        return "April";
    case Calendar.MAY:
        if (locale.getLanguage().equals("pt")) {
            return "Maio";
        }
        return "May";
    case Calendar.JUNE:
        if (locale.getLanguage().equals("pt")) {
            return "Junho";
        }
        return "June";
    case Calendar.JULY:
        if (locale.getLanguage().equals("pt")) {
            return "Julho";
        }
        return "July";
    case Calendar.AUGUST:
        if (locale.getLanguage().equals("pt")) {
            return "Agosto";
        }
        return "August";
    case Calendar.SEPTEMBER:
        if (locale.getLanguage().equals("pt")) {
            return "Setembro";
        }
        return "September";
    case Calendar.OCTOBER:
        if (locale.getLanguage().equals("pt")) {
            return "Outubro";
        }
        return "October";
    case Calendar.NOVEMBER:
        if (locale.getLanguage().equals("pt")) {
            return "Novembro";
        }
        return "November";
    case Calendar.DECEMBER:
        if (locale.getLanguage().equals("pt")) {
            return "Dezembro";
        }
        return "December";
    case Calendar.UNDECIMBER:
        return "Undecember";
    default:
        return "Error";
    }
}

From source file:com.norconex.jefmon.JEFMonSession.java

private void initLocale() {
    String cookieLocale = new CookieUtils().load(SessionLocaleUtils.COOKIE_LOCALE_KEY);
    Locale[] locales = getApp().getSupportedLocales();
    Locale locale = null;
    if (StringUtils.isNotBlank(cookieLocale)) {
        locale = LocaleUtils.toLocale(cookieLocale);
    }/* w w w.  j  ava  2 s .c  o m*/
    if (!ArrayUtils.contains(locales, locale)) {
        locale = getLocale();
        if (!ArrayUtils.contains(locales, locale) && locale.getCountry() != null) {
            locale = new Locale(locale.getLanguage(), locale.getCountry());
        }
        if (!ArrayUtils.contains(locales, locale)) {
            locale = new Locale(locale.getLanguage());
        }
        if (!ArrayUtils.contains(locales, locale)) {
            locale = locales[0];
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("User initial locale is:" + locale);
        }
    }
    setLocale(locale);
}

From source file:org.smigo.species.vernacular.VernacularHandler.java

public List<Vernacular> getAnyVernaculars(int speciesId, Locale locale) {
    List<Vernacular> ret = vernacularDao.getVernacularBySpecies(speciesId);

    //this is most likely a user species
    if (ret.size() == 1) {
        return ret;
    }/*from   w w  w.j a  v a 2s  .  co  m*/

    //filter by locale
    Predicate<Vernacular> localeMatcher = vernacular -> vernacular.getLanguage().equals(locale.getLanguage())
            && (vernacular.getCountry().isEmpty() || vernacular.getCountry().equals(locale.getCountry()));
    if (ret.stream().anyMatch(localeMatcher)) {
        return ret.stream().filter(localeMatcher).collect(Collectors.toList());
    }

    //no translation available, return everything
    return ret;
}

From source file:de.hybris.platform.commercefacades.storesession.impl.DefaultStoreSessionFacade.java

protected LanguageData findMatchingLanguageByLocale(final Locale locale,
        final Collection<LanguageData> availableLanguages) {
    return findMatchingLanguageByIsoCode(locale.getLanguage(), availableLanguages);
}

From source file:de.xplib.xdbm.util.I18N.java

/**
 * @param localeIn .../*from  w  w  w .j ava 2s .c o  m*/
 */
public void setLocale(final Locale localeIn) {

    InputStream is = this.getClass().getClassLoader()
            .getResourceAsStream("de/xplib/xdbm/ui/res/i18n/" + localeIn.getLanguage() + ".xml");

    try {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

        Document doc = db.parse(is);
        this.entries.clear();

        NodeList nl = doc.getDocumentElement().getElementsByTagName("entry");

        for (int i = 0, l = nl.getLength(); i < l; i++) {
            NamedNodeMap nnm = nl.item(i).getAttributes();
            if (nnm == null) {
                continue;
            }

            Node n = nnm.getNamedItem("key");
            if (n == null) {
                continue;
            }

            this.entries.put(n.getNodeValue(), nnm);
        }

        this.notifyObservers();

    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.examproject.tweet.controller.PermalinkController.java

/**
 * date permalink page request.//from   w  ww .  j a  v a2  s .c  o m
 * expected http request is '/tweet/username/2012/05/04.html'
 */
@RequestMapping(value = "/tweet/{userName}/{year}/{month}/{day}.html", method = RequestMethod.GET)
public String doDatePermalink(@PathVariable String userName, @PathVariable String year,
        @PathVariable String month, @PathVariable String day,
        @RequestParam(value = "locale", defaultValue = "") String locale,
        @CookieValue(value = "__exmphangul_request_token", defaultValue = "") String requestToken,
        @CookieValue(value = "__exmphangul_access_token", defaultValue = "") String oauthToken,
        @CookieValue(value = "__exmphangul_token_secret", defaultValue = "") String oauthTokenSecret,
        @CookieValue(value = "__exmphangul_user_id", defaultValue = "") String userId,
        @CookieValue(value = "__exmphangul_screen_name", defaultValue = "") String screenName,
        @CookieValue(value = "__exmphangul_response_list_mode", defaultValue = "") String responseListMode,
        @CookieValue(value = "__exmphangul_user_list_name", defaultValue = "") String userListName,
        Model model) {
    LOG.debug("called.");
    try {
        // TODO: debug
        LOG.debug("userName: " + userName);
        LOG.debug("year: " + year);
        LOG.debug("month: " + month);
        LOG.debug("day: " + day);

        // get the current local.
        if (locale.equals("")) {
            Locale loc = Locale.getDefault();
            locale = loc.getLanguage();
        }

        // get the form.
        TweetForm tweetForm = getForm(userId, screenName, locale, responseListMode, userListName);

        // set the form-object to the model. 
        model.addAttribute(tweetForm);

        // get the service object.
        PermalinkService permalinkService = (PermalinkService) context.getBean(PERMALINK_SERVICE_BEAN_ID);

        // get the tweet.
        List<TweetDto> tweetDtoList = permalinkService.getTweetListByDate(userName, Integer.valueOf(year),
                Integer.valueOf(month), Integer.valueOf(day));
        LOG.debug("tweetDtoList size: " + tweetDtoList.size());

        // map the object.
        List<TweetModel> tweetModelList = new ArrayList<TweetModel>();
        for (TweetDto tweetDto : tweetDtoList) {
            TweetModel tweetModel = context.getBean(TweetModel.class);
            // map the dto-object to the model-object.
            mapper.map(tweetDto, tweetModel);
            tweetModelList.add(tweetModel);
        }

        // set the list-object to the model. 
        model.addAttribute(tweetModelList);
        model.addAttribute(year);
        model.addAttribute(month);
        model.addAttribute(day);

        if (isValidParameterOfGet(oauthToken, oauthTokenSecret, userId, screenName)) {
            // get the profile.
            ProfileModel profileModel = getProfile(oauthToken, oauthTokenSecret, responseListMode, userListName,
                    screenName);

            // set the profile model.
            model.addAttribute(profileModel);
        }

        // return view name.
        return "permalink";

    } catch (Exception e) {
        LOG.fatal(e.getMessage());
        return "error";
    }
}

From source file:com.qcadoo.view.internal.controllers.LoginController.java

@RequestMapping(value = "login", method = RequestMethod.GET)
public ModelAndView getLoginPageView(@RequestParam(required = false) final String loginError,
        @RequestParam(required = false, defaultValue = FALSE) final Boolean iframe,
        @RequestParam(required = false, defaultValue = FALSE) final Boolean popup,
        @RequestParam(required = false, defaultValue = FALSE) final Boolean logout,
        @RequestParam(required = false, defaultValue = "") final String targetUrl,
        @RequestParam(required = false, defaultValue = FALSE) final Boolean timeout,
        @RequestParam(required = false, defaultValue = FALSE) final Boolean passwordReseted,
        final Locale locale) {

    ModelAndView mav = new ModelAndView();
    mav.setViewName("qcadooView/login");
    viewParametersAppender.appendCommonViewObjects(mav);
    mav.addObject("translation", translationService.getMessagesGroup("security", locale));
    mav.addObject("currentLanguage", locale.getLanguage());
    mav.addObject("locales", translationService.getLocales());

    mav.addObject("iframe", iframe);
    mav.addObject("popup", popup);
    mav.addObject("targetUrl", targetUrl);

    if (logout) {
        mav.addObject(MESSAGE_TYPE, "success");
        mav.addObject(MESSAGE_HEADER, "security.message.logoutHeader");
        mav.addObject(MESSAGE_CONTENT, "security.message.logoutContent");
    } else if (timeout || iframe || popup) {
        mav.addObject(MESSAGE_TYPE, "info");
        mav.addObject(MESSAGE_HEADER, "security.message.timeoutHeader");
        mav.addObject(MESSAGE_CONTENT, "security.message.timeoutContent");
    } else if (StringUtils.isNotEmpty(loginError)) {
        mav.addObject(MESSAGE_TYPE, "error");
        mav.addObject(MESSAGE_HEADER, "security.message.errorHeader");
        mav.addObject(MESSAGE_CONTENT, "security.message.errorContent");
    } else if (passwordReseted) {
        mav.addObject(MESSAGE_TYPE, "success");
        mav.addObject(MESSAGE_HEADER, "security.message.passwordReset.successHeader");
        mav.addObject(MESSAGE_CONTENT, "security.message.passwordReset.successContent");
    }/*from   www . ja  v  a2s  .c om*/

    return mav;
}

From source file:ch.silviowangler.dox.TranslationServiceImpl.java

@Override
@Transactional(readOnly = true, propagation = SUPPORTS)
public String findTranslation(String key, Locale locale) throws NoTranslationFoundException {

    logger.debug("Trying to find message for key '{}' and locale '{}'", key, locale.getDisplayName());

    Translation translation = translationRepository.findByKeyAndLocale(key, locale);

    if (translation == null) {
        final Locale fallbackLocale = new Locale(locale.getLanguage());
        logger.debug("No translation found for key '{}' and locale '{}'. Falling back to locale '{}'",
                new Object[] { key, locale.getDisplayName(), fallbackLocale.getDisplayName() });
        translation = translationRepository.findByKeyAndLocale(key, fallbackLocale);

        if (translation == null && !fallbackLocale.equals(GERMAN)) {

            translation = translationRepository.findByKeyAndLocale(key, GERMAN);

            if (translation == null) {
                logger.warn("No translation found for key '{}' and locale '{}'", key, locale);
                throw new NoTranslationFoundException(key, locale);
            }//from w  w w  .  ja  v a 2  s. com
            return translation.getLanguageSpecificTranslation();

        } else {
            logger.debug("Found translation of key '{}' using fallback locale '{}'", key,
                    fallbackLocale.getDisplayName());
            if (translation == null)
                throw new NoTranslationFoundException(key, locale);
            return translation.getLanguageSpecificTranslation();
        }
    } else {
        logger.debug("Found translation of key '{}' on first attempt using locale '{}'", key,
                locale.getDisplayName());
        return translation.getLanguageSpecificTranslation();
    }
}

From source file:de.elbe5.base.data.XmlData.java

public void addLocaleAttribute(Element node, String key, Locale locale) {
    if (locale != null) {
        addAttribute(node, key, locale.getLanguage());
    }/*from   ww  w.  j  a v a 2s . c om*/
}

From source file:com.aurel.track.prop.LoginBL.java

/**
 * This method controls entire login procedure.
 *
 * @param isInTestMode//  w w w  .ja  v  a  2  s  .c  o m
 * @param isMobileApplication
 * @param username
 * @param usingContainerBasedAuthentication
 * @param password
 * @param forwardUrl
 * @param springAuthenticated
 * @param mobileApplicationVersionNo
 * @param locale
 * @return
 */
public static String login(String isInTestMode, boolean isMobileApplication, String username,
        boolean usingContainerBasedAuthentication, String password, String forwardUrl,
        boolean springAuthenticated, Integer mobileApplicationVersionNo, Locale _locale) {
    Boolean ready = (Boolean) ServletActionContext.getServletContext().getAttribute(ApplicationStarter.READY);
    if (ready == null || !ready.booleanValue()) {
        return "loading";
    }
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession httpSession = request.getSession();
    String nonce = (String) httpSession.getAttribute("NONCE");

    if ("true".equals(isInTestMode)) {
        nonce = null; // accept clear text passwords
    }

    httpSession.setAttribute(ISMOBILEAPP, isMobileApplication);

    Locale locale = _locale;
    if (locale == null) {
        locale = Locale.getDefault();
        LOGGER.debug("Requested locale is null. Using default:" + locale.getDisplayName());
    } else {
        LOGGER.debug("Requested locale " + locale.getDisplayName());
    }
    httpSession.setAttribute("localizationJSON", LocalizeJSON.encodeLocalization(locale));
    TMotdBean motd = MotdBL.loadMotd(locale.getLanguage());

    if (motd == null) {
        motd = MotdBL.loadMotd("en");
    }
    // if already logged in forward to home page
    if (SessionUtils.getCurrentUser(httpSession) != null) {

        String redirectMapEntry = "itemNavigator";
        TPersonBean personBean = (TPersonBean) httpSession.getAttribute(Constants.USER_KEY);
        if (personBean != null && personBean.getHomePage() != null
                && personBean.getHomePage().trim().length() > 0) {
            redirectMapEntry = personBean.getHomePage();
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        JSONUtility.appendBooleanValue(sb, JSONUtility.JSON_FIELDS.SUCCESS, true);
        sb.append(DATABRACE);
        JSONUtility.appendStringValue(sb, "jsonURL", redirectMapEntry + DOTACTION, true);
        sb.append("}");
        sb.append("}");
        return LoginBL.writeJSONResponse(sb); // The redirect is done by the
        // client JavaScript
    }
    // if Container Based Authentication is enabled and we can get a remote
    // user we use that one, no more questions asked. However, a local login
    // always overrules.

    if ((username == null || "".equals(username) || password == null || "".equals(password))
            && (request.getRemoteUser() != null
                    && ApplicationBean.getInstance().getSiteBean().getIsCbaAllowed())) {
        username = request.getRemoteUser();
        usingContainerBasedAuthentication = true;
    }

    List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
    StringBuilder sb = new StringBuilder();
    String redirectMapEntry = "";
    sb = LoginBL.createLoginResponseJSON(username, password, nonce, usingContainerBasedAuthentication,
            springAuthenticated, request, errors, httpSession, forwardUrl, motd, isMobileApplication, locale,
            mobileApplicationVersionNo, redirectMapEntry);

    if (errors != null && errors.size() > 0 && usingContainerBasedAuthentication) {
        return "forwardToLogin"; // could not verify container registered
        // user with Genji
    }

    if (usingContainerBasedAuthentication && !isMobileApplication) {
        ACCESSLOGGER.info("User was authenticated via container.");
        if (redirectMapEntry.isEmpty())
            return SUCCESS;
        return redirectMapEntry;
    }
    return writeJSONResponse(sb); // The redirect is done by the client
    // JavaScript
}