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.product.ProductDetailsAction.java

public String displayProduct() {

    try {//  www  .  ja v  a 2 s .c om

        CacheModule cache = (CacheModule) SpringUtil.getBean("cache");

        String url = super.getRequestedEntityId();
        CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService);
        MerchantStore store = (MerchantStore) super.getServletRequest().getSession().getAttribute("STORE");
        Locale locale = (Locale) super.getLocale();
        product = cservice.getProductByMerchantIdAndSeoURLAndByLang(store.getMerchantId(), url,
                locale.getLanguage());

        if (product == null) {
            if (product == null) {
                logger.warn("Product having seUrl " + url + " does not exist");
                return "DEFAULT";
            }
        }

        if (!StringUtils.isBlank(product.getProductDescription().getProductTitle())) {
            this.setPageTitle(product.getProductDescription().getProductTitle());
        } else {
            this.setPageTitle(product.getName());
        }

        this.setMetaDescription(product.getDescription());

        ((I18NEntity) product).setLocale(super.getLocale(), store.getCurrency());

        Set prices = product.getPrices();

        LocaleUtil.setLocaleToEntityCollection(prices, locale, store.getCurrency());

        // for category trail
        categoryPath = CategoryUtil.getCategoryPath(super.getLocale().getLanguage(), store.getMerchantId(),
                product.getMasterCategoryId());

        // options - attributes
        Collection attributes = cservice.getProductAttributes(product.getProductId(), locale.getLanguage());

        Collection defaultOptions = new ArrayList();

        if (attributes != null && attributes.size() > 0) {

            // extract read only
            Iterator i = attributes.iterator();

            long lastOptionId = -1;
            long lastSpecificationOptionId = -1;
            ProductOptionDescriptor pod = null;

            while (i.hasNext()) {

                ProductAttribute pa = (ProductAttribute) i.next();

                ProductOption po = pa.getProductOption();
                ProductOptionValue pov = pa.getProductOptionValue();
                if (po != null) {

                    if (pa.isAttributeDisplayOnly()) {

                        if (lastSpecificationOptionId == -1) {
                            lastSpecificationOptionId = po.getProductOptionId();
                            pod = new ProductOptionDescriptor();
                            pod.setOptionType(po.getProductOptionType());
                            pod.setName(po.getName());
                            specifications.add(pod);
                        } else {
                            if (pa.getOptionId() != lastOptionId) {
                                lastSpecificationOptionId = po.getProductOptionId();
                                pod = new ProductOptionDescriptor();
                                pod.setOptionType(po.getProductOptionType());
                                pod.setName(po.getName());
                                specifications.add(pod);
                            }
                        }

                    } else {// option

                        if (lastOptionId == -1) {
                            lastOptionId = po.getProductOptionId();
                            pod = new ProductOptionDescriptor();
                            pod.setOptionType(po.getProductOptionType());
                            pod.setName(po.getName());
                            options.add(pod);
                            if (pa.isAttributeDefault()) {
                                defaultOptions.add(pa);
                            }

                        } else {
                            if (pa.getOptionId() != lastOptionId) {
                                lastOptionId = po.getProductOptionId();
                                pod = new ProductOptionDescriptor();
                                pod.setOptionType(po.getProductOptionType());
                                pod.setName(po.getName());
                                options.add(pod);
                                if (pa.isAttributeDefault()) {
                                    defaultOptions.add(pa);
                                }
                            }
                        }

                    }

                    pod.addValue(pa);
                    pod.setOptionId(pa.getOptionId());
                    if (pa.isAttributeDefault()) {
                        pod.setDefaultOption(pa.getProductAttributeId());
                    }
                }
            }

        }

        if (defaultOptions != null && defaultOptions.size() > 0) {
            this.setProductPrice(ProductUtil.formatHTMLProductPriceWithAttributes(super.getLocale(),
                    store.getCurrency(), this.getProduct(), defaultOptions, true));
        } else {
            this.setProductPrice(ProductUtil.formatHTMLProductPrice(super.getLocale(), store.getCurrency(),
                    this.getProduct(), true, false));
        }

        // related items
        relatedItems = null;
        try {
            relatedItems = (Collection) cache.getFromCache(
                    Constants.CACHE_RELATED_ITEMS + product.getProductId() + "_" + locale.getLanguage(), store);
        } catch (Exception ignore) {

        }

        if (relatedItems == null) {

            // get it from missed cache
            boolean missed = false;
            try {
                missed = (Boolean) cache.getFromCache(Constants.CACHE_RELATED_ITEMS + product.getProductId()
                        + "_MISSED_" + locale.getLanguage(), store);
            } catch (Exception ignore) {

            }

            if (!missed) {

                Collection r = cservice.getProductRelationShip(this.getProduct().getProductId(),
                        store.getMerchantId(), CatalogConstants.PRODUCT_RELATIONSHIP_RELATED_ITEMS,
                        super.getLocale().getLanguage(), true);

                if (r != null && r.size() > 0) {

                    LocaleUtil.setLocaleToEntityCollection(r, super.getLocale(), store.getCurrency());

                    relatedItems = r;

                    try {
                        cache.putInCache(Constants.CACHE_RELATED_ITEMS + product.getProductId() + "_"
                                + locale.getLanguage(), relatedItems, Constants.CACHE_PRODUCTS, store);
                    } catch (Exception ignore) {

                    }

                } else {

                    try {
                        cache.putInCache(Constants.CACHE_RELATED_ITEMS + product.getProductId() + "_MISSED_"
                                + locale.getLanguage(), true, Constants.CACHE_PRODUCTS, store);
                    } catch (Exception ignore) {

                    }

                }

            }

        }

    } catch (Exception e) {
        logger.error(e);
        List msg = new ArrayList();
        msg.add(e.getMessage());
        super.setActionErrors(msg);
        return "GENERICERROR";
    }

    return SUCCESS;

}

