Java Code Examples for com.ibm.icu.impl.ICUResourceBundle#getAllItemsWithFallback()

The following examples show how to use com.ibm.icu.impl.ICUResourceBundle#getAllItemsWithFallback() . 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: RelativeDateTimeFormatter.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
public RelativeDateTimeFormatterData load() {
    // Sink for traversing data.
    RelDateTimeDataSink sink = new RelDateTimeDataSink();

    ICUResourceBundle r = (ICUResourceBundle)UResourceBundle.
            getBundleInstance(ICUData.ICU_BASE_NAME, ulocale);
    r.getAllItemsWithFallback("fields", sink);

    // Check fallbacks array for loops or too many levels.
    for (Style testStyle : Style.values()) {
        Style newStyle1 = fallbackCache[testStyle.ordinal()];
        // Data loading guaranteed newStyle1 != testStyle.
        if (newStyle1 != null) {
            Style newStyle2 = fallbackCache[newStyle1.ordinal()];
            if (newStyle2 != null) {
                // No fallback should take more than 2 steps.
                if (fallbackCache[newStyle2.ordinal()] != null) {
                    throw new IllegalStateException("Style fallback too deep");
                }
            }
        }
    }

    return new RelativeDateTimeFormatterData(
            sink.qualitativeUnitMap, sink.styleRelUnitPatterns,
            getDateTimePattern(r));
}
 
Example 2
Source File: MeasureFormat.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
/**
 * Returns formatting data for all MeasureUnits except for currency ones.
 */
private static MeasureFormatData loadLocaleData(ULocale locale) {
    ICUResourceBundle resource =
            (ICUResourceBundle)UResourceBundle.getBundleInstance(ICUData.ICU_UNIT_BASE_NAME, locale);
    MeasureFormatData cacheData = new MeasureFormatData();
    UnitDataSink sink = new UnitDataSink(cacheData);
    resource.getAllItemsWithFallback("", sink);
    return cacheData;
}
 
Example 3
Source File: MeasureUnit.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
/**
 * Populate the MeasureUnit cache with all types from the data.
 * Population is done lazily, in response to MeasureUnit.getAvailable()
 * or other API that expects to see all of the MeasureUnits.
 *
 * <p>At static initialization time the MeasureUnits cache is populated
 * with public static instances (G_FORCE, METER_PER_SECOND_SQUARED, etc.) only.
 * Adding of others is deferred until later to avoid circular static init
 * dependencies with classes Currency and TimeUnit.
 *
 * <p>Synchronization: this function must be called from static synchronized methods only.
 *
 * @internal
 */
static private void populateCache() {
    if (cacheIsPopulated) {
        return;
    }
    cacheIsPopulated = true;

    /*  Schema:
     *
     *  units{
     *    duration{
     *      day{
     *        one{"{0} ден"}
     *        other{"{0} дена"}
     *      }
     */

    // Load the unit types.  Use English, since we know that that is a superset.
    ICUResourceBundle rb1 = (ICUResourceBundle) UResourceBundle.getBundleInstance(
            ICUData.ICU_UNIT_BASE_NAME,
            "en");
    rb1.getAllItemsWithFallback("units", new MeasureUnitSink());

    // Load the currencies
    ICUResourceBundle rb2 = (ICUResourceBundle) UResourceBundle.getBundleInstance(
            ICUData.ICU_BASE_NAME,
            "currencyNumericCodes",
            ICUResourceBundle.ICU_DATA_CLASS_LOADER);
    rb2.getAllItemsWithFallback("codeMap", new CurrencyNumericCodeSink());
}
 
Example 4
Source File: DateIntervalInfo.java    From fitnotifications with Apache License 2.0 4 votes vote down vote up
private void setup(ULocale locale) {
    int DEFAULT_HASH_SIZE = 19;
    fIntervalPatterns = new HashMap<String, Map<String, PatternInfo>>(DEFAULT_HASH_SIZE);
    // initialize to guard if there is no interval date format defined in
    // resource files
    fFallbackIntervalPattern = "{0} \u2013 {1}";

    try {
        // Get the correct calendar type
        String calendarTypeToUse = locale.getKeywordValue("calendar");
        if ( calendarTypeToUse == null ) {
            String[] preferredCalendarTypes =
                    Calendar.getKeywordValuesForLocale("calendar", locale, true);
            calendarTypeToUse = preferredCalendarTypes[0]; // the most preferred calendar
        }
        if ( calendarTypeToUse == null ) {
            calendarTypeToUse = "gregorian"; // fallback
        }

        // Instantiate the sink to process the data and the resource bundle
        DateIntervalSink sink = new DateIntervalSink(this);
        ICUResourceBundle resource =
                (ICUResourceBundle)UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME, locale);

        // Get the fallback pattern
        String fallbackPattern = resource.getStringWithFallback(CALENDAR_KEY + "/" + calendarTypeToUse
                + "/" + INTERVAL_FORMATS_KEY + "/" + FALLBACK_STRING);
        setFallbackIntervalPattern(fallbackPattern);

        // Already loaded calendar types
        Set<String> loadedCalendarTypes = new HashSet<String>();

        while (calendarTypeToUse != null) {
            // Throw an exception when a loop is detected
            if (loadedCalendarTypes.contains(calendarTypeToUse)) {
                throw new ICUException("Loop in calendar type fallback: " + calendarTypeToUse);
            }

            // Register the calendar type to avoid loops
            loadedCalendarTypes.add(calendarTypeToUse);

            // Get all resources for this calendar type
            String pathToIntervalFormats = CALENDAR_KEY + "/" + calendarTypeToUse;
            resource.getAllItemsWithFallback(pathToIntervalFormats, sink);

            // Get next calendar type to load if there was an alias pointing at it
            calendarTypeToUse = sink.getAndResetNextCalendarType();
        }
    } catch ( MissingResourceException e) {
        // Will fallback to {data0} - {date1}
    }
}
 
