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.jamwiki.utils.WikiUtil.java

/**
 * Utility method for reading special topic values from files and returning
 * the file contents./*from  www. ja  v  a2 s . c o m*/
 *
 * @param locale The locale for the user viewing the special page.
 * @param pageName The name of the special page being retrieved.
 */
public static String readSpecialPage(Locale locale, String pageName) throws IOException {
    String contents = null;
    String filename = null;
    String language = null;
    String country = null;
    if (locale != null) {
        language = locale.getLanguage();
        country = locale.getCountry();
    }
    String subdirectory = "";
    if (!StringUtils.isBlank(language) && !StringUtils.isBlank(country)) {
        try {
            subdirectory = new File(WikiBase.SPECIAL_PAGE_DIR, language + "_" + country).getPath();
            filename = new File(subdirectory, WikiUtil.encodeForFilename(pageName) + ".txt").getPath();
            contents = Utilities.readFile(filename);
        } catch (IOException e) {
            logger.info("File " + filename + " does not exist");
        }
    }
    if (contents == null && !StringUtils.isBlank(language)) {
        try {
            subdirectory = new File(WikiBase.SPECIAL_PAGE_DIR, language).getPath();
            filename = new File(subdirectory, WikiUtil.encodeForFilename(pageName) + ".txt").getPath();
            contents = Utilities.readFile(filename);
        } catch (IOException e) {
            logger.info("File " + filename + " does not exist");
        }
    }
    if (contents == null) {
        try {
            subdirectory = new File(WikiBase.SPECIAL_PAGE_DIR).getPath();
            filename = new File(subdirectory, WikiUtil.encodeForFilename(pageName) + ".txt").getPath();
            contents = Utilities.readFile(filename);
        } catch (IOException e) {
            logger.warning("File " + filename + " could not be read", e);
            throw e;
        }
    }
    return contents;
}

From source file:org.languagetool.Language.java

private static Language getLanguageForLanguageNameAndCountry(Locale locale) {
    for (Language language : Language.REAL_LANGUAGES) {
        if (language.getShortName().equals(locale.getLanguage())) {
            final List<String> countryVariants = Arrays.asList(language.getCountries());
            if (countryVariants.contains(locale.getCountry())) {
                return language;
            }/*from   w  w w  . j  av a 2s .  c  om*/
        }
    }
    return null;
}

From source file:com.yolanda.nohttp.BasicRequest.java

/**
 * Create acceptLanguage./*from www. j  a v  a2  s .  c  om*/
 *
 * @return Returns the client can accept the language types. Such as:zh-CN,zh.
 */
public static String defaultAcceptLanguage() {
    if (TextUtils.isEmpty(acceptLanguage)) {
        Locale locale = Locale.getDefault();
        String language = locale.getLanguage();
        String country = locale.getCountry();
        StringBuilder acceptLanguageBuilder = new StringBuilder(language);
        if (!TextUtils.isEmpty(country))
            acceptLanguageBuilder.append('-').append(country).append(',').append(language);
        acceptLanguage = acceptLanguageBuilder.toString();
    }
    return acceptLanguage;
}

From source file:io.github.mathiasberwig.cloudvision.controller.service.RestApisConsumer.java

/**
 * Get a locale-dependent SPARQL  query for an entity on Wikidata. In it we query for brands as
 * instances/subclasses of business enterprise, bands or softwares.
 *
 * @param locale The locale to get language and country code.
 * @param brandName The name of the brand that will be queried.
 * @return A locale-dependent SPARQL query for the {@code brandName} provided.
 *//*www .ja va2 s.co  m*/