From source file:com.salesmanager.core.service.reference.ReferenceService.java

@Transactional
public DynamicLabelDescription getDynamicLabelDescription(int merchantId, int sectionId, Locale locale)
        throws Exception {

    int langId = LanguageUtil.getLanguageNumberCode(locale.getLanguage());

    // get DynamicLabel
    DynamicLabel lbl = null;//from   w  w  w  .  j  a v  a 2  s .  co m
    List lbls = (List) dynamicLabelDao.findByMerchantIdAndSectionId(merchantId, sectionId);

    if (lbls != null && lbls.size() > 0) {
        lbl = (DynamicLabel) lbls.get(0);
    }

    if (lbl != null) {
        Set descriptions = lbl.getDescriptions();
        if (descriptions != null) {
            Iterator i = descriptions.iterator();
            DynamicLabelDescription returnDesc = null;
            while (i.hasNext()) {
                DynamicLabelDescription desc = (DynamicLabelDescription) i.next();
                returnDesc = desc;
                DynamicLabelDescriptionId id = desc.getId();
                if (id.getLanguageId() == langId) {
                    return desc;
                }

            }
            return returnDesc;
        }

    }
    return null;
}

From source file:ca.oson.json.gson.functional.DefaultTypeAdaptersTest.java

public void testLocaleDeserializationWithLanguage() {
    String json = "\"en\"";
    Locale locale = oson.fromJson(json, Locale.class);
    assertEquals("en", locale.getLanguage());
}

From source file:org.amnesty.aidoc.search.AidocSearch.java

/**
 * Execute the search/*w  w  w  .  ja v  a 2 s  . c  om*/
 *
 * @param searchTerms
 * @param startPage
 *          Search page to start results on
 * @param itemsPerPage
 *          Number of items to display per search page
 * @param language
 *          Language to restrict search results by. If null search will
 *          return all results.
 * @return
 */
