Example usage for java.util Locale getISO3Language

List of usage examples for java.util Locale getISO3Language

Introduction

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

Prototype

public String getISO3Language() throws MissingResourceException 

Source Link

Document

Returns a three-letter abbreviation of this locale's language.

Usage

From source file:Main.java

public static void main(String[] args) {
    Locale locale = new Locale("en", "US", "WIN");

    System.out.println("Locale:" + locale);

    // print ISO3 language name for locale
    System.out.println("Name:" + locale.getISO3Language());

}

From source file:org.fao.geonet.kernel.LocaleUtil.java

/**
 * Attempts to match the code to a Locale.  If no match then the default Locale is returned
 * Case is ignored/*from www .  ja  v  a  2  s  .  c  o  m*/
 * 
 * @param langCode A 2 or 3 character ISO language code
 * @param defaultLocale the local returned if not match is made
 * @return the associated Locale or the default locale if no match is founde
 * 
 */
public static Locale toLocale(String langCode, Locale defaultLocale) {
    for (Locale loc : Locale.getAvailableLocales()) {
        if (loc.getISO3Language().toLowerCase().startsWith(langCode)) {
            return loc;
        }

    }
    return defaultLocale;
}

From source file:org.openmrs.util.LocaleUtility.java

/**
 * Checks if specified locale object is valid
 *
 * @param locale// ww w . j av  a  2s .c  om
 *            object for validation
 * @return true if locale is available
 */
public static boolean isValid(Locale locale) {
    try {
        return locale.getISO3Language() != null && locale.getISO3Country() != null;
    } catch (MissingResourceException e) {
        return false;
    }
}

From source file:com.hichinaschool.flashcards.anki.ReadText.java

public static void textToSpeech(String text, long did, int ord, int qa) {
    mTextToSpeak = text;/*  ww w  .  j  a v a  2s  .c om*/
    mQuestionAnswer = qa;
    mDid = did;
    mOrd = ord;

    String language = getLanguage(mDid, mOrd, mQuestionAnswer);
    if (availableTtsLocales.isEmpty()) {
        Locale[] systemLocales = Locale.getAvailableLocales();
        for (Locale loc : systemLocales) {
            if (mTts.isLanguageAvailable(loc) == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
                availableTtsLocales.add(new String[] { loc.getISO3Language(), loc.getDisplayName() });
            }
        }
    }

    // Check, if stored language is available
    for (int i = 0; i < availableTtsLocales.size(); i++) {
        if (language.equals(NO_TTS)) {
            return;
        } else if (language.equals(availableTtsLocales.get(i)[0])) {
            speak(mTextToSpeak, language);
            return;
        }
    }

    // Otherwise ask
    Resources res = mReviewer.getResources();
    StyledDialog.Builder builder = new StyledDialog.Builder(mReviewer);
    if (availableTtsLocales.size() == 0) {
        builder.setTitle(res.getString(R.string.no_tts_available_title));
        builder.setMessage(res.getString(R.string.no_tts_available_message));
        builder.setIcon(R.drawable.ic_dialog_alert);
        builder.setPositiveButton(res.getString(R.string.ok), null);
    } else {
        ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>();
        final ArrayList<String> dialogIds = new ArrayList<String>();
        builder.setTitle(R.string.select_locale_title);
        // Add option: "no tts"
        dialogItems.add(res.getString(R.string.tts_no_tts));
        dialogIds.add(NO_TTS);
        for (int i = 0; i < availableTtsLocales.size(); i++) {
            dialogItems.add(availableTtsLocales.get(i)[1]);
            dialogIds.add(availableTtsLocales.get(i)[0]);
        }
        String[] items = new String[dialogItems.size()];
        dialogItems.toArray(items);

        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                MetaDB.storeLanguage(mReviewer, mDid, mOrd, mQuestionAnswer, dialogIds.get(which));
                speak(mTextToSpeak, dialogIds.get(which));
            }
        });
    }
    builder.create().show();
}

From source file:org.encuestame.core.security.util.WidgetUtil.java

