Example usage for java.util Locale getCountry

List of usage examples for java.util Locale getCountry

Introduction

In this page you can find the example usage for java.util Locale getCountry.

Prototype

public String getCountry() 

Source Link

Document

Returns the country/region code for this locale, which should either be the empty string, an uppercase ISO 3166 2-letter code, or a UN M.49 3-digit code.

Usage

From source file:org.codelibs.fess.helper.QueryHelper.java

protected String getQueryLanguage() {
    final String[] supportedLanguages = systemHelper.getSupportedLanguages();
    if (supportedLanguages.length == 0) {
        return null;
    }//from  www. j av a  2s. co m
    if (defaultQueryLanguage != null) {
        return defaultQueryLanguage;
    }
    final HttpServletRequest request = RequestUtil.getRequest();
    if (request == null) {
        return null;
    }
    final Locale locale = request.getLocale();
    if (locale == null) {
        return null;
    }
    final String language = locale.getLanguage();
    final String country = locale.getCountry();
    if (StringUtil.isNotBlank(language)) {
        if (StringUtil.isNotBlank(country)) {
            final String lang = language + "_" + country;
            for (final String value : supportedLanguages) {
                if (value.equals(lang)) {
                    final String fieldLang = fieldLanguageMap.get(value);
                    if (fieldLang == null) {
                        return value;
                    } else {
                        return fieldLang;
                    }
                }
            }
        }
        for (final String value : supportedLanguages) {
            if (value.equals(language)) {
                final String fieldLang = fieldLanguageMap.get(value);
                if (fieldLang == null) {
                    return value;
                } else {
                    return fieldLang;
                }
            }
        }
    }
    return null;
}

From source file:org.ireland.jnetty.http.HttpServletResponseImpl.java

@Override
// OK WITH TODO//from   w w  w.  ja  v a 2 s  .  c om
public void setLocale(Locale locale) {
    if (locale == null || isCommitted()) {
        return;
    }

    // Ignore any call from an included servlet
    if (isIncluding()) {
        return;
    }

    // Save the locale for use by getLocale()
    _locale = locale;

    // Set the contentLanguage for header output
    contentLanguage = locale.getLanguage();
    if ((contentLanguage != null) && (contentLanguage.length() > 0)) {
        String country = locale.getCountry();
        StringBuilder value = new StringBuilder(contentLanguage);
        if ((country != null) && (country.length() > 0)) {
            value.append('-');
            value.append(country);
        }
        contentLanguage = value.toString();
    }

    // Ignore any call made after the getWriter has been invoked.
    // The default should be used
    if (usingWriter) {
        return;
    }

    if (isCharacterEncodingSet) {
        return;
    }

    // :TODO
    /*
     * String charset = servletContext.getCharset(locale); if (charset != null) {
     * coyoteResponse.setCharacterEncoding(charset); }
     */
}

From source file:dhbw.clippinggorilla.userinterface.windows.NewSourceWindow.java

public void validateSecondStage(Source s, String id, String title, String url, String description,
        Category category, Locale language, Locale country, String imageUrl) {
    String errors = "";
    if (id == null || id.isEmpty()) {
        errors += "Empty Id<br>";
    }/*ww w.  ja v a2s . c  om*/
    if (title == null || title.isEmpty()) {
        errors += "Empty Name<br>";
    }
    if (!isURL(url)) {
        errors += "Empty or invalid URL<br>";
    }
    if (description == null || description.isEmpty()) {
        errors += "Empty Description<br>";
    }
    if (category == null) {
        errors += "Empty Category<br>";
    }
    if (language == null || language.equals(Locale.ROOT)) {
        errors += "Empty Language<br>";
    }
    if (country == null || country.equals(Locale.ROOT)) {
        errors += "Empty Country<br>";
    }
    if (!isURL(imageUrl)) {
        errors += "Empty or invalid ImageURL";
    }
    if (!errors.isEmpty()) {
        VaadinUtils.errorNotification("Errors during Source setup<br>" + errors);
    } else {
        s.setName(title);
        s.setUrl(url);
        s.setDescription(description);
        s.setCategory(category.name());//Ignore possible null pointer, cant happen
        s.setLanguageAndCountry(language.getLanguage(), country.getCountry());//Ignore possible null pointer, cant happen
        s.setLogo(imageUrl);
        setContent(getThirdStage(s));
        center();
    }

}

From source file:org.apache.cocoon.matching.LocaleMatcher.java