private SearchResult search(String searchTerms, int startPage, int itemsPerPage, String language,
        WebScriptRequest req) {
    SearchResult searchResult = null;
    ResultSet results = null;

    logger.debug("invoking AidocSearch");

    try {

        Map<String, List<String>> queryMap = AidocSearchQueryStringParser.parse(searchTerms);
        StringBuffer query = new StringBuffer();

        /*
         * 1. First add the general restriction parameters so we query over
         * the right dataset
         */

        query.append("TYPE:\"{" + AICORE_CONTENT_TYPE + "}Document\" AND \n");
        query.append("ASPECT:\"{" + CONTENT_TYPE + "}effectivity\" AND \n");
        query.append("ASPECT:\"{" + CONTENT_TYPE + "}mlDocument\" AND \n");

        // Exclude documents without an effective date

        // Warning! We probably have timezone problems at the moment
        // See AIDOC-138

        /* Set the date range if provided */
        String fromDate = "1900-01-01T00:00:00";
        if (queryMap.get("from") != null) {
            List<String> fromList = queryMap.get("from");
            fromDate = (String) fromList.get(0);
        }
        String toDate = ISO8601DateFormat.format(new Date());
        if (queryMap.get("to") != null) {
            List<String> toList = queryMap.get("to");
            toDate = (String) toList.get(0);
        }

        query.append(" @cm\\:from:[" + fromDate + " TO " + toDate + "] AND");

        /*
         * Process language from query. If it exists this overrides form
         * parameter
         */
        if (queryMap.containsKey("lang")) {
            List<String> langList = (List<String>) queryMap.get("lang");
            String lang = langList.get(0);
            if (lang != null && lang.length() > 0)
                language = lang;
        }
        if (language != null && language.length() > 0) {
            language = language.replace("-", "_");
        }
        logger.debug("language: " + language);

        /* Process language */
        // Locale locale = I18NUtil.getLocale();
        Locale locale = null;
        if (language != null && language.length() > 0 && !language.equals("any")) {
            locale = new Locale(language);
            query.append(" @sys\\:locale:\"" + locale.getLanguage() + "_\" AND");
        }

        /*
         * 2. Now add the user's parameters
         */

        if (AidocSearchQueryStringParser.isDocumentIdQuery(searchTerms)) {
            query = buildIndexQuery(query, searchTerms);
        } else {
            query = buildStandardQuery(query, queryMap, language);
        }

        if (query.toString().trim().endsWith("AND")) {
            query.delete(query.length() - 4, query.length());
        }

        /*
         * Create SearchParameters to go with Lucene search string
         */
        SearchParameters parameters = new SearchParameters();
        parameters.addStore(SEARCH_STORE);
        parameters.setLanguage(SearchService.LANGUAGE_LUCENE);
        // Doesn't work yet. See AIDOC-466
        // parameters.setDefaultOperator(SearchParameters.AND);
        parameters.setQuery(query.toString());

        /* Add locale clause if locale is set */
        // if (locale != null) {
        // parameters.addLocale(locale);
        // }
        // Add sort clause if sort:date specified
        if (queryMap.containsKey("sort")) {
            List<String> sortValues = (List<String>) queryMap.get("sort");

            boolean asc = false;
            if (queryMap.containsKey("order")) {
                List<String> orderValues = (List<String>) queryMap.get("order");
                if (orderValues.get(0).equals("asc"))
                    asc = true;
            }

            if (sortValues.get(0).equals("date")) {
                logger.debug("sort by date");
                if (asc) {
                    logger.debug("order descending");
                } else
                    logger.debug("order ascending");
                parameters.addSort("@" + QName.createQName(CONTENT_TYPE, "from"), asc);
            }
        } else
            parameters.addSort("@" + QName.createQName(CONTENT_TYPE, "from"), false);

        /*
         * Execute query
         */
        if (logger.isDebugEnabled()) {
            logger.debug("Search parameters: searchTerms=" + searchTerms + ", startPage=" + startPage
                    + ", itemsPerPage=" + itemsPerPage);
            logger.debug("Issuing lucene search: " + query);
        }

        results = searchService.query(parameters);
        int totalResults = results.length();

        logger.debug("Results: " + totalResults + " rows (limited: "
                + results.getResultSetMetaData().getLimitedBy() + ")");

        int totalPages = (totalResults / itemsPerPage);
        totalPages += (totalResults % itemsPerPage != 0) ? 1 : 0;

        /* construct search result */
        searchResult = new SearchResult();
        searchResult.setSearchTerms(searchTerms);
        searchResult.setLocale(locale);
        searchResult.setItemsPerPage(itemsPerPage);
        searchResult.setStartPage(startPage);
        searchResult.setTotalResults(totalResults);
        if (totalResults == 0) {
            searchResult.setTotalPages(0);
            searchResult.setStartIndex(0);
            searchResult.setTotalPageItems(0);
        } else if (totalPages != 0 && (startPage < 1 || startPage > totalPages)) {
            /* handle out-of-range by displaying no results */
            searchResult.setTotalPages(totalPages);
            searchResult.setStartIndex(0);
            searchResult.setTotalPageItems(0);
        } else {
            searchResult.setTotalPages(totalPages);
            searchResult.setStartIndex(((startPage - 1) * itemsPerPage) + 1);
            searchResult
                    .setTotalPageItems(Math.min(itemsPerPage, totalResults - searchResult.getStartIndex() + 1));
        }
        SearchTemplateNode[] nodes = new SearchTemplateNode[searchResult.getTotalPageItems()];
        for (int i = 0; i < searchResult.getTotalPageItems(); i++) {
            NodeRef node = results.getNodeRef(i + searchResult.getStartIndex() - 1);
            float score = results.getScore(i + searchResult.getStartIndex() - 1);
            nodes[i] = new SearchTemplateNode(node, score);
        }
        searchResult.setResults(nodes);
        return searchResult;
    } catch (Exception e) {
        logger.error("Search failed", e);
        return null;
    } finally {
        if (results != null) {
            results.close();
        }
    }
}

