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.cat.external.util.OtherUtils.java

/**
 * @param context if null, use the default format
 *                (Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 %sSafari/534.30).
 * @return//from   w  w  w . j  a  va 2  s  .com
 */
@SuppressLint("DefaultLocale")
public static String getUserAgent(Context context) {
    String webUserAgent = null;
    if (context != null) {
        try {
            @SuppressWarnings("rawtypes")
            Class sysResCls = Class.forName("com.android.internal.R$string");
            Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent");
            Integer resId = (Integer) webUserAgentField.get(null);
            webUserAgent = context.getString(resId);
        } catch (Throwable ignored) {
        }
    }
    if (TextUtils.isEmpty(webUserAgent)) {
        webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 %sSafari/533.1";
    }

    Locale locale = Locale.getDefault();
    StringBuffer buffer = new StringBuffer();
    // Add version
    final String version = Build.VERSION.RELEASE;
    if (version.length() > 0) {
        buffer.append(version);
    } else {
        // default to "1.0"
        buffer.append("1.0");
    }
    buffer.append("; ");
    final String language = locale.getLanguage();
    if (language != null) {
        buffer.append(language.toLowerCase());
        final String country = locale.getCountry();
        if (country != null) {
            buffer.append("-");
            buffer.append(country.toLowerCase());
        }
    } else {
        // default to "en"
        buffer.append("en");
    }
    // add the model for the release build
    if ("REL".equals(Build.VERSION.CODENAME)) {
        final String model = Build.MODEL;
        if (model.length() > 0) {
            buffer.append("; ");
            buffer.append(model);
        }
    }
    final String id = Build.ID;
    if (id.length() > 0) {
        buffer.append(" Build/");
        buffer.append(id);
    }
    return String.format(webUserAgent, buffer, "Mobile ");
}

From source file:com.ruint.core.utils.OtherUtils.java

/**
 * @param context//from   w  w w . j a v a2 s .  c  o  m
 *          if null, use the default format (Mozilla/5.0 (Linux; U; Android
 *          %s) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0
 *          %sSafari/534.30).
 * @return
 */
@SuppressWarnings("rawtypes")
public static String getUserAgent(Context context) {
    String webUserAgent = null;
    if (context != null) {
        try {
            Class sysResCls = Class.forName("com.android.internal.R$string");
            Field webUserAgentField = sysResCls.getDeclaredField("web_user_agent");
            Integer resId = (Integer) webUserAgentField.get(null);
            webUserAgent = context.getString(resId);
        } catch (Throwable ignored) {
        }
    }
    if (TextUtils.isEmpty(webUserAgent)) {
        webUserAgent = "Mozilla/5.0 (Linux; U; Android %s) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 %sSafari/533.1";
    }

    Locale locale = Locale.getDefault();
    StringBuffer buffer = new StringBuffer();
    // Add version
    final String version = Build.VERSION.RELEASE;
    if (version.length() > 0) {
        buffer.append(version);
    } else {
        // default to "1.0"
        buffer.append("1.0");
    }
    buffer.append("; ");
    final String language = locale.getLanguage();
    if (language != null) {
        buffer.append(language.toLowerCase());
        final String country = locale.getCountry();
        if (country != null) {
            buffer.append("-");
            buffer.append(country.toLowerCase());
        }
    } else {
        // default to "en"
        buffer.append("en");
    }
    // add the model for the release build
    if ("REL".equals(Build.VERSION.CODENAME)) {
        final String model = Build.MODEL;
        if (model.length() > 0) {
            buffer.append("; ");
            buffer.append(model);
        }
    }
    final String id = Build.ID;
    if (id.length() > 0) {
        buffer.append(" Build/");
        buffer.append(id);
    }
    return String.format(webUserAgent, buffer, "Mobile ");
}

From source file:Dates.java

