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:fr.paris.lutece.portal.web.admin.AdminMenuJspBean.java

/**
 * Returns the html code of the menu of the users
 * @param request The Http request/*from ww  w . j a  va  2 s.c om*/
 * @return The html code of the users menu
 */
public String getAdminMenuUser(HttpServletRequest request) {
    AdminUser user = AdminUserService.getAdminUser(request);

    Locale locale = user.getLocale();

    // Displays the menus according to the users rights
    List<FeatureGroup> listFeatureGroups = getFeatureGroupsList(user);

    Map<String, Object> model = new HashMap<String, Object>();

    model.put(MARK_FEATURE_GROUP_LIST, listFeatureGroups);
    model.put(MARK_USER, user);
    model.put(MARK_LANGUAGES_LIST, I18nService.getAdminLocales(locale));
    model.put(MARK_CURRENT_LANGUAGE, locale.getLanguage());
    model.put(MARK_MODIFY_PASSWORD_URL, AdminAuthenticationService.getInstance().getChangePasswordPageUrl());

    setDashboardData(model, user, request);

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_ADMIN_HOME, locale, model);

    return template.getHtml();
}

From source file:it.cnr.icar.eric.server.query.CompressContentQueryFilterPlugin.java

private String getLocalizedString(ServerRequestContext context, List<?> lsList) {
    Locale locale = context.getLocale();
    Iterator<?> lsItr = lsList.iterator();
    String value = null;//from   w  w w .ja v  a  2s. c  o  m
    while (lsItr.hasNext()) {
        LocalizedStringType ls = (LocalizedStringType) lsItr.next();
        String lang = ls.getLang();
        String userLang = locale.getLanguage();
        if (lang.equalsIgnoreCase(userLang)) {
            value = ls.getValue();
            break;
        } else if (lang.indexOf(userLang) != -1 || userLang.indexOf(lang) != -1) {
            //TODO: make the locale match more robust
            value = ls.getValue();
            break;
        }
    }
    if (value == null) {
        if (lsItr.hasNext()) {
            LocalizedStringType ls = (LocalizedStringType) lsList.get(0);
            value = ls.getValue();
        }
    }
    return value;
}

From source file:com.globalsight.connector.blaise.BlaiseCreateJobHandler.java

private void setEntryInfo(HttpServletRequest request)
        throws LocaleManagerException, RemoteException, GeneralException {
    HttpSession session = request.getSession(false);
    Locale uiLocale = (Locale) session.getAttribute(UILOCALE);

    HashMap<Long, String> id2FileNameMap = new HashMap<Long, String>();
    HashMap<Long, String> id2LocaleMap = new HashMap<Long, String>();
    for (TranslationInboxEntryVo entry : currPageEntries) {
        id2FileNameMap.put(entry.getId(), BlaiseHelper.getEntryFileName(entry));

        Locale javaLocale = entry.getTargetLocale();
        String localeCode = BlaiseHelper.fixLocale(javaLocale.getLanguage() + "_" + javaLocale.getCountry());
        StringBuilder sb = new StringBuilder(localeCode).append(" (")
                .append(javaLocale.getDisplayLanguage(uiLocale)).append("_")
                .append(javaLocale.getDisplayCountry(uiLocale)).append(")");
        id2LocaleMap.put(entry.getId(), sb.toString());
    }//from ww w.ja v  a 2s  . co m

    getSessionManager(request).setAttribute("id2FileNameMap", id2FileNameMap);
    getSessionManager(request).setAttribute("id2LocaleMap", id2LocaleMap);
}

From source file:it.uniud.ailab.dcore.annotation.annotators.StopwordSimpleFilterAnnotator.java

/**
 * Loads the stopword database according to the path and language specified
 * in the constructor.//  ww  w  .  j  av a  2 s  .  c  o  m
 *
 * @param lang the language to search in the database
 * @throws IOException if the database file is nonexistent or non accessible
 * @throws ParseException if the database file is malformed
 * @throws NullPointerException if the language requested is not in the
 * database
 */
private void loadDatabase(Locale lang) throws IOException, ParseException {
    // Get the POS pattern file and parse it.

    InputStreamReader is;

    // running from command-line and loading inside the JAR
    if (stopwordsPath.get(lang).contains("!")) {
        is = new InputStreamReader(
                getClass().getResourceAsStream(
                        stopwordsPath.get(lang).substring(stopwordsPath.get(lang).lastIndexOf("!") + 1)),
                StandardCharsets.UTF_8);
    } else {
        // normal operation
        is = new FileReader(stopwordsPath.get(lang));
    }

    // If the language is not supported by the database, stop the execution.
    if (is == null) {
        throw new NullPointerException("Language " + lang.getLanguage() + " not available.");
    }

    List<String> doc = new BufferedReader(is).lines().collect(Collectors.toList());

    for (String line : doc) {
        // don't process comments
        if (!line.startsWith("##")) {
            String word = line.trim();
            if (!word.isEmpty())
                stopwords.add(word);
        }
    }

}