private boolean isValidResource(String pattern, Locale locale, Locale testLocale, Map map) {
    String url;/* w  w  w  .j  a v  a 2 s . c  o m*/

    String testLocaleStr = testLocale.toString();
    if ("".equals(testLocaleStr)) {
        // If same character found before and after the '*', leave only one.
        int starPos = pattern.indexOf("*");
        if (starPos < pattern.length() - 1 && starPos > 1
                && pattern.charAt(starPos - 1) == pattern.charAt(starPos + 1)) {
            url = pattern.substring(0, starPos - 1) + pattern.substring(starPos + 1);
        } else {
            url = StringUtils.replace(pattern, "*", "");
        }
    } else {
        url = StringUtils.replace(pattern, "*", testLocaleStr);
    }

    boolean result = true;
    if (testResourceExists) {
        Source source = null;
        try {
            source = resolver.resolveURI(url);
            result = source.exists();
        } catch (IOException e) {
            result = false;
        } finally {
            if (source != null) {
                resolver.release(source);
            }
        }
    }

    if (result) {
        map.put("source", url);
        map.put("matched-locale", testLocaleStr);
        if (locale != null) {
            map.put("locale", locale.toString());
            map.put("language", locale.getLanguage());
            map.put("country", locale.getCountry());
            map.put("variant", locale.getVariant());
        }
    }

    return result;
}

From source file:org.jahia.taglibs.uicomponents.i18n.DisplayLanguageSwitchLinkTag.java

public int doStartTag() {
    try {//w w w  . j a v a  2 s . com
        final StringBuilder buff = new StringBuilder();

        final boolean isCurrentBrowsingLanguage = isCurrentBrowsingLanguage(languageCode);
        final boolean isRedirectToHomePageActivated = InitLangBarAttributes.GO_TO_HOME_PAGE
                .equals(onLanguageSwitch);

        if (!isCurrentBrowsingLanguage) {
            if (isRedirectToHomePageActivated) {
                if (redirectCssClassName == null || redirectCssClassName.length() == 0) {
                    redirectCssClassName = InitLangBarAttributes.REDIRECT_DEFAULT_STYLE;
                }
                buff.append("<div class='");
                buff.append(redirectCssClassName);
                buff.append("'>");
            }
            buff.append("<a href='");
            final String link;
            if (onLanguageSwitch == null || onLanguageSwitch.length() == 0
                    || InitLangBarAttributes.STAY_ON_CURRENT_PAGE.equals(onLanguageSwitch)) {
                link = generateCurrentNodeLangSwitchLink(languageCode) + "##requestParameters##";

            } else if (isRedirectToHomePageActivated) {
                link = generateNodeLangSwitchLink(rootPage, languageCode) + "##requestParameters##";

            } else {
                throw new JspTagException("Unknown onLanguageSwitch attribute value " + onLanguageSwitch);
            }

            buff.append(StringEscapeUtils.escapeXml(link));
            if (urlVar != null && urlVar.length() > 0) {
                pageContext.setAttribute(urlVar, link);
            }
            buff.append("' ");
            buff.append("title='");
            if (isRedirectToHomePageActivated) {
                titleKey += "." + onLanguageSwitch;
            }
            buff.append(getMessage(titleKey, title));
            buff.append("'>");
        } else {
            buff.append("<span>");
            if (urlVar != null)
                pageContext.removeAttribute(urlVar, PageContext.PAGE_SCOPE);
        }

        String attributeValue = null;
        if (linkKind == null || linkKind.length() == 0 || LANGUAGE_CODE.equals(linkKind)
                || linkKind.startsWith(FLAG)) {
            attributeValue = languageCode;
            buff.append(languageCode);

        } else if (NAME_CURRENT_LOCALE.equals(linkKind)) {
            final Locale locale = LanguageCodeConverters.languageCodeToLocale(languageCode);
            final String value = locale.getDisplayName(getRenderContext().getMainResource().getLocale());
            attributeValue = value;
            buff.append(value);

        } else if (NAME_IN_LOCALE.equals(linkKind)) {
            final Locale locale = LanguageCodeConverters.languageCodeToLocale(languageCode);
            final String value = locale.getDisplayName(locale);
            attributeValue = value;
            buff.append(value);

        } else if (LETTER.equals(linkKind)) {
            final Locale locale = LanguageCodeConverters.languageCodeToLocale(languageCode);
            final String value = locale.getDisplayName(locale).substring(0, 1).toUpperCase();
            attributeValue = value;
            buff.append(value);

        } else if (DOUBLE_LETTER.equals(linkKind)) {
            final Locale locale = LanguageCodeConverters.languageCodeToLocale(languageCode);
            final String value = locale.getDisplayName(locale).substring(0, 2).toUpperCase();
            attributeValue = value;
            buff.append(value);

        } else if (ISOLOCALECOUNTRY_CODE.equals(linkKind)) {
            final Locale locale = LanguageCodeConverters.languageCodeToLocale(languageCode);
            StringBuilder value = new StringBuilder(locale.getLanguage().toUpperCase());
            if (locale.getCountry() != null && locale.getCountry().length() != 0) {
                value.append("(").append(locale.getCountry()).append(")");
            }
            attributeValue = value.toString();
            buff.append(value);

        } else {
            throw new JspTagException("Unknown linkKind value '" + linkKind + "'");
        }

        if (getVar() != null) {
            pageContext.setAttribute(getVar(), attributeValue);
        }

        if (!isCurrentBrowsingLanguage) {
            buff.append("</a>");
            if (isRedirectToHomePageActivated)
                buff.append("</div>");
        } else {
            buff.append("</span>");
        }

        if (display) {
            pageContext.getOut().print(buff.toString());
        }

    } catch (final Exception e) {
        logger.error("Error while getting language switch URL", e);
    }
    return SKIP_BODY;
}