public static String dateTimeFormatForJSCalendar(Locale locale) {
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
    String datetime = df.format(create(1, 2, 1971, 15, 59, 0)); // d, m, y, hr, min, sec 
    boolean always4InYear = "es".equals(locale.getLanguage()) || "pl".equals(locale.getLanguage());
    String result = datetime.// w  ww  . j av  a  2  s. c om

    // time part
            replaceAll("15", "%H"). // 24hr format 
            replaceAll("03", "%I"). // 12hr format - double digit 
            replaceAll("3", "%l"). // 12hr format - single digit
            replaceAll("59", "%M"). // minute
            replaceAll("PM", "%p"). // AM/PM - uppercase
            replaceAll("pm", "%P"). // am/pm - lowercase

            // date part
            replaceAll("01", "%d"). // day - double digit
            replaceAll("02", "%m"). // month - double digit
            replaceAll("1971", "%Y"). // year - 4 digit
            replaceAll("71", always4InYear ? "%Y" : "%y"). // year - 2 digit     
            replaceAll("1", "%e"). // day - single digit
            replaceAll("2", "%m") // month - ??? seems only double digit is supported by calendar
    ;

    return result;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.RefactoredIndividualCandidacyProcessPublicDA.java

static private String readCountryCode(final Locale locale) {
    String country = locale.getCountry();
    String language = locale.getLanguage();

    String result = null;/*  ww  w.  j  a  v  a2  s. c o  m*/
    if (!StringUtils.isEmpty(country)) {
        result = country.toUpperCase();
    } else if (!StringUtils.isEmpty(language)) {
        result = language.toUpperCase();
    }

    if (!StringUtils.isEmpty(result)) {
        return result;
    }

    return "PT";
}

From source file:ch.entwine.weblounge.common.impl.language.LanguageUtils.java

/**
 * Returns the language object that represents the given locale.
 * //w w  w .j ava2s. c  o  m
 * @param locale
 *          the locale
 * @return the language
 * @throws UnknownLanguageException
 *           if there is no language for the given locale
 */
public static Language getLanguage(Locale locale) throws UnknownLanguageException {

    // Do we know this language already?
    Language language = systemLanguages.get(locale.getLanguage());
    if (language != null)
        return language;

    // Makes sure we get the locale in the right format (might be hand crafted)
    Matcher matcher = ACCEPT_LANGUAGE_HEADER.matcher(locale.getLanguage());
    if (matcher.matches()) {
        locale = new Locale(matcher.group(2), matcher.group(1));
    }

    // Check the system locales for a match
    Locale systemLocale = null;
    try {
        for (Locale l : Locale.getAvailableLocales()) {
            if (l.getISO3Language().equals(locale.getISO3Language())) {
                systemLocale = l;
                break;
            } else if (l.getLanguage().equals(l.getLanguage())) {
                systemLocale = l;
                break;
            }
        }
    } catch (MissingResourceException e) {
        logger.debug("No 3 found for '{}': {}", locale, e.getMessage());
    }

    // Is there a matching system locale?
    if (systemLocale != null) {
        language = new LanguageImpl(locale);
        systemLanguages.put(locale.getLanguage(), language);
        return language;
    }

    // Apparently not...
    throw new UnknownLanguageException(locale.getLanguage());
}

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

private static void addFacetsTo(SimpleSearch simpleSearch, SolrQuery query, boolean withMultiValuedFacets,
        boolean withSingleValuedFacets, boolean notIncludedOnly) {
    List<SearchedFacet> searchedFacets = simpleSearch.getSearchedFacets();
    for (SearchedFacet searchedFacet : searchedFacets) {
        SearchableFacet searchableFacet = searchedFacet.getSearchableFacet();
        if ((searchableFacet.isMultiValued() && withMultiValuedFacets)
                || (!searchableFacet.isMultiValued() && withSingleValuedFacets)) {
            if (!searchableFacet.isCluster()) {
                if (searchableFacet.isQuery()) {
                    if (!searchedFacet.getIncludedValues().isEmpty()) {
                        StringBuffer sb = new StringBuffer("");
                        if (notIncludedOnly) {
                            sb.append("{!tag=dt}");
                            // sb.append("{!tag=");
                            // boolean first = true;
                            // for (String includedValue : searchedFacet.getIncludedValues()) {
                            // if (first) {
                            // first = false;
                            // } else {
                            // sb.append(",");
                            // }
                            // sb.append(includedValue);
                            // }
                            // sb.append("}");
                        }//from   w  w w  .  j  a v  a2s  . com
                        sb.append("(");
                        boolean first = true;
                        for (String includedValue : searchedFacet.getIncludedValues()) {
                            if (first) {
                                first = false;
                            } else {
                                sb.append(" OR ");
                            }
                            sb.append(includedValue);
                        }
                        sb.append(")");
                        query.addFilterQuery(sb.toString());
                    }
                } else {
                    String facetName = searchableFacet.getName();
                    if (!searchedFacet.getIncludedValues().isEmpty()) {
                        StringBuffer sb = new StringBuffer();
                        if (notIncludedOnly) {
                            sb.append("{!tag=dt}");
                            // StringBuffer sbTag = new StringBuffer();
                            // sbTag.append("{!tag=");
                            // boolean first = true;
                            // for (String includedValue : searchedFacet.getIncludedValues()) {
                            // if (first) {
                            // first = false;
                            // } else {
                            // sbTag.append(",");
                            // }
                            // sbTag.append(includedValue);
                            // }
                            // sbTag.append("}");
                            // sb.append(sbTag);
                        }
                        sb.append(facetName + ":(");
                        boolean first = true;
                        for (String includedValue : searchedFacet.getIncludedValues()) {
                            if (first) {
                                first = false;
                            } else {
                                sb.append(" OR ");
                            }
                            sb.append("\"");
                            sb.append(SimpleSearch.correctFacetValue(includedValue));
                            sb.append("\"");
                        }
                        sb.append(")");
                        query.addFilterQuery(sb.toString());
                    }
                }
            }
        }
    }

    // valeurs exclues
    for (SearchedFacet searchedFacet : searchedFacets) {
        SearchableFacet searchableFacet = searchedFacet.getSearchableFacet();
        if (!searchableFacet.isCluster() && !searchedFacet.getExcludedValues().isEmpty()) {
            StringBuffer sb = new StringBuffer();
            String facetName = searchableFacet.getName();
            for (String excludedValue : searchedFacet.getExcludedValues()) {
                sb.append("NOT ");
                if (searchableFacet.isQuery()) {
                    sb.append(SimpleSearch.correctFacetValue(excludedValue));
                } else {
                    sb.append(facetName);
                    sb.append(":\"");
                    sb.append(SimpleSearch.correctFacetValue(excludedValue));
                    sb.append("\"");
                }
            }
            String sbToString = sb.toString();
            if (!sbToString.isEmpty()) {
                query.addFilterQuery(sb.toString());
            }
        }
    }

    SearchedFacet cluster = simpleSearch.getCluster();
    if (cluster != null) {
        RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
        RecordCollection collection = collectionServices.get(simpleSearch.getCollectionName());
        IndexField uniqueKeyIndexField = collection.getUniqueKeyIndexField();

        if (!cluster.getIncludedValues().isEmpty()) {
            StringBuilder sb = new StringBuilder(uniqueKeyIndexField.getName() + ":(");
            for (String includedValue : cluster.getIncludedValues()) {
                boolean first = true;
                StringTokenizer st = new StringTokenizer(includedValue, FacetValue.CONCAT_DELIM);
                while (st.hasMoreTokens()) {
                    String docId = st.nextToken();
                    if (first) {
                        first = false;
                    } else {
                        sb.append(" OR ");
                    }
                    sb.append("\"");
                    sb.append(docId);
                    sb.append("\"");
                }
            }
            sb.append(")");
            query.addFilterQuery(sb.toString());
        }
        if (!cluster.getExcludedValues().isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String excludedValue : cluster.getExcludedValues()) {
                StringTokenizer st = new StringTokenizer(excludedValue, FacetValue.CONCAT_DELIM);
                while (st.hasMoreTokens()) {
                    String docId = st.nextToken();
                    sb.append("NOT ");
                    sb.append(uniqueKeyIndexField.getName());
                    sb.append(":\"");
                    sb.append(docId);
                    sb.append("\"");
                    if (st.hasMoreTokens()) {
                        sb.append(" ");
                    }
                }
            }
            query.addFilterQuery(sb.toString());
        }
    }

    CloudKeyword cloudKeyword = simpleSearch.getCloudKeyword();
    if (cloudKeyword != null) {
        query.addFilterQuery("keyword:\"" + cloudKeyword.getKeyword() + "\"");
    }

    Locale singleSearchLocale = simpleSearch.getSingleSearchLocale();
    if (singleSearchLocale != null && StringUtils.isNotBlank(singleSearchLocale.getLanguage())) {
        query.addFilterQuery(IndexField.LANGUAGE_FIELD + ":\"" + singleSearchLocale.getLanguage() + "\"");
    }

    query.addFilterQuery(IndexField.DB_EXCLUDED_FIELD + ":\"false\"");
}

