Java Code Examples for com.ibm.icu.util.ULocale#forLanguageTag()

The following examples show how to use com.ibm.icu.util.ULocale#forLanguageTag() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MeasureFormat.java    From fitnotifications with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    in.readByte(); // version.
    locale = ULocale.forLanguageTag(in.readUTF());
    formatWidth = fromFormatWidthOrdinal(in.readByte() & 0xFF);
    numberFormat = (NumberFormat) in.readObject();
    if (numberFormat == null) {
        throw new InvalidObjectException("Missing number format.");
    }
    subClass = in.readByte() & 0xFF;

    // This cast is safe because the serialized form of hashtable can have
    // any object as the key and any object as the value.
    keyValues = (HashMap<Object, Object>) in.readObject();
    if (keyValues == null) {
        throw new InvalidObjectException("Missing optional values map.");
    }
}
 
Example 2
Source File: MessageFormat.java    From fitnotifications with Apache License 2.0 6 votes vote down vote up
/**
 * Custom deserialization, new in ICU 4.8. See comments on writeObject().
 * @throws InvalidObjectException if the objects read from the stream is invalid.
 */
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    // ICU 4.8 custom deserialization.
    String languageTag = (String)in.readObject();
    ulocale = ULocale.forLanguageTag(languageTag);
    MessagePattern.ApostropheMode aposMode = (MessagePattern.ApostropheMode)in.readObject();
    if (msgPattern == null || aposMode != msgPattern.getApostropheMode()) {
        msgPattern = new MessagePattern(aposMode);
    }
    String msg = (String)in.readObject();
    if (msg != null) {
        applyPattern(msg);
    }
    // custom formatters
    for (int numFormatters = in.readInt(); numFormatters > 0; --numFormatters) {
        int formatIndex = in.readInt();
        Format formatter = (Format)in.readObject();
        setFormat(formatIndex, formatter);
    }
    // skip future (int, Object) pairs
    for (int numPairs = in.readInt(); numPairs > 0; --numPairs) {
        in.readInt();
        in.readObject();
    }
}
 
Example 3
Source File: LocalizationUtils.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
/**
 * Converts an array of language tags to a list of ULocale instances ordered according to priority, availability and
 * fallback rules. For example "en-us-posix" will be returned as a List containing the ULocales for "en-us-posix",
 * "en-us", and "en".
 * 
 * @param locales
 * @return
 */
public static List<ULocale> getProcessedLocaleList(String[] locales) {
    if (locales == null)
        return getDefaultLocaleList();
    GlobalizationPreferences prefs = new GlobalizationPreferences();

    ArrayList<ULocale> ulocales = new ArrayList<ULocale>();
    for (String locale : locales) {
        if (locale != null) {
            try {
                ULocale ulocale = ULocale.forLanguageTag(locale);
                if (!ulocale.getLanguage().equals(""))
                    ulocales.add(ulocale);
            } catch (Exception e) {
                // There can be intermittent problems with the internal
                // functioning of the ULocale class with some
                // language tags; best to just log these and continue
                _logger.error("icu4j:ULocale.forLanguageTag(" + locale + ") threw Exception:", e);
            }
        }
    }
    if (ulocales.isEmpty())
        return getDefaultLocaleList();
    prefs.setLocales(ulocales.toArray(new ULocale[ulocales.size()]));
    return prefs.getLocales();
}
 
Example 4
Source File: LocalizationUtils.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
/**
 * Validates a given language tag. Empty and null values are considered false.
 * 
 * @param tag
 * @return true if a valid language tag, otherwise false
 */
