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:jp.terasoluna.fw.message.DataSourceMessageSource.java

/**
 * ???? ??//  w  w  w  . j a  v  a2s  . c o m
 * ????????
 * locale??????
 * locale??????
 * ???????
 * ?????
 * ????
 * 
 * @param locale
 *            
 * 
 * @return ???
 */
protected List<Locale> getAlternativeLocales(Locale locale) {
    List<Locale> locales = new ArrayList<Locale>();
    // ?????
    if (locale.getVariant().length() > 0) {
        // Locale(language,country,"")
        locales.add(new Locale(locale.getLanguage(), locale.getCountry()));
    }
    // ????
    if (locale.getCountry().length() > 0) {
        // Locale(language,"","")
        locales.add(new Locale(locale.getLanguage()));
    }
    // ?????
    if (defaultLocale != null && !locale.equals(defaultLocale)) {
        if (defaultLocale.getVariant().length() > 0) {
            // Locale(language,country,"")
            locales.add(defaultLocale);
        }
        if (defaultLocale.getCountry().length() > 0) {
            // Locale(language,country,"")
            locales.add(new Locale(defaultLocale.getLanguage(), defaultLocale.getCountry()));
        }
        // ????
        if (defaultLocale.getLanguage().length() > 0) {
            // Locale(language,"","")
            locales.add(new Locale(defaultLocale.getLanguage()));
        }
    }
    return locales;
}

From source file:com.evolveum.midpoint.web.component.menu.top.LocalePanel.java

private LocaleDescriptor getSelectedLocaleDescriptor() {
    Locale locale = getSession().getLocale();
    if (locale == null) {
        return null;
    }//from   w ww . j a  v  a2  s  .  c  om

    // The second condition is a fix attempt for issue MID-2075, where firefox
    // returns 'sk' as a locale from session, while other browsers return 'sk_SK'.
    // This is the reason, why in firefox selected locale is ignored (the commented
    // condition is not met) so we are adding second condition to overcome this issue.
    for (LocaleDescriptor desc : AVAILABLE_LOCALES) {
        //            if (locale.equals(desc.getLocale())
        if (locale.equals(desc.getLocale()) || locale.getLanguage().equals(desc.getLocale().getLanguage())) {
            return desc;
        }
    }

    return null;
}

From source file:com.daugherty.e2c.persistence.data.jdbc.JdbcSupplierDao.java

@Override
public List<Supplier> loadApprovedBySupplierIds(List<Long> ids, Locale locale) {
    List<Supplier> suppliers = Lists.newArrayList();
    HashSet<Long> uniqueIds = Sets.newHashSet(ids);
    LOGGER.debug("Getting Supplier from the database by supplier ids " + uniqueIds);
    for (List<Long> partitionedIds : Lists.partition(Lists.newArrayList(uniqueIds), 1000)) {
        String sql = getSql("/supplier/getApprovedBySupplierIds.sql");
        SqlParameterSource parameterSource = new MapSqlParameterSource("supplierIds", partitionedIds)
                .addValue("language", locale.getLanguage());
        suppliers.addAll(jdbcTemplate.query(sql, parameterSource, new SupplierResultSetExtractor()));
    }//  w  w  w. j  a  va2  s .co  m

    return suppliers;
}

From source file:com.daugherty.e2c.persistence.data.jdbc.JdbcSupplierDao.java

@Override
public List<Supplier> loadLatestBySupplierIds(List<Long> ids, Locale locale) {
    List<Supplier> suppliers = Lists.newArrayList();

    HashSet<Long> uniqueIds = Sets.newHashSet(ids);
    LOGGER.debug("Getting Supplier from the database by supplier ids " + uniqueIds);
    for (List<Long> partitionedIds : Lists.partition(Lists.newArrayList(uniqueIds), 1000)) {
        String sql = getSql("/supplier/getLatestBySupplierIds.sql");
        SqlParameterSource parameterSource = new MapSqlParameterSource("supplierIds", partitionedIds)
                .addValue("language", locale.getLanguage());
        suppliers.addAll(jdbcTemplate.query(sql, parameterSource, new SupplierResultSetExtractor()));
    }//from   w w w.ja v a 2  s  .c o  m

    return suppliers;
}