From source file:lucee.commons.i18n.FormatUtil.java

private static void addCustom(List<DateFormat> list, Locale locale, short formatType) {
    // get custom formats from file
    Config config = ThreadLocalPageContext.getConfig();
    Resource dir = config.getConfigDir().getRealResource("locales");
    if (dir.isDirectory()) {
        String appendix = "-datetime";
        if (formatType == FORMAT_TYPE_DATE)
            appendix = "-date";
        if (formatType == FORMAT_TYPE_TIME)
            appendix = "-time";

        Resource file = dir//w  w  w. j av  a2 s .c  om
                .getRealResource(locale.getLanguage() + "-" + locale.getCountry() + appendix + ".df");
        if (file.isFile()) {
            try {
                String content = IOUtil.toString(file, (Charset) null);
                String[] arr = lucee.runtime.type.util.ListUtil.listToStringArray(content, '\n');
                String line;
                SimpleDateFormat sdf;
                for (int i = 0; i < arr.length; i++) {
                    line = arr[i].trim();
                    if (StringUtil.isEmpty(line))
                        continue;
                    sdf = new SimpleDateFormat(line, locale);
                    if (!list.contains(sdf))
                        list.add(sdf);
                }

            } catch (Throwable t) {
            }
        }
    }
}

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

private synchronized static void init() {
    if (Utils.instance == null) {
        List<Locale> listaLingueDisponibili = Utils.getListaLingueDisponibili();
        Utils.instance = new HashMap<String, Utils>();
        if (listaLingueDisponibili != null && listaLingueDisponibili.size() > 0) {
            for (int i = 0; i < listaLingueDisponibili.size(); i++) {
                Locale locale = listaLingueDisponibili.get(i);
                Utils.instance.put(locale.getLanguage(), new Utils(locale));
            }/*from   w w  w. j  a v a2 s  .  co  m*/
        } else {
            // italiano sempre presente
            Utils.instance.put(Locale.ITALIAN.getLanguage(), new Utils(Locale.ITALIAN));
        }
    }
}

