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:com.salesmanager.catalog.category.CategoryListAction.java

public String displayCategory() {

    try {/*from   w  ww .j a  v  a  2s  . co m*/

        super.setSize(getProductCount());// defined in configuration
        // according to template
        super.setPageStartNumber();

        // 1) Get Category

        String url = super.getRequestedEntityId();
        this.setCurrentEntity(url);
        MerchantStore store = SessionUtil.getMerchantStore(super.getServletRequest());
        CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService);
        Locale locale = (Locale) super.getLocale();

        // make a query to retrieve a category by id or seurl
        Category c = cservice.getCategoryByMerchantIdAndSeoURLAndByLang(store.getMerchantId(), url,
                locale.getLanguage());

        if (c != null) {

            CategoryDescription description = c.getCategoryDescription();

            this.setCategory(c);

            this.setMetaDescription(description.getMetatagDescription());
            this.setMetaKeywords(description.getMetatagKeywords());
            if (!StringUtils.isBlank(description.getCategoryTitle())) {
                this.setPageTitle(description.getCategoryTitle());
            } else {
                this.setPageTitle(description.getCategoryName());
            }
            this.setPageText(description.getCategoryDescription());

            // SET CURRENT MAIN CATEGORY AND SUB CATEGORY IN HTTP SESSION
            if (c.getParentId() == 0) {
                // will be used for top category display
                super.getServletRequest().getSession().setAttribute("mainUrl", c);
            } else {
                // will be used for side bar navigation categories
                super.getServletRequest().getSession().setAttribute("subCategory", c);
            }

            super.getServletRequest().getSession().setAttribute("currentCategory", c);

        }

        this.setCategories(c, this.getPageStartIndex());

    } catch (Exception e) {
        logger.error(e);
    }

    return SUCCESS;

}

From source file:com.github.spyhunter99.pdf.plugin.PdfMojo.java

/**
 * @param locales the list of locales dir to exclude
 * @param defaultLocale the default locale.
 * @return the comma separated list of default excludes and locales dir.
 * @see FileUtils#getDefaultExcludesAsString()
 * @since 1.1/* w  w  w  .j  av a  2s . c  o  m*/
 */
private static String getDefaultExcludesWithLocales(List<Locale> locales, Locale defaultLocale) {
    String excludesLocales = FileUtils.getDefaultExcludesAsString();
    for (final Locale locale : locales) {
        if (!locale.getLanguage().equals(defaultLocale.getLanguage())) {
            excludesLocales = excludesLocales + ",**/" + locale.getLanguage() + "/*";
        }
    }

    return excludesLocales;
}

From source file:CurrLocaleServlet.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");

    NumberFormat nft = NumberFormat.getCurrencyInstance(locale);
    String formatted = nft.format(1000000);

    //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("Locale: ");
    out.println(locale.getLanguage() + "_" + locale.getCountry());

    out.println("<br /><br />");
    out.println(formatted);/*www  .  j a  v  a 2 s .  co  m*/

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

}

From source file:com.liferay.portal.struts.PortalTilesDefinitionsFactory.java

/**
 * Calculate the suffixes based on the locale.
 * @param locale the locale// w  w w .  j a va  2s . c o  m
 */
private List calculateSuffixes(Locale locale) {

    List suffixes = new ArrayList(3);
    String language = locale.getLanguage();
    String country = locale.getCountry();
    String variant = locale.getVariant();

    StringBuffer suffix = new StringBuffer();
    suffix.append('_');
    suffix.append(language);
    if (language.length() > 0) {
        suffixes.add(suffix.toString());
    }

    suffix.append('_');
    suffix.append(country);
    if (country.length() > 0) {
        suffixes.add(suffix.toString());
    }

    suffix.append('_');
    suffix.append(variant);
    if (variant.length() > 0) {
        suffixes.add(suffix.toString());
    }

    return suffixes;

}

From source file:com.liferay.portal.servlet.PortletContextListener.java