Example 5
Source File: TimeUnitFormat.java    From fitnotifications with Apache License 2.0 4 votes vote down vote up
private void setup(String resourceKey, Map<TimeUnit, Map<String, Object[]>> timeUnitToCountToPatterns, int style,
        Set<String> pluralKeywords) {
    // fill timeUnitToCountToPatterns from resource file
    try {

        ICUResourceBundle resource = (ICUResourceBundle) UResourceBundle.getBundleInstance(
                ICUData.ICU_UNIT_BASE_NAME, locale);

        TimeUnitFormatSetupSink sink = new TimeUnitFormatSetupSink(
                timeUnitToCountToPatterns, style, pluralKeywords, locale);
        resource.getAllItemsWithFallback(resourceKey, sink);
    } catch (MissingResourceException e) {
    }
    // there should be patterns for each plural rule in each time unit.
    // For each time unit,
    // for each plural rule, following is unit pattern fall-back rule:
    // ( for example: "one" hour )
    // look for its unit pattern in its locale tree.
    // if pattern is not found in its own locale, such as de_DE,
    // look for the pattern in its parent, such as de,
    // keep looking till found or till root.
    // if the pattern is not found in root either,
    // fallback to plural count "other",
    // look for the pattern of "other" in the locale tree:
    // "de_DE" to "de" to "root".
    // If not found, fall back to value of
    // static variable DEFAULT_PATTERN_FOR_xxx, such as "{0} h".
    //
    // Following is consistency check to create pattern for each
    // plural rule in each time unit using above fall-back rule.
    //
    final TimeUnit[] timeUnits = TimeUnit.values();
    Set<String> keywords = pluralRules.getKeywords();
    for (int i = 0; i < timeUnits.length; ++i) {
        // for each time unit,
        // get all the patterns for each plural rule in this locale.
        final TimeUnit timeUnit = timeUnits[i];
        Map<String, Object[]> countToPatterns = timeUnitToCountToPatterns.get(timeUnit);
        if (countToPatterns == null) {
            countToPatterns = new TreeMap<String, Object[]>();
            timeUnitToCountToPatterns.put(timeUnit, countToPatterns);
        }
        for (String pluralCount : keywords) {
            if (countToPatterns.get(pluralCount) == null || countToPatterns.get(pluralCount)[style] == null) {
                // look through parents
                searchInTree(resourceKey, style, timeUnit, pluralCount, pluralCount, countToPatterns);
            }
        }
    }
}
 
Example 6
Source File: CompactDecimalDataCache.java    From fitnotifications with Apache License 2.0 4 votes vote down vote up
private static DataBundle load(ULocale ulocale) throws MissingResourceException {
    DataBundle dataBundle = DataBundle.createEmpty();
    String nsName = NumberingSystem.getInstance(ulocale).getName();
    ICUResourceBundle r = (ICUResourceBundle) UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME,
            ulocale);
    CompactDecimalDataSink sink = new CompactDecimalDataSink(dataBundle, ulocale);
    sink.isFallback = false;

    // First load the number elements data from nsName if nsName is not Latin.
    if (!nsName.equals(LATIN_NUMBERING_SYSTEM)) {
        sink.isLatin = false;

        try {
            r.getAllItemsWithFallback(NUMBER_ELEMENTS + "/" + nsName, sink);
        } catch (MissingResourceException e) {
            // Silently ignore and use Latin
        }

        // Set the "isFallback" flag for when we read Latin
        sink.isFallback = true;
    }

    // Now load Latin, which will fill in things that were left out from above.
    sink.isLatin = true;
    r.getAllItemsWithFallback(NUMBER_ELEMENTS + "/" + LATIN_NUMBERING_SYSTEM, sink);

    // If longData is empty, default it to be equal to shortData
    if (dataBundle.longData.isEmpty()) {
        dataBundle.longData = dataBundle.shortData;
    }

    // Check for "other" variants in each of the three data classes
    checkForOtherVariants(dataBundle.longData, ulocale, LONG_STYLE);
    checkForOtherVariants(dataBundle.shortData, ulocale, SHORT_STYLE);
    checkForOtherVariants(dataBundle.shortCurrencyData, ulocale, SHORT_CURRENCY_STYLE);

    // Resolve missing elements
    fillInMissing(dataBundle.longData);
    fillInMissing(dataBundle.shortData);
    fillInMissing(dataBundle.shortCurrencyData);

    // Return the data bundle
    return dataBundle;
}
 