public static boolean isValid(Locale locale) {
    try {/*  ww  w  . j  av a  2s  .  co m*/
        return locale.getISO3Language() != null && locale.getISO3Country() != null;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.jahia.izpack.ResourcesConverter.java

/**
 * Performs conversion of the property file into XML language pack.
 * /*from  w w  w  . j a v  a  2 s.  com*/
 * @param bundleName
 *            the resource bundle name
 * @param locale
 *            locale to be used
 * @param targetFolder
 *            the target folder
 * @throws FileNotFoundException
 */
private static void convert(String bundleName, Locale locale, File targetFolder) throws FileNotFoundException {
    ResourceBundle enBundle = ResourceBundle.getBundle(bundleName, Locale.ENGLISH);
    ResourceBundle bundle = null;
    try {
        bundle = ResourceBundle.getBundle(bundleName, locale);
    } catch (MissingResourceException e) {
        bundle = enBundle;
    }
    PrintWriter out = new PrintWriter(new File(targetFolder,
            StringUtils.substringAfterLast(bundleName, ".") + "." + locale.getISO3Language() + ".xml"));
    Enumeration<String> keyEnum = enBundle.getKeys();
    List<String> keys = new LinkedList<String>();
    while (keyEnum.hasMoreElements()) {
        keys.add(keyEnum.nextElement());
    }
    Collections.sort(keys);
    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    out.println("<langpack>");
    for (String key : keys) {
        String value = null;
        try {
            value = bundle.getString(key);
        } catch (MissingResourceException e) {
            try {
                value = enBundle.getString(key);
            } catch (MissingResourceException e2) {
                value = key;
            }
        }
        out.append("    <str id=\"").append(key).append("\" txt=\"").append(StringEscapeUtils.escapeXml(value))
                .append("\"/>");
        out.println();
    }
    out.println("</langpack>");
    out.flush();
    out.close();
}

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

/**
 * Returns the language object that represents the given locale.
 * //  w w  w  .j av a  2  s .  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: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 . jav a  2  s.  co  m

    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:com.xpn.xwiki.util.Util.java

/**
 * Normalize the given language code. Converts the given language code to lower case and checks its validity (i.e.
 * whether it is an ISO 639 language code or the string "default").
 * <p>/*ww w .j a va2 s  . c om*/
 * 
 * <pre>
 * Util.normalizeLanguage(null)      = null
 * Util.normalizeLanguage("")        = ""
 * Util.normalizeLanguage("  ")      = ""
 * Util.normalizeLanguage("default") = "default"
 * Util.normalizeLanguage("DeFault") = "default"
 * Util.normalizeLanguage("invalid") = "default"
 * Util.normalizeLanguage("en")      = "en"
 * Util.normalizeLanguage("DE_at")   = "de_AT"
 * </pre>
 * 
 * </p>
 * 
 * @param languageCode the language code to normalize
 * @return normalized language code or the string "default" if the code is invalid
 */
public static String normalizeLanguage(String languageCode) {
    if (languageCode == null) {
        return null;
    }
    if (StringUtils.isBlank(languageCode)) {
        return "";
    }
    // handle language_COUNTRY case
    final String separator = "_";

    String[] parts = StringUtils.split(languageCode.toLowerCase(), "_-.");
    String result = parts[0];
    if (parts.length > 1) {
        parts[1] = parts[1].toUpperCase();
        // NOTE cannot use Locale#toString(), because it would change some language codes
        result = parts[0] + separator + parts[1];
    }
    // handle the "default" case
    final String defaultLanguage = "default";
    if (defaultLanguage.equals(result)) {
        return defaultLanguage;
    }
    try {
        Locale l = new Locale(parts[0], parts.length > 1 ? parts[1] : "");
        // Will throw an exception if the language code is not valid
        l.getISO3Language();
        return result;
    } catch (MissingResourceException ex) {
        LOGGER.warn("Invalid language: " + languageCode);
    }
    return defaultLanguage;
}

From source file:org.texconverter.TexConverter.java

private static Locale getLocale(final String localeCode) {
    Locale locale = null;

    if (localeCode != null) {
        Locale[] locales = Locale.getAvailableLocales();
        for (int i = 0; i < locales.length; i++) {
            if (localeCode.equalsIgnoreCase(locales[i].getISO3Language())) {
                locale = locales[i];/*from   w w  w  .j av a  2 s.  c  o m*/
                break;
            }
        }
        if (locale == null) {
            locale = Locale.getDefault();
            LOGGER.warn("getLocale -> unknown locale code " + localeCode + ", using system locale "
                    + locale.getISO3Language() + " instead.");
        }
    } else {
        locale = Locale.getDefault();
    }

    return locale;
}