From source file:ca.oson.json.gson.functional.DefaultTypeAdaptersTest.java

public void testLocaleDeserializationWithLanguageCountryVariant() {
    String json = "\"de_DE_EURO\"";
    Locale locale = oson.fromJson(json, Locale.class);
    assertEquals("de", locale.getLanguage());
    assertEquals("DE", locale.getCountry());
    assertEquals("EURO", locale.getVariant());
}

From source file:com.haulmont.cuba.desktop.LoginDialog.java

protected Locale resolveLocale() {
    Locale appLocale;
    String lastLocale = this.loginProperties.loadLastLocale();
    if (StringUtils.isNotEmpty(lastLocale)) {
        appLocale = LocaleUtils.toLocale(lastLocale);
    } else {//w  ww.ja  va  2  s. c  om
        appLocale = Locale.getDefault();
    }

    for (Locale locale : locales.values()) {
        if (locale.equals(appLocale)) {
            return locale;
        }
    }

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

    // return first locale set in the cuba.availableLocales app property
    return locales.values().iterator().next();
}

From source file:com.globalsight.everest.projecthandler.MachineTranslateAdapter.java

private String checkLang(Locale p_locale) {
    if (p_locale == null) {
        return "";
    }/*w  w w .  jav a 2 s  .c  o m*/

    String lang = p_locale.getLanguage();
    if ("in".equalsIgnoreCase(lang)) {
        lang = "id";
    }

    return lang;
}

From source file:com.salesmanager.core.service.reference.ReferenceService.java

@Transactional
public DynamicLabel getDynamicLabelByMerchantIdAndSeUrlAndLanguageId(int merchantId, String url,
        Locale locale) {
    return dynamicLabelDao.findByMerchantIdAndSeUrlAndLanguageId(merchantId, url,
            LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
}

From source file:it.govpay.web.utils.Utils.java

public Lingua getLabelLingua(Locale locale) {
    Map<String, String> etichette = getEtichetteLingua(locale);

    Lingua lingua = new Lingua(locale.getLanguage(), etichette);
    return lingua;
}

From source file:com.salesmanager.core.service.reference.ReferenceService.java

@Transactional
public DynamicLabel getDynamicLabel(int merchantId, String title, Locale locale) {
    return dynamicLabelDao.findByMerchantIdAndTitleAndLanguageId(merchantId, title,
            LanguageUtil.getLanguageNumberCode(locale.getLanguage()));

}