Example 7
Source File: DecimalFormatSymbols.java    From fitnotifications with Apache License 2.0 4 votes vote down vote up
private static CacheData loadData(ULocale locale) {
    String nsName;
    // Attempt to set the decimal digits based on the numbering system for the requested locale.
    NumberingSystem ns = NumberingSystem.getInstance(locale);
    String[] digits = new String[10];
    if (ns != null && ns.getRadix() == 10 && !ns.isAlgorithmic() &&
            NumberingSystem.isValidDigitString(ns.getDescription())) {
        String digitString = ns.getDescription();

        for (int i = 0, offset = 0; i < 10; i++) {
            int cp = digitString.codePointAt(offset);
            int nextOffset = offset + Character.charCount(cp);
            digits[i] = digitString.substring(offset, nextOffset);
            offset = nextOffset;
        }
        nsName = ns.getName();
    } else {
        // Default numbering system
        digits = DEF_DIGIT_STRINGS_ARRAY;
        nsName = "latn";
    }

    // Open the resource bundle and get the locale IDs.
    // TODO: Is there a better way to get the locale than making an ICUResourceBundle instance?
    ICUResourceBundle rb = (ICUResourceBundle)UResourceBundle.
            getBundleInstance(ICUData.ICU_BASE_NAME, locale);
    // TODO: Determine actual and valid locale correctly.
    ULocale validLocale = rb.getULocale();

    String[] numberElements = new String[SYMBOL_KEYS.length];

    // Load using a data sink
    DecFmtDataSink sink = new DecFmtDataSink(numberElements);
    try {
        rb.getAllItemsWithFallback(NUMBER_ELEMENTS + "/" + nsName + "/" + SYMBOLS, sink);
    } catch (MissingResourceException e) {
        // The symbols don't exist for the given nsName and resource bundle.
        // Silently ignore and fall back to Latin.
    }

    // Load the Latin fallback if necessary
    boolean hasNull = false;
    for (String entry : numberElements) {
        if (entry == null) {
            hasNull = true;
            break;
        }
    }
    if (hasNull && !nsName.equals(LATIN_NUMBERING_SYSTEM)) {
        rb.getAllItemsWithFallback(NUMBER_ELEMENTS + "/" + LATIN_NUMBERING_SYSTEM + "/" + SYMBOLS, sink);
    }

    // Fill in any remaining missing values
    for (int i = 0; i < SYMBOL_KEYS.length; i++) {
        if (numberElements[i] == null) {
            numberElements[i] = SYMBOL_DEFAULTS[i];
        }
    }

    // If monetary decimal or grouping were not explicitly set, then set them to be the same as
    // their non-monetary counterparts.
    if (numberElements[10] == null) {
        numberElements[10] = numberElements[0];
    }
    if (numberElements[11] == null) {
        numberElements[11] = numberElements[1];
    }

    return new CacheData(validLocale, digits, numberElements);
}
 
Example 8
Source File: Collator.java    From fitnotifications with Apache License 2.0 3 votes vote down vote up
/**
 * {@icu} Given a key and a locale, returns an array of string values in a preferred
 * order that would make a difference. These are all and only those values where
 * the open (creation) of the service with the locale formed from the input locale
 * plus input keyword and that value has different behavior than creation with the
 * input locale alone.
 * @param key           one of the keys supported by this service.  For now, only
 *                      "collation" is supported.
 * @param locale        the locale
 * @param commonlyUsed  if set to true it will return only commonly used values
 *                      with the given locale in preferred order.  Otherwise,
 *                      it will return all the available values for the locale.
 * @return an array of string values for the given key and the locale.
 * @stable ICU 4.2
 */
public static final String[] getKeywordValuesForLocale(String key, ULocale locale,
                                                       boolean commonlyUsed) {
    // Note: The parameter commonlyUsed is not used.
    // The switch is in the method signature for consistency
    // with other locale services.

    // Read available collation values from collation bundles.
    ICUResourceBundle bundle = (ICUResourceBundle)
            UResourceBundle.getBundleInstance(
                    ICUData.ICU_COLLATION_BASE_NAME, locale);
    KeywordsSink sink = new KeywordsSink();
    bundle.getAllItemsWithFallback("collations", sink);
    return sink.values.toArray(new String[sink.values.size()]);
}