From source file:org.parancoe.web.util.ReloadableResourceBundleMessageSource.java

/**
 * Calculate the filenames for the given bundle basename and Locale, appending language code,
 * country code, and variant code. E.g.: basename "messages", Locale "de_AT_oo" ->
 * "messages_de_AT_OO", "messages_de_AT", "messages_de". <p>Follows the rules defined by {@link java.util.Locale#toString()}.
 *
 * @param basename the basename of the bundle
 * @param locale the locale/*from   w w w.j  a  v  a2  s .  co m*/
 * @return the List of filenames to check
 */
protected List<String> calculateFilenamesForLocale(String basename, Locale locale) {
    List<String> result = new ArrayList<String>(3);
    String language = locale.getLanguage();
    String country = locale.getCountry();
    String variant = locale.getVariant();
    StringBuilder temp = new StringBuilder(basename);

    temp.append('_');
    if (language.length() > 0) {
        temp.append(language);
        result.add(0, temp.toString());
    }

    temp.append('_');
    if (country.length() > 0) {
        temp.append(country);
        result.add(0, temp.toString());
    }

    if (variant.length() > 0 && (language.length() > 0 || country.length() > 0)) {
        temp.append('_').append(variant);
        result.add(0, temp.toString());
    }

    return result;
}

From source file:com.salesmanager.catalog.product.ProductDetailsAction.java

public String displayReviews() {

    if (this.getProduct() == null) {
        return "AUTHORIZATIONERROR";
    }//w ww.j av  a  2 s  . com

    try {

        Locale locale = super.getLocale();

        setSize(size);

        SearchReviewCriteria criteria = new SearchReviewCriteria();
        criteria.setProductId(this.getProduct().getProductId());
        criteria.setLanguageId(LanguageUtil.getLanguageNumberCode(locale.getLanguage()));
        criteria.setQuantity(this.getSize());
        criteria.setStartindex(super.getPageStartIndex());

        CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService);

        SearchReviewResponse response = cservice.searchProductReviewsByProduct(criteria);
        reviews = response.getReviews();

        super.setListingCount(response.getCount());
        super.setRealCount(reviews.size());
        super.setPageElements();

        LocaleUtil.setLocaleToEntityCollection(reviews, super.getLocale());

        // calculate average
        counter = cservice.countAverageRatingPerProduct(this.getProduct().getProductId());

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

    return SUCCESS;
}

From source file:com.doculibre.constellio.services.SearchServicesImpl.java