public void contextInitialized(ServletContextEvent sce) {
    try {/*from  w  ww.  j a  v a  2 s  .co  m*/

        // Servlet context

        ServletContext ctx = sce.getServletContext();

        _servletContextName = StringUtil.replace(ctx.getServletContextName(), StringPool.SPACE,
                StringPool.UNDERLINE);

        // Company ids

        _companyIds = StringUtil.split(ctx.getInitParameter("company_id"));

        // Class loader

        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

        // Initialize portlets

        String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/portlet.xml")),
                Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet.xml")) };

        _portlets = PortletManagerUtil.initWAR(_servletContextName, xmls);

        // Portlet context wrapper

        Iterator itr1 = _portlets.iterator();

        while (itr1.hasNext()) {
            Portlet portlet = (Portlet) itr1.next();

            javax.portlet.Portlet portletInstance = (javax.portlet.Portlet) contextClassLoader
                    .loadClass(portlet.getPortletClass()).newInstance();

            Indexer indexerInstance = null;
            if (Validator.isNotNull(portlet.getIndexerClass())) {
                indexerInstance = (Indexer) contextClassLoader.loadClass(portlet.getIndexerClass())
                        .newInstance();
            }

            Scheduler schedulerInstance = null;
            if (Validator.isNotNull(portlet.getSchedulerClass())) {
                schedulerInstance = (Scheduler) contextClassLoader.loadClass(portlet.getSchedulerClass())
                        .newInstance();
            }

            PreferencesValidator prefsValidator = null;
            if (Validator.isNotNull(portlet.getPreferencesValidator())) {
                prefsValidator = (PreferencesValidator) contextClassLoader
                        .loadClass(portlet.getPreferencesValidator()).newInstance();

                try {
                    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) {

                        prefsValidator.validate(
                                PortletPreferencesSerializer.fromDefaultXML(portlet.getDefaultPreferences()));
                    }
                } catch (Exception e1) {
                    _log.warn("Portlet with the name " + portlet.getPortletId()
                            + " does not have valid default preferences");
                }
            }

            Map resourceBundles = null;

            if (Validator.isNotNull(portlet.getResourceBundle())) {
                resourceBundles = CollectionFactory.getHashMap();

                Iterator itr2 = portlet.getSupportedLocales().iterator();

                while (itr2.hasNext()) {
                    String supportedLocale = (String) itr2.next();

                    Locale locale = new Locale(supportedLocale);

                    try {
                        ResourceBundle resourceBundle = ResourceBundle.getBundle(portlet.getResourceBundle(),
                                locale, contextClassLoader);

                        resourceBundles.put(locale.getLanguage(), resourceBundle);
                    } catch (MissingResourceException mre) {
                        _log.warn(mre.getMessage());
                    }
                }
            }

            Map customUserAttributes = CollectionFactory.getHashMap();

            Iterator itr2 = portlet.getCustomUserAttributes().entrySet().iterator();

            while (itr2.hasNext()) {
                Map.Entry entry = (Map.Entry) itr2.next();

                String attrName = (String) entry.getKey();
                String attrCustomClass = (String) entry.getValue();

                customUserAttributes.put(attrCustomClass,
                        contextClassLoader.loadClass(attrCustomClass).newInstance());
            }

            PortletContextWrapper pcw = new PortletContextWrapper(portlet.getPortletId(), ctx, portletInstance,
                    indexerInstance, schedulerInstance, prefsValidator, resourceBundles, customUserAttributes);

            PortletContextPool.put(portlet.getPortletId(), pcw);
        }

        // Portlet class loader

        String servletPath = ctx.getRealPath("/");
        if (!servletPath.endsWith("/") && !servletPath.endsWith("\\")) {
            servletPath += "/";
        }

        File servletClasses = new File(servletPath + "WEB-INF/classes");
        File servletLib = new File(servletPath + "WEB-INF/lib");

        List urls = new ArrayList();

        if (servletClasses.exists()) {
            urls.add(new URL("file:" + servletClasses + "/"));
        }

        if (servletLib.exists()) {
            String[] jars = FileUtil.listFiles(servletLib);

            for (int i = 0; i < jars.length; i++) {
                urls.add(new URL("file:" + servletLib + "/" + jars[i]));
            }
        }

        URLClassLoader portletClassLoader = new URLClassLoader((URL[]) urls.toArray(new URL[0]),
                contextClassLoader);

        ctx.setAttribute(WebKeys.PORTLET_CLASS_LOADER, portletClassLoader);

        // Portlet display

        String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml"));

        Map newCategories = PortletManagerUtil.getWARDisplay(_servletContextName, xml);

        for (int i = 0; i < _companyIds.length; i++) {
            String companyId = _companyIds[i];

            Map oldCategories = (Map) WebAppPool.get(companyId, WebKeys.PORTLET_DISPLAY);

            Map mergedCategories = PortalUtil.mergeCategories(oldCategories, newCategories);

            WebAppPool.put(companyId, WebKeys.PORTLET_DISPLAY, mergedCategories);
        }

        // Reinitialize portal properties

        PropsUtil.init();
    } catch (Exception e2) {
        Logger.error(this, e2.getMessage(), e2);
    }
}