public static boolean isValidLanguageTag(String tag) {
    try {
        ULocale locale = ULocale.forLanguageTag(tag);
        if (locale.toLanguageTag() == null) {
            return false;
}
        // We don't accept "x" extensions (private use tags)
        if (locale.getExtension("x".charAt(0)) != null) {
            return false;
}
        if (!locale.toLanguageTag().equalsIgnoreCase(tag)) {
            return false;
}
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 5
Source File: SegmenterObject.java    From es6draft with MIT License 6 votes vote down vote up
private BreakIterator createBreakIterator() {
    ULocale locale = ULocale.forLanguageTag(this.locale);
    if ("line".equals(granularity)) {
        // "strictness" cannot be set through unicode extensions (u-lb-strict), handle here:
        locale = locale.setKeywordValue("lb", strictness);
    }
    BreakIterator breakIterator;
    switch (granularity) {
    case "grapheme":
        breakIterator = BreakIterator.getCharacterInstance(locale);
        break;
    case "word":
        breakIterator = BreakIterator.getWordInstance(locale);
        break;
    case "sentence":
        breakIterator = BreakIterator.getSentenceInstance(locale);
        break;
    case "line":
        breakIterator = BreakIterator.getLineInstance(locale);
        break;
    default:
        throw new AssertionError();
    }
    return breakIterator;
}
 
Example 6
Source File: PluralRulesObject.java    From es6draft with MIT License 6 votes vote down vote up
private NumberFormat createNumberFormat() {
    ULocale locale = ULocale.forLanguageTag(this.locale);
    locale = locale.setKeywordValue("numbers", "latn");

    DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(locale, NumberFormat.NUMBERSTYLE);
    if (minimumSignificantDigits != 0 && maximumSignificantDigits != 0) {
        numberFormat.setSignificantDigitsUsed(true);
        numberFormat.setMinimumSignificantDigits(minimumSignificantDigits);
        numberFormat.setMaximumSignificantDigits(maximumSignificantDigits);
    } else {
        numberFormat.setSignificantDigitsUsed(false);
        numberFormat.setMinimumIntegerDigits(minimumIntegerDigits);
        numberFormat.setMinimumFractionDigits(minimumFractionDigits);
        numberFormat.setMaximumFractionDigits(maximumFractionDigits);
    }
    // as required by ToRawPrecision/ToRawFixed
    numberFormat.setRoundingMode(BigDecimal.ROUND_HALF_UP);
    return numberFormat;
}
 
Example 7
Source File: DateTimeFormatObject.java    From es6draft with MIT License 6 votes vote down vote up
private DateFormat createDateFormat() {
    ULocale locale = ULocale.forLanguageTag(this.locale);
    // calendar and numberingSystem are already handled in language-tag
    // assert locale.getKeywordValue("calendar").equals(calendar);
    // assert locale.getKeywordValue("numbers").equals(numberingSystem);
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern.get(), locale);
    if (timeZone != null) {
        dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
    }
    Calendar calendar = dateFormat.getCalendar();
    if (calendar instanceof GregorianCalendar) {
        // format uses a proleptic Gregorian calendar with no year 0
        GregorianCalendar gregorian = (GregorianCalendar) calendar;
        gregorian.setGregorianChange(new Date(Long.MIN_VALUE));
    }
    return dateFormat;
}
 
Example 8
Source File: PluralsHolder.java    From mojito with Apache License 2.0 5 votes vote down vote up
void retainForms(LocaleId localeId, List<String> pluralForms) {
    if (localeId != null && !LocaleId.EMPTY.equals(localeId)) {
        ULocale ulocale = ULocale.forLanguageTag(localeId.toBCP47());
        PluralRules pluralRules = PluralRules.forLocale(ulocale);
        pluralForms.retainAll(pluralRules.getKeywords());
    }
}
 
Example 9
Source File: DateTimeFormatConstructor.java    From es6draft with MIT License 5 votes vote down vote up
/**
 * 12.1.4 BestFitFormatMatcher (options, formats)
 * 
 * @param formatRecord
 *            the format matcher record
 * @param dataLocale
 *            the locale
 * @return the best applicable pattern
 */
public static String BestFitFormatMatcher(FormatMatcherRecord formatRecord, String dataLocale) {
    // Let ICU4J compute the best applicable pattern for the requested input values
    ULocale locale = ULocale.forLanguageTag(dataLocale);
    DateTimePatternGenerator generator = DateTimePatternGenerator.getInstance(locale);
    String pattern = generator.getBestPattern(formatRecord.toSkeleton());

    // Fixup the hour representation to match the expected hour cycle.
    if (formatRecord.isTime() && formatRecord.hasNonDefaultHourCycle(locale)) {
        pattern = modifyHour(formatRecord, pattern);
    }
    return pattern;
}
 
Example 10
Source File: NumberFormatObject.java    From es6draft with MIT License 5 votes vote down vote up
private NumberFormat createNumberFormat() {
    ULocale locale = ULocale.forLanguageTag(this.locale);
    int choice;
    if ("decimal".equals(style)) {
        choice = NumberFormat.NUMBERSTYLE;
    } else if ("percent".equals(style)) {
        choice = NumberFormat.PERCENTSTYLE;
    } else {
        if ("code".equals(currencyDisplay)) {
            choice = NumberFormat.ISOCURRENCYSTYLE;
        } else if ("symbol".equals(currencyDisplay)) {
            choice = NumberFormat.CURRENCYSTYLE;
        } else {
            choice = NumberFormat.PLURALCURRENCYSTYLE;
        }
    }
    DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(locale, choice);
    if ("currency".equals(style)) {
        numberFormat.setCurrency(Currency.getInstance(currency));
    }
    // numberingSystem is already handled in language-tag
    // assert locale.getKeywordValue("numbers").equals(numberingSystem);
    if (minimumSignificantDigits != 0 && maximumSignificantDigits != 0) {
        numberFormat.setSignificantDigitsUsed(true);
        numberFormat.setMinimumSignificantDigits(minimumSignificantDigits);
        numberFormat.setMaximumSignificantDigits(maximumSignificantDigits);
    } else {
        numberFormat.setSignificantDigitsUsed(false);
        numberFormat.setMinimumIntegerDigits(minimumIntegerDigits);
        numberFormat.setMinimumFractionDigits(minimumFractionDigits);
        numberFormat.setMaximumFractionDigits(maximumFractionDigits);
    }
    numberFormat.setGroupingUsed(useGrouping);
    // as required by ToRawPrecision/ToRawFixed
    // FIXME: ICU4J bug:
    // new Intl.NumberFormat("en",{useGrouping:false}).format(111111111111111)
    // returns "111111111111111.02"
    numberFormat.setRoundingMode(BigDecimal.ROUND_HALF_UP);
    return numberFormat;
}
 
Example 11
Source File: ListFormatObject.java    From es6draft with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
private ListFormatter createListFormatter() {
    ULocale locale = ULocale.forLanguageTag(this.locale);
    ICUResourceBundle r = (ICUResourceBundle) UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME, locale);
    String resourceStyle = resourceStyle();
    return new ListFormatter(r.getWithFallback("listPattern/" + resourceStyle + "/2").getString(),
            r.getWithFallback("listPattern/" + resourceStyle + "/start").getString(),
            r.getWithFallback("listPattern/" + resourceStyle + "/middle").getString(),
            r.getWithFallback("listPattern/" + resourceStyle + "/end").getString());
}
 