From source file:com.heliosphere.demeter.base.resource.bundle.ResourceBundleManager.java

/**
 * Refresh all the resource bundles already handled by the
 * {@link ResourceBundleManager} for the given {@link Locale}.
 * <p>/*from  www. ja va  2s  .  c o  m*/
 * @param locale {@link Locale} corresponding to the new language to use.
 */
@SuppressWarnings("nls")
private static final void refresh(final Locale locale) {
    if (NAMES.isEmpty()) {
        ResourceBundleManager.locale = locale;
    }

    for (Class<? extends IBundle> bundleClass : NAMES.keySet()) {
        final ResourceBundle bundle = ResourceBundle.getBundle(NAMES.get(bundleClass), locale);
        if (bundle != null && bundle.getLocale().getLanguage() != locale.getLanguage()) {
            log.error("Bundle cannot be found [name=" + NAMES.get(bundleClass) + ", locale=" + locale.toString()
                    + "]. Using default one [name=" + NAMES.get(bundleClass) + ", locale="
                    + getLocale().toString() + "]");
            ResourceBundleManager.locale = english;
        } else {
            ResourceBundleManager.locale = locale;
        }

        BUNDLES.clear();
        register(bundleClass, bundle);
    }
}

From source file:com.heliosphere.athena.base.resource.bundle.ResourceBundleManager.java

/**
 * Refresh all the resource bundles already handled by the
 * {@link ResourceBundleManager} for the given {@link Locale}.
 * <p>/*  w ww  . j a va 2 s  .  c o m*/
 * @param locale {@link Locale} corresponding to the new language to use.
 */
@SuppressWarnings("nls")
private static final void refresh(final Locale locale) {
    if (NAMES.isEmpty()) {
        ResourceBundleManager.locale = locale;
    }

    for (Class<? extends IBundle> bundleClass : NAMES.keySet()) {
        final ResourceBundle bundle = ResourceBundle.getBundle(NAMES.get(bundleClass), locale);
        if (bundle != null && !bundle.getLocale().getLanguage().equals(locale.getLanguage())) {
            log.error("Bundle cannot be found [name=" + NAMES.get(bundleClass) + ", locale=" + locale.toString()
                    + "]. Using default one [name=" + NAMES.get(bundleClass) + ", locale="
                    + getLocale().toString() + "]");
            ResourceBundleManager.locale = english;
        } else {
            ResourceBundleManager.locale = locale;
        }

        BUNDLES.clear();
        register(bundleClass, bundle);
    }
}