From source file:fi.helsinki.opintoni.integration.coursepage.CoursePageRestClient.java

@Override
public List<CoursePageNotification> getCoursePageNotifications(Set<String> courseImplementationIds,
        LocalDateTime from, Locale locale) {
    if (courseImplementationIds.isEmpty()) {
        return newArrayList();
    }// w ww. j  av  a 2 s  . c  om

    ResponseEntity<List<CoursePageNotification>> responseEntity = restTemplate.exchange(
            "{baseUrl}/course_implementation_activity"
                    + "?course_implementation_id={courseImplementationIds}&timestamp={from}&langcode={locale}",
            HttpMethod.GET, null, new ParameterizedTypeReference<List<CoursePageNotification>>() {
            }, baseUrl, courseImplementationIds.stream().collect(Collectors.joining(",")),
            from.format(DateFormatter.COURSE_PAGE_DATE_TIME_FORMATTER), locale.getLanguage());

    return Optional.ofNullable(responseEntity.getBody()).orElse(newArrayList());
}

From source file:com._17od.upm.gui.OptionsDialog.java

private void okButtonAction() {
    try {//from   w w  w .j a  va 2 s . c  o  m
        if (databaseAutoLockCheckbox.isSelected()) {
            if (databaseAutoLockTime.getText() == null || databaseAutoLockTime.getText().trim().equals("")
                    || !Util.isNumeric(databaseAutoLockTime.getText())) {
                JOptionPane.showMessageDialog(OptionsDialog.this,
                        Translator.translate("invalidValueForDatabaseAutoLockTime"),
                        Translator.translate("problem"), JOptionPane.ERROR_MESSAGE);
                databaseAutoLockTime.requestFocusInWindow();
                return;
            }
        }

        if (accountPasswordLength.getText() == null || accountPasswordLength.getText().trim().equals("")
                || !Util.isNumeric(accountPasswordLength.getText())) {
            JOptionPane.showMessageDialog(OptionsDialog.this,
                    Translator.translate("invalidValueForAccountPasswordLength"),
                    Translator.translate("problem"), JOptionPane.ERROR_MESSAGE);
            databaseAutoLockTime.requestFocusInWindow();
            return;
        }

        Preferences.set(Preferences.ApplicationOptions.DB_TO_LOAD_ON_STARTUP, dbToLoadOnStartup.getText());
        Preferences.set(Preferences.ApplicationOptions.ACCOUNT_HIDE_PASSWORD,
                String.valueOf(hideAccountPasswordCheckbox.isSelected()));
        Preferences.set(Preferences.ApplicationOptions.DATABASE_AUTO_LOCK,
                String.valueOf(databaseAutoLockCheckbox.isSelected()));
        Preferences.set(Preferences.ApplicationOptions.DATABASE_AUTO_LOCK_TIME, databaseAutoLockTime.getText());
        Preferences.set(Preferences.ApplicationOptions.ACCOUNT_PASSWORD_LENGTH,
                accountPasswordLength.getText());
        Preferences.set(Preferences.ApplicationOptions.HTTPS_ACCEPT_SELFSIGNED_CERTS,
                String.valueOf(acceptSelfSignedCertsCheckbox.isSelected()));
        Preferences.set(Preferences.ApplicationOptions.HTTP_PROXY_HOST, httpProxyHost.getText());
        Preferences.set(Preferences.ApplicationOptions.HTTP_PROXY_PORT, httpProxyPort.getText());
        Preferences.set(Preferences.ApplicationOptions.HTTP_PROXY_USERNAME, httpProxyUsername.getText());
        String encodedPassword = new String(
                Base64.encodeBase64(new String(httpProxyPassword.getPassword()).getBytes()));
        Preferences.set(Preferences.ApplicationOptions.HTTP_PROXY_PASSWORD, encodedPassword);
        Preferences.set(Preferences.ApplicationOptions.HTTP_PROXY_ENABLED,
                String.valueOf(enableProxyCheckbox.isSelected()));

        // Save the new language and set a flag if it has changed
        String beforeLocale = Preferences.get(Preferences.ApplicationOptions.LOCALE);
        Locale selectedLocale = Translator.SUPPORTED_LOCALES[localeComboBox.getSelectedIndex()];
        String afterLocale = selectedLocale.getLanguage();
        if (!afterLocale.equals(beforeLocale)) {
            Preferences.set(Preferences.ApplicationOptions.LOCALE, selectedLocale.getLanguage());
            Translator.loadBundle(selectedLocale);
            languageChanged = true;
        }

        Preferences.save();
        setVisible(false);
        dispose();
        okClicked = true;
    } catch (Exception e) {
        JOptionPane.showMessageDialog(parentFrame, e.getStackTrace(), Translator.translate("error"),
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.alkacon.opencms.excelimport.CmsExcelXmlConfiguration.java

/**
 * Reads configuration file.<p>//w w  w  .ja v a  2  s.com
 * 
 * @param cmsObject current CmsObject
 * @param fileName name from configuration file to read
 */
public void readConfigurationFile(CmsObject cmsObject, String fileName) {

    CmsXmlContent xmlContent = null;

    try {
        CmsFile xmlFile = cmsObject.readFile(fileName);
        xmlContent = CmsXmlContentFactory.unmarshal(cmsObject, xmlFile);

        Locale locale = cmsObject.getRequestContext().getLocale();
        // check for current request locale
        boolean localeFound = false;
        Iterator iterLocale = xmlContent.getLocales().iterator();
        while (iterLocale.hasNext()) {
            Locale localeCheck = (Locale) iterLocale.next();
            if (locale.getLanguage().equals(localeCheck.getLanguage())) {
                localeFound = true;
            }
        }
        if (!localeFound) {
            locale = (Locale) xmlContent.getLocales().get(0);
        }

        // resource type
        if (xmlContent.hasValue(NODE_RESOURCE_TYPE, locale)) {
            m_resourceType = xmlContent.getValue(NODE_RESOURCE_TYPE, locale).getStringValue(cmsObject);
        }
        // interface name
        if (xmlContent.hasValue(NODE_INTERFACE_NAME, locale)) {
            m_interfaceName = xmlContent.getValue(NODE_INTERFACE_NAME, locale).getStringValue(cmsObject);
        }
        // minimum weight for existing XML content
        if (xmlContent.hasValue(NODE_MINIMUM_WEIGHT, locale)) {
            String minimum = xmlContent.getValue(NODE_MINIMUM_WEIGHT, locale).getStringValue(cmsObject);
            if (CmsStringUtil.isNotEmpty(minimum)) {
                m_minimumSumWeightsForExistingXmlContent = Integer.parseInt(minimum);
            }
        }
        // mappings
        Iterator iterImages = xmlContent.getValues(NODE_MAPPING, locale).iterator();
        while (iterImages.hasNext()) {
            // loop all mapping nodes
            I_CmsXmlContentValue value = (I_CmsXmlContentValue) iterImages.next();
            CmsExcelXmlConfigurationMapping mapping = new CmsExcelXmlConfigurationMapping();

            String xPath = value.getPath();
            // XML tag name
            if (xmlContent.hasValue(xPath + "/" + NODE_MAPPING_XML_TAG_NAME, locale)) {
                String xmlTagName = xmlContent.getValue(xPath + "/" + NODE_MAPPING_XML_TAG_NAME, locale)
                        .getStringValue(cmsObject);
                mapping.setXmlTagName(xmlTagName);
            }
            // excel column name
            if (xmlContent.hasValue(xPath + "/" + NODE_MAPPING_EXCEL_COLUMN_NAME, locale)) {
                String excelColumnName = xmlContent
                        .getValue(xPath + "/" + NODE_MAPPING_EXCEL_COLUMN_NAME, locale)
                        .getStringValue(cmsObject);
                mapping.setExcelColumnName(excelColumnName);
            }
            // weight
            if (xmlContent.hasValue(xPath + "/" + NODE_MAPPING_WEIGHT, locale)) {
                String valueString = xmlContent.getValue(xPath + "/" + NODE_MAPPING_WEIGHT, locale)
                        .getStringValue(cmsObject);
                if (CmsStringUtil.isNotEmpty(valueString)) {
                    int weight = Integer.parseInt(valueString);
                    mapping.setWeight(weight);
                }
            }
            // mandatory
            if (xmlContent.hasValue(xPath + "/" + NODE_MAPPING_MANDATORY, locale)) {
                String valueString = xmlContent.getValue(xPath + "/" + NODE_MAPPING_MANDATORY, locale)
                        .getStringValue(cmsObject);
                boolean mandatory = new Boolean(valueString).booleanValue();
                mapping.setMandatory(mandatory);
            }
            m_mappings.add(mapping);
            m_configName = fileName;
        }
    } catch (CmsException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e.toString());
        }
    }
}

From source file:com.alkacon.opencms.v8.excelimport.CmsExcelXmlConfiguration.java

/**
 * Reads configuration file.<p>//from w w w  .j  a  v a  2 s  .  co  m
 * 
 * @param cmsObject current CmsObject
 * @param fileName name from configuration file to read
 */
public void readConfigurationFile(CmsObject cmsObject, String fileName) {

    CmsXmlContent xmlContent = null;

    try {
        CmsFile xmlFile = cmsObject.readFile(fileName);
        xmlContent = CmsXmlContentFactory.unmarshal(cmsObject, xmlFile);

        Locale locale = cmsObject.getRequestContext().getLocale();
        // check for current request locale
        boolean localeFound = false;
        Iterator iterLocale = xmlContent.getLocales().iterator();
        while (iterLocale.hasNext()) {
            Locale localeCheck = (Locale) iterLocale.next();
            if (locale.getLanguage().equals(localeCheck.getLanguage())) {
                localeFound = true;
            }
        }
        if (!localeFound) {
            locale = xmlContent.getLocales().get(0);
        }

        // resource type
        if (xmlContent.hasValue(NODE_RESOURCE_TYPE, locale)) {
            m_resourceType = xmlContent.getValue(NODE_RESOURCE_TYPE, locale).getStringValue(cmsObject);
        }
        // interface name
        if (xmlContent.hasValue(NODE_INTERFACE_NAME, locale)) {
            m_interfaceName = xmlContent.getValue(NODE_INTERFACE_NAME, locale).getStringValue(cmsObject);
        }
        // minimum weight for existing XML content
        if (xmlContent.hasValue(NODE_MINIMUM_WEIGHT, locale)) {
            String minimum = xmlContent.getValue(NODE_MINIMUM_WEIGHT, locale).getStringValue(cmsObject);
            if (CmsStringUtil.isNotEmpty(minimum)) {
                m_minimumSumWeightsForExistingXmlContent = Integer.parseInt(minimum);
            }
        }
        // mappings
        Iterator iterImages = xmlContent.getValues(NODE_MAPPING, locale).iterator();
        while (iterImages.hasNext()) {
            // loop all mapping nodes
            I_CmsXmlContentValue value = (I_CmsXmlContentValue) iterImages.next();
            CmsExcelXmlConfigurationMapping mapping = new CmsExcelXmlConfigurationMapping();

            String xPath = value.getPath();
            // XML tag name
            if (xmlContent.hasValue(xPath + "/" + NODE_MAPPING_XML_TAG_NAME, locale)) {
                String xmlTagName = xmlContent.getValue(xPath + "/" + NODE_MAPPING_XML_TAG_NAME, locale)
                        .getStringValue(cmsObject);
                mapping.setXmlTagName(xmlTagName);
            }
            // excel column name
            if (xmlContent.hasValue(xPath + "/" + NODE_MAPPING_EXCEL_COLUMN_NAME, locale)) {
                String excelColumnName = xmlContent
                        .getValue(xPath + "/" + NODE_MAPPING_EXCEL_COLUMN_NAME, locale)
                        .getStringValue(cmsObject);
                mapping.setExcelColumnName(excelColumnName);
            }
            // weight
            if (xmlContent.hasValue(xPath + "/" + NODE_MAPPING_WEIGHT, locale)) {
                String valueString = xmlContent.getValue(xPath + "/" + NODE_MAPPING_WEIGHT, locale)
                        .getStringValue(cmsObject);
                if (CmsStringUtil.isNotEmpty(valueString)) {
                    int weight = Integer.parseInt(valueString);
                    mapping.setWeight(weight);
                }
            }
            // mandatory
            if (xmlContent.hasValue(xPath + "/" + NODE_MAPPING_MANDATORY, locale)) {
                String valueString = xmlContent.getValue(xPath + "/" + NODE_MAPPING_MANDATORY, locale)
                        .getStringValue(cmsObject);
                boolean mandatory = new Boolean(valueString).booleanValue();
                mapping.setMandatory(mandatory);
            }
            m_mappings.add(mapping);
            m_configName = fileName;
        }
    } catch (CmsException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(e.toString());
        }
    }
}

From source file:de.ingrid.external.gemet.GEMETService.java

/**
 * Determine language filter for GEMET dependent from passed locale !
 * //w w  w  .j a v  a  2 s.  c  o  m
 * @param locale
 * @return language used in gemet
 */
private String getGEMETLanguageFilter(Locale locale) {
    // default is german !
    String langFilter = "de";
    if (locale != null) {
        langFilter = locale.getLanguage();
    }

    return langFilter;
}