@Override
public QueryResponse search(SimpleSearch simpleSearch, int start, int rows, SearchParams searchParams,
        ConstellioUser user) {/* ww w  . ja  v a2 s.  co m*/
    QueryResponse queryResponse;

    String collectionName = simpleSearch.getCollectionName();
    if (collectionName != null) {
        RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
        RecordServices recordServices = ConstellioSpringUtils.getRecordServices();
        RecordCollection collection = collectionServices.get(collectionName);

        SolrServices solrServices = ConstellioSpringUtils.getSolrServices();
        Boolean usesDisMax = solrServices.usesDisMax(collection);

        SolrQuery query;
        if (!collection.isOpenSearch()) {
            query = toSolrQuery(simpleSearch, usesDisMax, true, true);
        } else {
            query = toSolrQuery(simpleSearch, usesDisMax, false, true);
        }
        // displayQuery(query);

        String luceneQuery = simpleSearch.getLuceneQuery();
        query.setParam(ConstellioSolrQueryParams.LUCENE_QUERY, luceneQuery);
        query.setParam(ConstellioSolrQueryParams.SIMPLE_SEARCH, simpleSearch.toSimpleParams().toString());
        query.setParam(ConstellioSolrQueryParams.COLLECTION_NAME, collectionName);
        if (user != null) {
            query.setParam(ConstellioSolrQueryParams.USER_ID, "" + user.getId());
        }

        String queryString = query.getQuery();
        if (StringUtils.isEmpty(queryString)) {
            queryString = SimpleSearch.SEARCH_ALL;
        }

        List<Record> pendingExclusions = recordServices.getPendingExclusions(collection);
        while (!pendingExclusions.isEmpty()) {
            IndexingManager indexingManager = IndexingManager.get(collection);
            if (indexingManager.isActive()) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                pendingExclusions = recordServices.getPendingExclusions(collection);
            } else {
                return null;
            }
        }

        // SolrQuery query = new SolrQuery();
        query.set("collectionName", simpleSearch.getCollectionName());
        // query.setQuery(luceneQuery);

        query.set("shards.qt", "/elevate");
        query.setRequestHandler("/elevate");

        // nb rsultats par page
        query.setRows(rows);

        // page de dbut
        query.setStart(start);
        query.setHighlight(searchParams.isHighlightingEnabled());
        if (searchParams.isHighlightingEnabled()) {
            query.setHighlightFragsize(searchParams.getFragsize());
            query.setHighlightSnippets(searchParams.getSnippets());
        }

        if (simpleSearch.getSortField() != null) {
            ORDER order = SimpleSearch.SORT_DESCENDING.equals(simpleSearch.getSortOrder()) ? ORDER.desc
                    : ORDER.asc;
            IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices();
            IndexField indexField = indexFieldServices.get(simpleSearch.getSortField(), collection);
            if (indexField != null) {
                IndexField sortIndexField = indexFieldServices.getSortFieldOf(indexField);
                if (sortIndexField != null) {
                    query.setSort(sortIndexField.getName(), order);
                }
            }
        }

        if (collection.isOpenSearch()) {
            query.setParam("openSearchURL", collection.getOpenSearchURL());
            Locale locale = simpleSearch.getSingleSearchLocale();
            if (locale != null) {
                query.setParam("lang", locale.getLanguage());
            }
        }

        if (searchParams.getHighlightedFields() == null) {
            IndexField defaultSearchField = collection.getDefaultSearchIndexField();
            query.addHighlightField(defaultSearchField.getName());
            for (CopyField copyFieldDest : defaultSearchField.getCopyFieldsDest()) {
                IndexField copyIndexFieldSource = copyFieldDest.getIndexFieldSource();
                if (copyIndexFieldSource != null && !copyIndexFieldSource.isTitleField()
                        && copyIndexFieldSource.isHighlighted()) {
                    query.addHighlightField(copyIndexFieldSource.getName());
                }
            }
            IndexField titleField = collection.getTitleIndexField();
            if (titleField != null && titleField.isHighlighted()) {
                query.addHighlightField(titleField.getName());
            }
        } else {
            for (String highlightedField : searchParams.getHighlightedFields()) {
                IndexField field = collection.getIndexField(highlightedField);
                if (field != null) {
                    query.addHighlightField(highlightedField);
                }
            }
        }
        SolrServer server = SolrCoreContext.getSolrServer(collectionName);
        if (server != null) {
            try {
                // displayQuery(query);
                queryResponse = server.query(query);
            } catch (SolrServerException e) {
                queryResponse = null;
            }
        } else {
            queryResponse = null;
        }

        //            if (queryResponse != null && !collection.isOpenSearch()) {
        //                StatsCompiler statCompiler = StatsCompiler.getInstance();
        //                try {
        //                    statCompiler.saveStats(collectionName, SolrLogContext.getStatsSolrServer(),
        //                        SolrLogContext.getStatsCompileSolrServer(), queryResponse, luceneQuery);
        //                } catch (SolrServerException e) {
        //                    throw new RuntimeException(e);
        //                } catch (IOException e) {
        //                    throw new RuntimeException(e);
        //                }
        //            }

    } else {
        queryResponse = null;
    }

    // improveQueryResponse(collectionName, queryResponse);
    // System.out.println("Response size" + queryResponse.getResults().getNumFound());
    return queryResponse;
}

From source file:com.erudika.scoold.utils.ScooldUtils.java

public String getLanguageCode(HttpServletRequest req) {
    String cookieLoc = getCookieValue(req, LOCALE_COOKIE);
    Locale requestLocale = langutils.getProperLocale(req.getLocale().toString());
    return (cookieLoc != null) ? cookieLoc : requestLocale.getLanguage();
}