Example 12
Source File: RepositoryStatisticService.java    From mojito with Apache License 2.0 4 votes vote down vote up
private Long computeDiffToSourceLocaleCount(String targetLocaleBcp47Tag) {
    ULocale targetLocale = ULocale.forLanguageTag(targetLocaleBcp47Tag);
    PluralRules pluralRulesTargetLocale = PluralRules.forLocale(targetLocale);
    return 6L - pluralRulesTargetLocale.getKeywords().size();
}
 
Example 13
Source File: PluralFormForLocaleService.java    From mojito with Apache License 2.0 4 votes vote down vote up
public List<PluralFormForLocale> getPluralFormsForLocales() {
    
    List<PluralFormForLocale> pluralFormForLocales = new ArrayList<>();
    
    List<Locale> locales = localeRepository.findAll();
    
    for (Locale locale : locales) {
        
        ULocale forLanguageTag = ULocale.forLanguageTag(locale.getBcp47Tag());
        
        PluralRules pluralRules = PluralRules.forLocale(forLanguageTag);
        for (String keyword : pluralRules.getKeywords()) {
            logger.debug("{} : {} : {}", locale.getId(), locale.getBcp47Tag(), keyword);
            
            PluralFormForLocale pluralFormForLocale = new PluralFormForLocale();
            pluralFormForLocale.setPluralForm(pluralFormService.findByPluralFormString(keyword));
            pluralFormForLocale.setLocale(locale);
            
            pluralFormForLocales.add(pluralFormForLocale);
        }
    }
    
    return pluralFormForLocales;
}
 
Example 14
Source File: EvolveCommand.java    From mojito with Apache License 2.0 4 votes vote down vote up
boolean isRightToLeft(String bcp47Tag) {
    ULocale uLocale = ULocale.forLanguageTag(bcp47Tag);
    return uLocale.isRightToLeft();
}
 
Example 15
Source File: CollatorObject.java    From es6draft with MIT License 4 votes vote down vote up
private Collator createCollator() {
    ULocale locale = ULocale.forLanguageTag(this.locale);
    if ("search".equals(usage)) {
        // "search" usage cannot be set through unicode extensions (u-co-search), handle here:
        locale = locale.setKeywordValue("collation", "search");
    }
    RuleBasedCollator collator = (RuleBasedCollator) Collator.getInstance(locale);
    collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
    collator.setNumericCollation(numeric);
    switch (caseFirst) {
    case "upper":
        collator.setUpperCaseFirst(true);
        break;
    case "lower":
        collator.setLowerCaseFirst(true);
        break;
    case "false":
        if (collator.isLowerCaseFirst()) {
            collator.setLowerCaseFirst(false);
        }
        if (collator.isUpperCaseFirst()) {
            collator.setUpperCaseFirst(false);
        }
        break;
    default:
        throw new AssertionError();
    }
    switch (sensitivity) {
    case "base":
        collator.setStrength(Collator.PRIMARY);
        break;
    case "accent":
        collator.setStrength(Collator.SECONDARY);
        break;
    case "case":
        collator.setStrength(Collator.PRIMARY);
        collator.setCaseLevel(true);
        break;
    case "variant":
        collator.setStrength(Collator.TERTIARY);
        break;
    default:
        throw new AssertionError();
    }
    collator.setAlternateHandlingShifted(ignorePunctuation);
    return collator;
}
 
Example 16
Source File: PluralRulesObject.java    From es6draft with MIT License 4 votes vote down vote up
private PluralRules createPluralRules() {
    ULocale locale = ULocale.forLanguageTag(this.locale);
    PluralType pluralType = "cardinal".equals(type) ? PluralType.CARDINAL : PluralType.ORDINAL;
    return PluralRules.forLocale(locale, pluralType);
}