From source file:org.sakaiproject.contentreview.turnitin.oc.ContentReviewServiceTurnitinOC.java

private String getUserEulaLocale(String userId) {
    String userLocale = null;/*from w ww .  ja v a 2  s . com*/
    // Check user preference for locale         
    // If user has no preference set - get the system default
    Locale locale = Optional.ofNullable(preferencesService.getLocale(userId)).orElse(Locale.getDefault());
    if (locale != null && StringUtils.isNotEmpty(locale.getCountry())) {
        StringBuilder sb = new StringBuilder();
        sb.append(locale.getLanguage());
        if (StringUtils.isNotEmpty(locale.getCountry())) {
            sb.append("-" + locale.getCountry());
        }
        userLocale = sb.toString();
    }
    //find available EULA langauges:
    boolean found = false;
    if (StringUtils.isNotEmpty(userLocale)) {
        Map<String, Object> eula = getLatestEula();
        if (eula != null && eula.containsKey("available_languages")
                && eula.get("available_languages") instanceof List) {

            for (String eula_locale : (List<String>) eula.get("available_languages")) {
                if (userLocale.equalsIgnoreCase(eula_locale)) {
                    //found exact match
                    userLocale = eula_locale;
                    found = true;
                    break;
                }
            }
            if (!found && StringUtils.isNotEmpty(locale.getLanguage()) && locale.getLanguage().length() >= 2) {
                //if we do not find the exact match, find a match based on the country code
                String userLanguage = locale.getLanguage().substring(0, 2);
                for (String eula_locale : (List<String>) eula.get("available_languages")) {
                    if (eula_locale.toLowerCase().startsWith(userLanguage.toLowerCase())) {
                        //found language match
                        userLocale = eula_locale;
                        found = true;
                        break;
                    }
                }
            }
        }
    }
    if (!found) {
        //user's locale was null or their langauge was not found, set default to english:
        userLocale = EULA_DEFAULT_LOCALE;
    }

    return userLocale;
}

From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java

public VerifyResult verify(final String number, final String brand, final String from, final int length,
        final Locale locale, final LineType type) throws IOException, SAXException {
    if (number == null || brand == null)
        throw new IllegalArgumentException("number and brand parameters are mandatory.");
    if (length > 0 && length != 4 && length != 6)
        throw new IllegalArgumentException("code length must be 4 or 6.");

    log.debug("HTTP-Number-Verify Client .. to [ " + number + " ] brand [ " + brand + " ] ");

    List<NameValuePair> params = new ArrayList<>();

    params.add(new BasicNameValuePair("api_key", this.apiKey));
    params.add(new BasicNameValuePair("api_secret", this.apiSecret));

    params.add(new BasicNameValuePair("number", number));
    params.add(new BasicNameValuePair("brand", brand));

    if (from != null)
        params.add(new BasicNameValuePair("sender_id", from));

    if (length > 0)
        params.add(new BasicNameValuePair("code_length", String.valueOf(length)));

    if (locale != null)
        params.add(//www.  j av a 2s  .c  o  m
                new BasicNameValuePair("lg", (locale.getLanguage() + "-" + locale.getCountry()).toLowerCase()));

    if (type != null)
        params.add(new BasicNameValuePair("require_type", type.toString()));

    String verifyBaseUrl = this.baseUrl + PATH_VERIFY;

    // Now that we have generated a query string, we can instanciate a HttpClient,
    // construct a POST method and execute to submit the request
    String response = null;
    for (int pass = 1; pass <= 2; pass++) {
        HttpPost httpPost = new HttpPost(verifyBaseUrl);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpUriRequest method = httpPost;
        String url = verifyBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8");

        try {
            if (this.httpClient == null)
                this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout)
                        .getNewHttpClient();
            HttpResponse httpResponse = this.httpClient.execute(method);
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status != 200)
                throw new Exception(
                        "got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] ");
            response = new BasicResponseHandler().handleResponse(httpResponse);
            log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
            break;
        } catch (Exception e) {
            method.abort();
            log.info("communication failure: " + e);
            String exceptionMsg = e.getMessage();
            if (exceptionMsg.indexOf("Read timed out") >= 0) {
                log.info(
                        "we're still connected, but the target did not respond in a timely manner ..  drop ...");
            } else {
                if (pass == 1) {
                    log.info("... re-establish http client ...");
                    this.httpClient = null;
                    continue;
                }
            }

            // return a COMMS failure ...
            return new VerifyResult(BaseResult.STATUS_COMMS_FAILURE, null,
                    "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e, true);
        }
    }

    Document doc;
    synchronized (this.documentBuilder) {
        doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
    }

    Element root = doc.getDocumentElement();
    if (!"verify_response".equals(root.getNodeName()))
        throw new IOException("No valid response found [ " + response + "] ");

    return parseVerifyResult(root);
}