From source file:com.aurel.track.user.ResetPasswordAction.java

/**
 *In case of changing password succeeded, the user will be logged in
 *automatically and redirected to default page.
 * @return//from   w w  w .  j  a v a2s .  c  o m
 */
public String reset() {
    TPersonBean personBean = PersonBL.loadByForgotPasswordToken(ctk);
    if (personBean != null && personBean.getTokenExpDate().getTime() > new Date().getTime()) {
        personBean.setDisabled(false);
        personBean.setTokenExpDate(null);
        personBean.setTokenPasswd(null);
        personBean.setForgotPasswordKey(null);
        personBean.setPasswdEncrypted(passwd);
        PersonBL.save(personBean);
        String forwardUrl = "";
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession httpSession = request.getSession();
        Locale locale = getLocale();
        if (locale == null) {
            locale = Locale.getDefault();
            LOGGER.debug("Requested locale is null. Using default:" + locale.getDisplayName());
        } else {
            LOGGER.debug("Requested locale " + locale.getDisplayName());
        }

        TMotdBean motd = MotdBL.loadMotd(locale.getLanguage());
        String redirectMapEntry = "";
        ArrayList<LabelValueBean> errors = new ArrayList<LabelValueBean>();
        StringBuilder sb = LoginBL.createLoginResponseJSON(personBean.getLoginName(), passwd, null, false,
                false, request, errors, httpSession, forwardUrl, motd, false, locale, null, redirectMapEntry);
        return LoginBL.writeJSONResponse(sb); // The redirect is done by the client JavaScript
    }

    layoutCls = "com.trackplus.layout.ResetPasswordExpiredLayout";
    pageTitle = "logon.register.expired.title";
    return "expired";
}

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

/**
 * // w  ww . j  av a2s.c  om
 */
public void processProperties() {
    initLucene();

    try {
        Locale currLocale = Locale.getDefault();

        Vector<String> terms = new Vector<String>();

        File resFile = new File("src/resources_" + currLocale.getLanguage() + ".properties");
        List<?> lines = FileUtils.readLines(resFile);
        for (String line : (List<String>) lines) {
            if (!line.startsWith("#")) {
                int inx = line.indexOf("=");
                if (inx > -1) {
                    String[] toks = StringUtils.split(line, "=");
                    if (toks.length > 1) {
                        terms.add(toks[0]);
                    }
                }
            }
        }

        Vector<Pair<String, String>> notFoundList = new Vector<Pair<String, String>>();
        String field = "contents";
        QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, field, analyzer);

        for (String term : terms) {
            Query query;
            try {
                if (term.equals("AND") || term.equals("OR"))
                    continue;

                query = parser.parse(term);

                String subTerm = null;
                int hits = getTotalHits(query, 10);
                if (hits == 0) {
                    int inx = term.indexOf('.');
                    if (inx > -1) {
                        subTerm = term.substring(inx + 1);
                        hits = getTotalHits(parser.parse(subTerm), 10);

                        if (hits == 0) {
                            int lastInx = term.lastIndexOf('.');
                            if (lastInx > -1 && lastInx != inx) {
                                subTerm = term.substring(lastInx + 1);
                                hits = getTotalHits(parser.parse(subTerm), 10);
                            }
                        }
                    }
                }

                if (hits == 0) {
                    notFoundList.add(new Pair<String, String>(term, subTerm));

                    System.out.println("'" + term + "' was not found "
                            + (subTerm != null ? ("SubTerm[" + subTerm + "]") : ""));
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        ConversionLogger convLogger = new ConversionLogger();
        convLogger.initialize("resources", "Resources");

        TableWriter tblWriter = convLogger.getWriter("resources.html", "Resources");
        tblWriter.startTable();
        tblWriter.logHdr("Id", "Full Key", "Sub Key");
        int cnt = 1;
        for (Pair<String, String> pair : notFoundList) {
            tblWriter.log(Integer.toString(cnt++), pair.first, pair.second != null ? pair.second : "&nbsp;");
        }
        tblWriter.endTable();
        convLogger.closeAll();

    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(LocalizerApp.class, ex);
        ex.printStackTrace();
    }
}