private static String getWikidataQuery(Locale locale, String brandName) {
    String language;
    // If the user locale language is any variant of english, we will query the default english
    // API. With different locales, we try to combine the language and country codes (like pt-BR),
    // and english is added as fallback lang (some properties doesn't have labels in other languages besides english).
    if (locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {
        language = locale.getLanguage();
    } else {
        language = locale.getCountry().equals("") ? String.format("%s,en", locale.getLanguage())
                : String.format("%s-%s,en", locale.getLanguage(), locale.getCountry());
    }

    String query = "SELECT DISTINCT " + " ?brand " + " ?website ?logo ?country ?inception"
            + " ?twitter ?facebook" + " ?founders " + " ?headquarters ?divisions ?employees" + " ?genre ?awards"
            + " ?developers ?languages ?licenses" + "WHERE {" + " ?brand ?label \"%s\" ." + // Search by Brand name
            " { ?brand wdt:P31/wdt:P279* wd:Q4830453 . }" + // Business enterprise (instance of any subclass of)
            " UNION" + " { ?brand wdt:P31/wdt:P279* wd:Q215380 . }" + // Band (instance of any subclass of)
            " UNION" + " { ?brand wdt:P31/wdt:P279* wd:Q7397 . }" + // Software (instance of any subclass of)
            " OPTIONAL { ?brand wdt:P856 ?website . }" + " OPTIONAL { ?brand wdt:P154 ?logo . }"
            + " OPTIONAL { ?brand wdt:P17 ?country . }" + " OPTIONAL { ?brand wdt:P495 ?country . }"
            + " OPTIONAL { ?brand wdt:P1128 ?employees . }" + " OPTIONAL { ?brand wdt:P571 ?inception . }"
            + " OPTIONAL { ?brand wdt:P2002 ?twitter . }" + " OPTIONAL { ?brand wdt:P2013 ?facebook . }"
            + " OPTIONAL { ?brand wdt:P136 ?genre . }" + " SERVICE wikibase:label {"
            + " bd:serviceParam wikibase:language \"%s\" ." + // Language for labels
            " ?country rdfs:label ?country ." + " ?genre rdfs:label ?genre }" + " { SELECT "
            + " (GROUP_CONCAT(DISTINCT(?founderLabel); separator=\", \") as ?founders)"
            + " (GROUP_CONCAT(DISTINCT(?industryLabel); separator=\", \") as ?divisions)"
            + " (GROUP_CONCAT(DISTINCT(?headquarterLabel); separator=\", \") as ?headquarters)"
            + " (GROUP_CONCAT(DISTINCT(?developerLabel); separator=\", \") as ?developers)"
            + " (GROUP_CONCAT(DISTINCT(?languageLabel); separator=\", \") as ?languages)"
            + " (GROUP_CONCAT(DISTINCT(?licenseLabel); separator=\", \") as ?licenses)"
            + " (GROUP_CONCAT(DISTINCT(?awardLabel); separator=\", \") as ?awards)" + " WHERE {"
            + " ?brand ?label \"%s\" ." + // Search by Brand name
            " { ?brand wdt:P31/wdt:P279* wd:Q4830453 . }" + // Business enterprise (instance of any subclass of)
            " UNION" + " { ?brand wdt:P31/wdt:P279* wd:Q215380 . }" + // Band (instance of any subclass of)
            " UNION" + " { ?brand wdt:P31/wdt:P279* wd:Q7397 . }" + // Software (instance of any subclass of)
            " OPTIONAL { ?brand wdt:P112 ?founder . }" + " OPTIONAL { ?brand wdt:P159 ?headquartersLocation . }"
            + " OPTIONAL { ?brand wdt:P452 ?industry . }  " + " OPTIONAL { ?brand wdt:P178 ?developer . }"
            + " OPTIONAL { ?brand wdt:P277 ?language . }" + " OPTIONAL { ?brand wdt:P275 ?license . }"
            + " OPTIONAL { ?brand wdt:P166 ?award . }" + " SERVICE wikibase:label {"
            + " bd:serviceParam wikibase:language \"%s\" ." + // Language for labels
            " ?founder rdfs:label ?founderLabel ." + " ?industry rdfs:label ?industryLabel ."
            + " ?headquartersLocation rdfs:label ?headquarterLabel ."
            + " ?developer rdfs:label ?developerLabel ." + " ?language rdfs:label ?languageLabel ."
            + " ?license rdfs:label ?licenseLabel ." + " ?award rdfs:label ?awardLabel }" + "} } }"
            + " ORDER BY ?brand" + " LIMIT 1";

    return String.format(query, brandName, language, brandName, language);
}

From source file:net.rim.ejde.internal.builders.ALXBuilder.java

private static ALXBuilder.Alx generateAlx(HashMap inherited, BlackBerryProject bbProject,
        boolean checkDependency) throws CoreException, ResourceParseException, FileNotFoundException {
    if (inherited == null) {
        inherited = new HashMap(); // used to pass values to projects this depends on
    }//from w  w  w .j  a va  2s . com

    BlackBerryProperties properties = ContextManager.PLUGIN.getBBProperties(bbProject.getProject().getName(),
            false);
    String outputName = properties._packaging.getOutputFileName();
    int end = outputName.lastIndexOf('.') == -1 ? outputName.length() : outputName.lastIndexOf('.');
    String outputNamenoext = outputName.substring(0, end);

    // access the resource tools and generate AlxBuilder.Language instances for each langauge supported (we're
    // looking for the resources for Title and Description, if provided

    // Add the output file name to the list of files required for this app
    HashMap<String, Object> requiredFilesList = new HashMap<String, Object>(); // use a hashmap to eliminate duplicates
    requiredFilesList.put(outputName, null);

    // Languages - generate an AlxBuilder.Lanuage instance for each language supported by the app
    Vector<Language> languages = new Vector<Language>(); // a vector to hold the Lanuage instances
    // If title resource not active, it is possibly a library,skip the languages step
    String titleResourceBundleClassName = properties._resources.getTitleResourceBundleClassName();
    String titleResourceBundleKey = properties._resources.getTitleResourceBundleKey();
    String rootTitle = IConstants.EMPTY_STRING, rootDescription = IConstants.EMPTY_STRING;
    if (properties._resources.hasTitleResource() && !StringUtils.isEmpty(titleResourceBundleClassName)
            && !StringUtils.isEmpty(titleResourceBundleKey)) {
        ResourceCollection resources;
        Map<String, RRHFile> resourceMap = ProjectUtils.getProjectResources(bbProject);
        IFile resourceFile = resourceMap.get(properties._resources.getTitleResourceBundleClassName()).getFile();
        if (resourceFile != null && resourceFile.exists()) {
            resources = ResourceCollectionFactory
                    .newResourceCollection(resourceFile.getLocation().toOSString());
            ResourceLocale[] resourceLocales = resources.getLocales();
            String titlevalue = null, descvalue = null;
            for (ResourceLocale resourceLocale : resourceLocales) {
                ResourceElement titleElement = resourceLocale
                        .getResourceElement(properties._resources.getTitleResourceBundleKey());
                if (titleElement != null) {
                    titlevalue = ResourceUtil.unicodeToEscaped(titleElement.getValueAsString());
                }
                ResourceElement descrElement = resourceLocale
                        .getResourceElement(properties._resources.getDescriptionId());
                if (descrElement != null) {
                    descvalue = ResourceUtil.unicodeToEscaped(descrElement.getValueAsString());
                }
                if (((titlevalue == null) && (descvalue == null))
                        || ((titlevalue == null) && (descvalue.length() == 0))
                        || ((titlevalue.length() == 0) && (descvalue == null))
                        || ((titlevalue.length() == 0) && (descvalue.length() == 0))) {
                    continue;
                }
                // don't generate a language element for the root
                if (resourceLocale.getLocaleName().equals(IConstants.EMPTY_STRING)) {
                    // we need to remember the root title and the description values
                    rootTitle = titlevalue;
                    rootDescription = descvalue;
                    continue;
                }
                Locale locale = ConvertUtil.localeValueOf(resourceLocale.getLocaleName());
                languages.addElement(new ALXBuilder.Language(locale.getISO3Language(), locale.getCountry(),
                        titlevalue, descvalue));
            }
        }
    }

    String copyright = "Copyright (c) " + Integer.toString(Calendar.getInstance().get(Calendar.YEAR)) + " "
            + properties._general.getVendor();

    // TODO: what directory for the FileSet? currently using the vendor name as the subdir, with '_' substituted for ' '
    /*
     * String dir = vendor.replace(' ', '_'); //String any trailing dots (windows strips them in path names for some reason)
     * dir = dir.endsWith(".") ? dir.substring(0, dir.length() - 1) : dir;
     */
    String vmversion = VMConst.DebugAPIVersionMajor + "." + VMConst.DebugAPIVersionMinor;

    // Generate all the dependency ALX objects
    Vector<Alx> dependencies = new Vector<Alx>();

    if (checkDependency) {
        for (BlackBerryProject dependantProj : ProjectUtils.getAllReferencedProjects(bbProject)) {
            // we do not need to recursively check the dependent project
            dependencies.addElement(ALXBuilder.generateAlx(inherited, dependantProj, false));
        }
    }

    // a vector to hold the alxImport instances
    Vector<AlxImport> alxImports = new Vector<AlxImport>();

    // create a new alxImport for each filename
    IFile alxFile;
    for (String alxFileName : properties._packaging.getAlxFiles()) {
        alxFile = bbProject.getProject().getFile(alxFileName);
        if (alxFile.exists()) {
            alxImports.addElement(new ALXBuilder.AlxImport(alxFile.getLocation().toOSString()));
        }
    }

    List<IVMInstall> vmList = VMUtils.getInstalledBBVMs();
    List<ALXBuilder.FileSet> fileSetList = new ArrayList<FileSet>();
    BlackBerrySDKInstall bbVM;
    String currentVersionString;
    Version bbVersionLeftBound, bbVersionRightBound;
    String compatiableVersion;
    Collections.sort(vmList, new VMUtils.VMGeneralComparator());
    int indexOfNextValidVM = nextValidBBVM(null, vmList, bbProject);
    while (indexOfNextValidVM >= 0) {
        bbVM = (BlackBerrySDKInstall) vmList.get(indexOfNextValidVM);
        currentVersionString = bbVM.getVMVersion();
        indexOfNextValidVM = nextValidBBVM(bbVM, vmList, bbProject);
        if (indexOfNextValidVM > 0) {
            bbVersionLeftBound = new Version(currentVersionString);
            bbVersionRightBound = new Version(bbVersionLeftBound.getMajor(), bbVersionLeftBound.getMinor(),
                    bbVersionLeftBound.getMicro() + 1);
            compatiableVersion = "[" + currentVersionString + "," + bbVersionRightBound + ")";
        } else {
            compatiableVersion = "[" + currentVersionString + ")";
        }
        if (currentVersionString.equalsIgnoreCase(IConstants.HEADVER_VM_VERSION)) {
            currentVersionString = IConstants.HEADVER_VM_OUTPUTFOLDER;
        }
        fileSetList.add(new ALXBuilder.FileSet(currentVersionString,
                new Vector<String>(requiredFilesList.keySet()), vmversion, compatiableVersion));
    }
    if (properties._resources.hasTitleResource() && !StringUtils.isEmpty(titleResourceBundleClassName)
            && !StringUtils.isEmpty(titleResourceBundleKey)) {
        // if resource is used, we use the root title and description
        return new ALXBuilder.Alx(outputNamenoext, rootTitle, rootDescription, properties._general.getVersion(),
                properties._general.getVendor(), copyright, languages, fileSetList, dependencies, alxImports);
    } else {
        return new ALXBuilder.Alx(outputNamenoext, properties._general.getTitle(),
                properties._general.getDescription(), properties._general.getVersion(),
                properties._general.getVendor(), copyright, languages, fileSetList, dependencies, alxImports);
    }

}

From source file:ORG.oclc.os.SRW.SRWServletInfo.java

public static String findRealXsl(String languages, Enumeration locales, String xsl) {
    log.debug("looking for stylesheet: " + xsl + " in languages: " + languages);
    File f;/*from  w w w.j  a va2 s.  c o m*/
    Locale l;
    String base = xsl, realXsl = xsl, suffix = null;

    // strip off suffix
    int off = xsl.lastIndexOf('.');
    if (off > 0) {
        base = xsl.substring(0, off);
        suffix = xsl.substring(off);
    }
    while (locales.hasMoreElements()) {
        l = (Locale) locales.nextElement();
        log.error("looking for " + xsl + " in " + webappHome + "/" + base + "_" + l.getLanguage() + "_"
                + l.getCountry() + suffix);
        f = new File(webappHome + "/" + base + "_" + l.getLanguage() + "_" + l.getCountry() + suffix);
        if (f.exists()) {
            log.debug("found " + f.getAbsolutePath());
            realXsl = base + "_" + l.getLanguage() + "_" + l.getCountry() + suffix;
            break;
        }
        log.debug("didn't find " + f.getAbsolutePath());
        log.error("looking in " + tomcatHome + "/" + base + "_" + l.getLanguage() + "_" + l.getCountry()
                + suffix);
        f = new File(tomcatHome + "/" + base + "_" + l.getLanguage() + "_" + l.getCountry() + suffix);
        if (f.exists()) {
            log.debug("found " + f.getAbsolutePath());
            realXsl = base + "_" + l.getLanguage() + "_" + l.getCountry() + suffix;
            break;
        }
        log.debug("didn't find " + f.getAbsolutePath());
        log.error("looking in " + webappHome + "/" + base + "_" + l.getLanguage() + suffix);
        f = new File(webappHome + "/" + base + "_" + l.getLanguage() + suffix);
        if (f.exists()) {
            log.debug("found " + f.getAbsolutePath());
            realXsl = base + "_" + l.getLanguage() + suffix;
            break;
        }
        log.error("looking in " + tomcatHome + "/" + base + "_" + l.getLanguage() + suffix);
        f = new File(tomcatHome + "/" + base + "_" + l.getLanguage() + suffix);
        if (f.exists()) {
            log.debug("found " + f.getAbsolutePath());
            realXsl = base + "_" + l.getLanguage() + suffix;
            break;
        }
        log.debug("didn't find " + f.getAbsolutePath());
    }
    realXsls.put(languages + "/" + xsl, realXsl);
    return realXsl;
}

From source file:net.pms.util.Languages.java

private static String localeToLanguageCode(Locale locale) {
    /*// w  w w.ja v  a  2  s.co  m
     * This might seem redundant, but a language can also contain a
     * country/region and a variant. Stating that e.g language
     * "ar" should return "ar" means that "messages_ar.properties"
     * will be used for any country/region and variant of Arabic.
     * This should be true until UMS contains multiple dialects of Arabic,
     * in which case different codes would have to be returned for the
     * different dialects.
     */

    if (locale == null) {
        return null;
    }
    String languageCode = locale.getLanguage();
    if (languageCode != null && !languageCode.isEmpty()) {
        switch (languageCode) {
        case "en":
            if (locale.getCountry().equalsIgnoreCase("GB")) {
                return "en-GB";
            } else {
                return "en-US";
            }
        case "pt":
            if (locale.getCountry().equalsIgnoreCase("BR")) {
                return "pt-BR";
            } else {
                return "pt";
            }
        case "nb":
        case "nn":
            return "no";
        case "cmn":
        case "zh":
            if (locale.getScript().equalsIgnoreCase("Hans")) {
                return "zh-Hans";
            } else if (locale.getCountry().equalsIgnoreCase("CN")
                    || locale.getCountry().equalsIgnoreCase("SG")) {
                return "zh-Hans";
            } else {
                return "zh-Hant";
            }
        default:
            return languageCode;
        }
    } else {
        return null;
    }
}

From source file:org.pentaho.platform.engine.services.actionsequence.ActionSequenceResource.java

public static long getLastModifiedDate(String filePath, Locale locale) {
    if (filePath.startsWith("system")) {
        File file = null;//  w ww . jav a  2s. com
        filePath = PentahoSystem.getApplicationContext().getSolutionPath(filePath);
        if (locale == null) {
            file = new File(filePath);
        } else {
            String extension = FilenameUtils.getExtension(filePath);
            String baseName = FilenameUtils.removeExtension(filePath);
            if (extension.length() > 0) {
                extension = "." + extension; //$NON-NLS-1$
            }
            String language = locale.getLanguage();
            String country = locale.getCountry();
            String variant = locale.getVariant();
            if (!variant.equals("")) { //$NON-NLS-1$
                file = new File(baseName + "_" + language + "_" + country + "_" + variant + extension); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            }
            if ((file == null) || !file.exists()) {
                file = new File(baseName + "_" + language + "_" + country + extension); //$NON-NLS-1$//$NON-NLS-2$
            }
            if ((file == null) || !file.exists()) {
                file = new File(baseName + "_" + language + extension); //$NON-NLS-1$
            }
            if ((file == null) || !file.exists()) {
                file = new File(filePath);
            }
        }
        if (file != null) {
            return file.lastModified();
        }
    } else {
        RepositoryFile repositoryFile = null;
        if (locale == null) {
            repositoryFile = getRepository().getFile(filePath);
        } else {
            String extension = FilenameUtils.getExtension(filePath);
            String baseName = FilenameUtils.removeExtension(filePath);
            if (extension.length() > 0) {
                extension = "." + extension; //$NON-NLS-1$
            }
            String language = locale.getLanguage();
            String country = locale.getCountry();
            String variant = locale.getVariant();
            if (!variant.equals("")) { //$NON-NLS-1$
                repositoryFile = getRepository()
                        .getFile(baseName + "_" + language + "_" + country + "_" + variant + extension); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            }
            if (repositoryFile == null) {
                repositoryFile = getRepository().getFile(baseName + "_" + language + "_" + country + extension); //$NON-NLS-1$//$NON-NLS-2$
            }
            if (repositoryFile == null) {
                repositoryFile = getRepository().getFile(baseName + "_" + language + extension); //$NON-NLS-1$
            }
            if (repositoryFile == null) {
                repositoryFile = getRepository().getFile(filePath);
            }
        }
        if (repositoryFile != null) {
            return repositoryFile.getLastModifiedDate().getTime();
        }
    }
    return -1L;
}

From source file:com.cyclopsgroup.waterview.ui.view.system.status.SetLocale.java

/**
 * Overwrite or implement method execute()
 *
 * @see com.cyclopsgroup.waterview.Module#execute(com.cyclopsgroup.waterview.RuntimeData, com.cyclopsgroup.waterview.Context)
 *///from   w w  w.  j a v a2 s.co m
public void execute(RuntimeData data, Context context) throws Exception {
    Locale[] locales = Locale.getAvailableLocales();
    TreeMap availableLocales = new TreeMap();
    for (int i = 0; i < locales.length; i++) {
        Locale locale = locales[i];
        if (StringUtils.isEmpty(locale.getCountry())) {
            continue;
        }
        String key = locale.getCountry() + '|' + locale.getLanguage();
        availableLocales.put(key, locale);
    }
    context.put("availableLocales", availableLocales.values());
    context.put("currentLocale", data.getSessionContext().get(RuntimeData.LOCALE_NAME));
}

From source file:com.job.portal.HomeController.java

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    System.out.println("Welcome Client krish change " + locale.getCountry());
    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate);

    return "home";
}