From source file:org.opencommercesearch.AbstractSearchServer.java

public void setGroupParams(SolrQuery query, Locale locale) {
    query.set("group", true);
    query.set("group.ngroups", true);
    query.set("group.limit", 50);
    query.set("group.field", "productId");
    query.set("group.facet", false);

    if (isGroupSortingEnabled()) {
        List<SolrQuery.SortClause> clauses = query.getSorts();
        boolean isSortByScore = false;

        if (clauses.size() > 0) {
            for (SolrQuery.SortClause clause : clauses) {
                if (SCORE.equals(clause.getItem())) {
                    isSortByScore = true;
                }/*from   w ww .j  a va  2 s.com*/
            }
        } else {
            isSortByScore = true;
        }

        if (isSortByScore) {
            // break ties with custom sort field
            query.set("group.sort",
                    "isCloseout asc, salePrice" + locale.getCountry() + " asc, sort asc, score desc");
        }
    }
}

From source file:it.cnr.icar.eric.client.ui.thin.RegistryBrowser.java

/**
 * Returns the localized version of an English html file
 * English file is something like <root dir>/doc/webUI/userGuide.html
 * the localized file will be <root dir>/doc/webUI/locale/userGuide.html
 *//*from  w  w  w.  j a va 2s  . c  om*/
public String getLocalizedHTMLFile(String htmlFile) {

    if (htmlFile == null || htmlFile.equals(""))
        return htmlFile;

    // split the file into directory and file name. file name could be followed
    // by #anchor or \#anchor or something else
    int dirIndex = htmlFile.lastIndexOf('/');
    int extensionIndex = htmlFile.indexOf(".html");
    if (dirIndex == -1 || extensionIndex == -1 || (dirIndex + 1) > extensionIndex)
        return htmlFile;
    String dirName = htmlFile.substring(0, dirIndex);
    String fileName = htmlFile.substring(dirIndex + 1, extensionIndex);
    String anchor = htmlFile.substring(extensionIndex + 5);

    UserPreferencesBean userBean = new UserPreferencesBean();
    Locale uiLocale = userBean.getUiLocale();

    ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

    String localizedFile = dirName + "/" + uiLocale.toString() + "/" + fileName + ".html";
    // start with .. because the callers are passing the context path
    String realPath = ctx.getRealPath("../" + localizedFile);
    File f = new File(realPath);
    if (f.exists())
        return localizedFile + anchor;

    // try to use language country, without variant
    if (uiLocale.getVariant() != null && !"".equals(uiLocale.getVariant())) {
        localizedFile = dirName + "/" + uiLocale.getLanguage() + "_" + uiLocale.getCountry() + "/" + fileName
                + ".html";
        realPath = ctx.getRealPath("../" + localizedFile);
        f = new File(realPath);
        if (f.exists())
            return localizedFile + anchor;
    }

    // try to use language without country and variant
    if (uiLocale.getCountry() != null && !"".equals(uiLocale.getCountry())) {
        localizedFile = dirName + "/" + uiLocale.getLanguage() + "/" + fileName + ".html";
        realPath = ctx.getRealPath("../" + localizedFile);
        f = new File(realPath);
        if (f.exists())
            return localizedFile + anchor;
    }
    //fall back to original file
    return htmlFile;
}