From source file:org.alfresco.repo.model.ml.MultilingualContentServiceImpl2.java

/** {@inheritDoc} */
public List<Locale> getMissingTranslations(NodeRef localizedNodeRef, boolean addThisNodeLocale) {
    List<Locale> foundLocales = new ArrayList<Locale>(getTranslations(localizedNodeRef).keySet());
    List<String> foundLanguages = new ArrayList<String>();

    // transform locales into languages codes
    for (Locale locale : foundLocales) {
        foundLanguages.add(locale.getLanguage());
    }//from ww w. j a  v  a2s  .c  om

    // add the locale of the given node if required
    if (addThisNodeLocale) {
        Locale localeNode = (Locale) nodeService.getProperty(localizedNodeRef, ContentModel.PROP_LOCALE);

        if (localeNode != null) {
            foundLanguages.remove(localeNode.toString());
        } else {
            logger.warn("No locale found for the node " + localizedNodeRef);
        }
    }

    List<String> missingLanguages = null;

    if (foundLanguages.size() == 0) {
        // The given node is the only one available translation and it must
        // be return.
        // MissingLanguages become the entire list pf languages.
        missingLanguages = contentFilterLanguagesService.getFilterLanguages();
    } else {
        // get the missing languages form the list of content filter
        // languages
        missingLanguages = contentFilterLanguagesService.getMissingLanguages(foundLanguages);
    }
    // construct a list of locales
    List<Locale> missingLocales = new ArrayList<Locale>(missingLanguages.size() + 1);

    for (String lang : missingLanguages) {
        missingLocales.add(I18NUtil.parseLocale(lang));
    }

    return missingLocales;
}

From source file:com.seer.datacruncher.validation.Logical.java

public ResultStepValidation logicalValidation(DatastreamDTO datastreamDTO, Object jaxbObject) {
    long idSchema = datastreamDTO.getIdSchema();
    Set<String> keys;
    ResultStepValidation retValue = new ResultStepValidation();
    retValue.setValid(true);/*  ww  w  .j av a 2  s.c  o m*/
    retValue.setMessageResult("");
    SchemaXSDEntity schemaXSDEntity = schemasXSDDao.read(idSchema);
    Class<?> validationClass;
    Object validationObj;
    Method factoryMethod;

    try {
        if (mapExtraCheck.keySet().size() == 0 || !mapExtraCheck.keySet().iterator().next()
                .contains(String.valueOf(datastreamDTO.getIdSchema()))) {
            mapExtraCheck = schemaFieldsDao.getMapExtraCheck(idSchema);
        }

        keys = mapExtraCheck.keySet();
        Map<String, List<String>> mapMultiClass = new HashMap<String, List<String>>();

        for (String fieldPath : keys) {
            try {
                boolean isValid = false;
                Set<String> setClass = mapExtraCheck.get(fieldPath);
                SchemaFieldEntity fieldEntity = schemaFieldsDao.getFieldByPath(fieldPath, idSchema, "/");

                String suggestions = "";
                String elementValue = CommonUtils.parseXMLandInvokeDoSomething(
                        new ByteArrayInputStream(datastreamDTO.getOutput().getBytes()), fieldPath, jaxbObject);
                if (elementValue == null) {
                    isValid = true;
                } else {

                    if (setClass != null && setClass.size() > 0) {
                        for (String checkInfo : setClass) {
                            String checkType = checkInfo.substring(checkInfo.indexOf(":") + 1,
                                    checkInfo.lastIndexOf("_"));
                            String extraCheckType = checkInfo.substring(checkInfo.indexOf("_") + 1,
                                    checkInfo.lastIndexOf("-"));
                            String className = checkInfo.substring(checkInfo.lastIndexOf("-") + 1);

                            if (checkType.contains("@spellcheck")) {

                                long idCheckType = Long.parseLong(className);
                                ChecksTypeEntity checksTypeEntity = checksTypeDao.find(idCheckType);

                                if (checksTypeEntity == null) {
                                    continue;
                                }
                                String description = checksTypeEntity.getName();
                                Locale locale = Locale.ENGLISH;
                                for (LanguagesList langs : LanguagesList.values()) {
                                    if (description.endsWith(langs.toString())) {
                                        locale = langs.getLocale();
                                        break;
                                    }
                                }
                                SpellChecker spellChecker = new SpellChecker(locale.getLanguage());

                                if (!spellChecker.exist(elementValue)) {
                                    String suggestion = MessageFormat
                                            .format(I18n.getMessage("message.spellCheckError"),
                                                    getPrefix(fieldEntity), elementValue,
                                                    Arrays.toString(spellChecker.getSuggestions(elementValue)))
                                            .concat("\n");
                                    suggestions += suggestion;
                                } else {
                                    isValid = true;
                                    break;
                                }
                            } else if (checkType.contains("singleValidation")) {
                                if (!extraCheckType.equalsIgnoreCase("Custom code")
                                        && !className.contains("com.seer.datacruncher.validation."))
                                    className = "com.seer.datacruncher.validation." + className;

                                if (extraCheckType.equalsIgnoreCase("Custom Code")) {
                                    validationObj = getCustomCodeInstance(checkType, className);
                                } else {
                                    validationClass = Class.forName(className);
                                    try {
                                        factoryMethod = validationClass.getDeclaredMethod("getInstance");
                                        validationObj = factoryMethod.invoke(null, (Object[]) null);
                                    } catch (Exception exception) {
                                        validationObj = validationClass.newInstance();
                                    }
                                }
                                if (validationObj != null && validationObj instanceof SingleValidation) {
                                    SingleValidation singleValidation = (SingleValidation) validationObj;
                                    ResultStepValidation localRetValue = singleValidation
                                            .checkValidity(elementValue);
                                    if (localRetValue != null && !localRetValue.isValid()) {
                                        suggestions += getPrefix(fieldEntity) + localRetValue.getMessageResult()
                                                + "\n";
                                    } else {
                                        isValid = true;
                                        break;
                                    }
                                } else {
                                    suggestions += getPrefix(fieldEntity) + MessageFormat
                                            .format(I18n.getMessage("error.validationClass"), className) + "\n";
                                }

                            } else if (checkType.contains("multipleValidation")) {
                                if (!className.contains("com.seer.datacruncher.validation."))
                                    className = "com.seer.datacruncher.validation." + className;
                                if (mapMultiClass.size() > 0 && mapMultiClass.containsKey(className)) {
                                    List<String> info = mapMultiClass.get(className);

                                    if (info.get(0) != null && info.get(0).equals("true")) {
                                        isValid = true;
                                        break;
                                    } else {
                                        if (info.get(1) != null)
                                            suggestions += info.get(1);
                                    }
                                } else {
                                    validationClass = Class.forName(className);
                                    validationObj = validationClass.newInstance();
                                    if (validationObj != null && validationObj instanceof MultipleValidation) {
                                        List<String> info;
                                        MultipleValidation multipleValidation = (MultipleValidation) validationObj;
                                        ResultStepValidation localRetValue = multipleValidation
                                                .checkValidity(datastreamDTO, jaxbObject, schemaXSDEntity);
                                        if (!localRetValue.isValid()) {
                                            String msg = localRetValue.getMessageResult();
                                            String postfix = msg.endsWith("\n")
                                                    ? msg.substring(0, msg.length() - 2)
                                                    : msg;
                                            msg = getPrefix(fieldEntity) + postfix + "\n";
                                            suggestions += msg;
                                            info = new ArrayList<String>();
                                            info.add(0, "false");
                                            info.add(1, "");
                                            mapMultiClass.put(className, info);
                                        } else {
                                            info = new ArrayList<String>();
                                            info.add(0, "true");
                                            info.add(1, "");
                                            mapMultiClass.put(className, info);
                                            isValid = true;
                                            break;
                                        }
                                    } else {
                                        suggestions += getPrefix(fieldEntity) + MessageFormat.format(
                                                I18n.getMessage("error.validationClass"), className) + "\n";
                                    }
                                }

                            }
                        }
                    }

                    if (!isValid) {
                        setErrorOrWarn(fieldEntity, retValue, suggestions);
                        if (!suggestions.equals("")) {
                            if (suggestions.endsWith("\n"))
                                suggestions = suggestions.substring(0, suggestions.length() - 1);
                            appendStrToResult(retValue, suggestions);
                        }
                    }

                }

            } catch (Exception exception) {
                log.error("Logical Validation - Exception : " + exception);
                retValue.setValid(false);
                appendStrToResult(retValue, I18n.getMessage("error.system"));
                return retValue;
            }
        }

        if (retValue.getMessageResult() != null && retValue.getMessageResult().equals("")) {
            retValue.setMessageResult(I18n.getMessage("success.validationOK"));
        }
    } catch (Exception exception) {
        retValue.setValid(false);
        appendStrToResult(retValue, I18n.getMessage("error.system"));
        log.error("Logical Validation - Exception : " + exception);
        return retValue;
    }
    return retValue;
}

From source file:DateLocaleServlet.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");
    String date = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.SHORT, locale).format(new Date());

    //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(date + "<br /><br />");

    java.util.Enumeration e = bundle.getKeys();
    while (e.hasMoreElements()) {

        out.println((String) e.nextElement());
        out.println("<br /><br />");

    }// ww  w.  j a v  a2s . c o m

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

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

}

From source file:com.aurel.track.dbase.InitDatabase.java

/**
 * This method loads resource strings from properties files (ApplicationResources.properties)
 * into the database./*from   w ww. ja v a 2  s .  c o m*/
 * @throws ServletException
 */
public static void loadResourcesFromPropertiesFiles(Boolean customOnly, ServletContext servletContext) {
    Boolean useProjects = true;
    Connection con = null;
    try {
        con = getConnection();
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM ID_TABLE WHERE TABLE_NAME = 'USESPACES'");
        if (rs.next()) {
            useProjects = false; // We have an installation that uses the workspace terminology
        }
    } catch (Exception e) {
        LOGGER.error("Problem reading from ID_TABLE when checking for USESPACES");
        LOGGER.debug(STACKTRACE, e);
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception ee) {
                LOGGER.debug(ee);
            }
        }
    }
    List<Locale> locs = LocaleHandler.getPropertiesLocales();
    int numberOfLocales = locs.size();
    int step = Math.round((float) ApplicationStarter.RESOURCE_UPGRADE[1] / numberOfLocales);
    float delta = new Float(ApplicationStarter.RESOURCE_UPGRADE[1] / new Float(numberOfLocales)) - step;
    Iterator<Locale> it = locs.iterator();

    while (it.hasNext()) {
        Locale loc = it.next();
        String locCode = loc.getLanguage();
        if (ApplicationBean.getInstance().isInTestMode() && locCode != "en") {
            continue;
        }
        if (loc.getCountry() != null && !"".equals(loc.getCountry())) {
            locCode = locCode + "_" + loc.getCountry();
        }
        if (!customOnly) {
            ApplicationStarter.getInstance().actualizePercentComplete(step,
                    ApplicationStarter.RESOURCE_UPGRADE_LOCALE_TEXT + loc.getDisplayName() + "...");
            addResourceToDatabase(loc, locCode, useProjects);
        }
        addCustomResourceToDatabase(loc, locCode);
    }
    if (!customOnly) {
        ApplicationStarter.getInstance().actualizePercentComplete(step,
                ApplicationStarter.RESOURCE_UPGRADE_DEFAULT_LOCALE_TEXT);
        addResourceToDatabase(Locale.getDefault(), null, useProjects);
    }
    addCustomResourceToDatabase(Locale.getDefault(), null);
    if (!customOnly) {
        ApplicationStarter.getInstance().actualizePercentComplete(Math.round(delta),
                ApplicationStarter.RESOURCE_UPGRADE_DEFAULT_LOCALE_TEXT);
    }
}

From source file:com.aurel.track.dbase.InitDatabase.java

/**
 * Update the message of the day shown on the front page
 * @param site//ww  w.  j av a  2 s . c  o  m
 */
private static void setMessageOfTheDay() {

    Locale[] availableLocales = Locale.getAvailableLocales(); // all on this system
    ResourceBundle messages = null;
    Map<String, String> languages = new HashMap<String, String>();

    for (int i = 0; i < availableLocales.length; ++i) {
        Locale locale = availableLocales[i];
        locale = new Locale(locale.getLanguage()); // just reduce the locale to the language specific one (no country)
        messages = ResourceBundle.getBundle("resources.UserInterface.ApplicationResources", locale);
        Locale theRealLoc = messages.getLocale(); // the existing locale found here
        String test = languages.get(theRealLoc.getLanguage()); // check if the language has already been treated
        if (test == null) {

            languages.put(theRealLoc.getLanguage(), "x");

            String motdMessage = messages.getString("motd.message");
            String motdTeaser = messages.getString("motd.teaser");

            TMotdBean motd = MotdBL.loadMotd(theRealLoc.getLanguage());
            try {
                if (motd == null && motdMessage != null && motdMessage.trim().length() > 0) {
                    motd = new TMotdBean();
                    motd.setTheLocale(theRealLoc.getLanguage());
                    motd.setTheMessage(motdMessage);
                    motd.setTeaserText(motdTeaser);
                    MotdBL.saveMotd(motd);
                    LOGGER.info("Created new MOTD for language " + theRealLoc.getLanguage());
                } else if (motd != null && motdMessage != null && motdMessage.trim().length() > 0) {
                    motd.setTheMessage(motdMessage + " " + motd.getTheMessage());
                    motd.setTeaserText(motdTeaser);
                    MotdBL.saveMotd(motd);
                    LOGGER.info("Updated MOTD for language " + theRealLoc.getLanguage());
                }
            } catch (Exception e) {
                LOGGER.error("Error updating MOTD: " + e.getMessage());
                LOGGER.debug(STACKTRACE, e);
            }
        }
    }
}