Java Code Examples for com.ibm.icu.util.UResourceBundle#getBundleInstance()

The following examples show how to use com.ibm.icu.util.UResourceBundle#getBundleInstance() . 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: NumberingSystem.java    From fitnotifications with Apache License 2.0 6 votes vote down vote up
private static NumberingSystem lookupInstanceByName(String name) {
    int radix;
    boolean isAlgorithmic;
    String description;
    try {
        UResourceBundle numberingSystemsInfo = UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME, "numberingSystems");
        UResourceBundle nsCurrent = numberingSystemsInfo.get("numberingSystems");
        UResourceBundle nsTop = nsCurrent.get(name);

        description = nsTop.getString("desc");
        UResourceBundle nsRadixBundle = nsTop.get("radix");
        UResourceBundle nsAlgBundle = nsTop.get("algorithmic");
        radix = nsRadixBundle.getInt();
        int algorithmic = nsAlgBundle.getInt();

        isAlgorithmic = ( algorithmic == 1 );

    } catch (MissingResourceException ex) {
        return null;
    }

    return getInstance(name, radix, isAlgorithmic, description);
}
 
Example 2
Source File: NumberingSystem.java    From fitnotifications with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a string array containing a list of the names of numbering systems
 * currently known to ICU.
 * @stable ICU 4.2
 */
public static String [] getAvailableNames() {

        UResourceBundle numberingSystemsInfo = UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME, "numberingSystems");
        UResourceBundle nsCurrent = numberingSystemsInfo.get("numberingSystems");
        UResourceBundle temp;

        String nsName;
        ArrayList<String> output = new ArrayList<String>();
        UResourceBundleIterator it = nsCurrent.getIterator();
        while (it.hasNext()) {
            temp = it.next();
            nsName = temp.getKey();
            output.add(nsName);
        }
        return output.toArray(new String[output.size()]);
}
 
Example 3
Source File: ICUCurrencyDisplayInfoProvider.java    From fitnotifications with Apache License 2.0 6 votes vote down vote up
private Map<String, String> _createSymbolMap() {
    Map<String, String> result = new HashMap<String, String>();

    for (ULocale locale = rb.getULocale(); locale != null; locale = locale.getFallback()) {
        ICUResourceBundle bundle = (ICUResourceBundle)
            UResourceBundle.getBundleInstance(ICUData.ICU_CURR_BASE_NAME, locale);
        ICUResourceBundle curr = bundle.findTopLevel("Currencies");
        if (curr == null) {
            continue;
        }
        for (int i = 0; i < curr.getSize(); ++i) {
            ICUResourceBundle item = curr.at(i);
            String isoCode = item.getKey();
            if (!result.containsKey(isoCode)) {
                // put the code itself
                result.put(isoCode, isoCode);
                // 0 == symbol element
                String symbol = item.getString(0);
                result.put(symbol, isoCode);
            }
        }
    }

    return Collections.unmodifiableMap(result);
}
 
Example 4
Source File: MeasureFormat.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
private static NumericFormatters loadNumericFormatters(
        ULocale locale) {
    ICUResourceBundle r = (ICUResourceBundle)UResourceBundle.
            getBundleInstance(ICUData.ICU_UNIT_BASE_NAME, locale);
    return new NumericFormatters(
            loadNumericDurationFormat(r, "hm"),
            loadNumericDurationFormat(r, "ms"),
            loadNumericDurationFormat(r, "hms"));
}
 
Example 5
Source File: TimeZoneNamesImpl.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
@Override
protected List<MZMapEntry> createInstance(String key, String data) {
    List<MZMapEntry> mzMaps = null;

    UResourceBundle bundle = UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME, "metaZones");
    UResourceBundle metazoneInfoBundle = bundle.get("metazoneInfo");

    String tzkey = data.replace('/', ':');
    try {
        UResourceBundle zoneBundle = metazoneInfoBundle.get(tzkey);

        mzMaps = new ArrayList<MZMapEntry>(zoneBundle.getSize());
        for (int idx = 0; idx < zoneBundle.getSize(); idx++) {
            UResourceBundle mz = zoneBundle.get(idx);
            String mzid = mz.getString(0);
            String fromStr = "1970-01-01 00:00";
            String toStr = "9999-12-31 23:59";
            if (mz.getSize() == 3) {
                fromStr = mz.getString(1);
                toStr = mz.getString(2);
            }
            long from, to;
            from = parseDate(fromStr);
            to = parseDate(toStr);
            mzMaps.add(new MZMapEntry(mzid, from, to));
        }

    } catch (MissingResourceException mre) {
        mzMaps = Collections.emptyList();
    }
    return mzMaps;
}
 
Example 6
Source File: CollationLoader.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
private static void loadRootRules() {
    if (rootRules != null) {
        return;
    }
    synchronized(CollationLoader.class) {
        if (rootRules == null) {
            UResourceBundle rootBundle = UResourceBundle.getBundleInstance(
                    ICUData.ICU_COLLATION_BASE_NAME, ULocale.ROOT);
            rootRules = rootBundle.getString("UCARules");
        }
    }
}
 
Example 7
Source File: ZoneMeta.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
private static synchronized String[] getZoneIDs() {
    if (ZONEIDS == null) {
        try {
            UResourceBundle top = UResourceBundle.getBundleInstance(
                    ICUData.ICU_BASE_NAME, ZONEINFORESNAME, ICUResourceBundle.ICU_DATA_CLASS_LOADER);
            ZONEIDS = top.getStringArray(kNAMES);
        } catch (MissingResourceException ex) {
            // throw away..
        }
    }
    if (ZONEIDS == null) {
        ZONEIDS = new String[0];
    }
    return ZONEIDS;
}
 
Example 8
Source File: ListFormatter.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
private static ListFormatter load(ULocale ulocale, String style) {
    ICUResourceBundle r = (ICUResourceBundle)UResourceBundle.
            getBundleInstance(ICUData.ICU_BASE_NAME, ulocale);
    StringBuilder sb = new StringBuilder();
    return new ListFormatter(
        compilePattern(r.getWithFallback("listPattern/" + style + "/2").getString(), sb),
        compilePattern(r.getWithFallback("listPattern/" + style + "/start").getString(), sb),
        compilePattern(r.getWithFallback("listPattern/" + style + "/middle").getString(), sb),
        compilePattern(r.getWithFallback("listPattern/" + style + "/end").getString(), sb),
        ulocale);
}
 
Example 9
Source File: DateIntervalFormat.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the concatenation DateTime pattern from the resource bundle.
 * @param locale Locale to retrieve.
 * @return Concatenation DateTime pattern.
 */
private String getConcatenationPattern(ULocale locale) {
    ICUResourceBundle rb = (ICUResourceBundle) UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME, locale);
    ICUResourceBundle dtPatternsRb = rb.getWithFallback("calendar/gregorian/DateTimePatterns");
    ICUResourceBundle concatenationPatternRb = (ICUResourceBundle) dtPatternsRb.get(8);
    if (concatenationPatternRb.getType() == UResourceBundle.STRING) {
        return concatenationPatternRb.getString();
    } else {
        return concatenationPatternRb.getString(0);
    }
}
 
Example 10
Source File: ICUResourceTableAccess.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Utility to fetch locale display data from resource bundle tables.  Convenience
 * wrapper for {@link #getTableString(ICUResourceBundle, String, String, String, String)}.
 */
public static String getTableString(String path, ULocale locale, String tableName,
        String itemName, String defaultValue) {
    ICUResourceBundle bundle = (ICUResourceBundle) UResourceBundle.
        getBundleInstance(path, locale.getBaseName());
    return getTableString(bundle, tableName, null, itemName, defaultValue);
}
 
Example 11
Source File: RelativeDateFormat.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
/**
 * Load the Date string array
 */
private synchronized void loadDates() {
    ICUResourceBundle rb = (ICUResourceBundle) UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME, fLocale);

    // Use sink mechanism to traverse data structure.
    fDates = new ArrayList<URelativeString>();
    RelDateFmtDataSink sink = new RelDateFmtDataSink();
    rb.getAllItemsWithFallback("fields/day/relative", sink);
}
 
Example 12
Source File: ICUResourceBundle.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
/**
 * Given a tree path and keyword, return a string enumeration of all possible values for that keyword.
 * @param baseName resource specifier
 * @param keyword a particular keyword to consider, must match a top level resource name
 * within the tree. (i.e. "collations")
 * @internal ICU 3.0
 */
public static final String[] getKeywordValues(String baseName, String keyword) {
    Set<String> keywords = new HashSet<String>();
    ULocale locales[] = getAvailEntry(baseName, ICU_DATA_CLASS_LOADER).getULocaleList();
    int i;

    for (i = 0; i < locales.length; i++) {
        try {
            UResourceBundle b = UResourceBundle.getBundleInstance(baseName, locales[i]);
            // downcast to ICUResourceBundle?
            ICUResourceBundle irb = (ICUResourceBundle) (b.getObject(keyword));
            Enumeration<String> e = irb.getKeys();
            while (e.hasMoreElements()) {
                String s = e.nextElement();
                if (!DEFAULT_TAG.equals(s) && !s.startsWith("private-")) {
                    // don't add 'default' items, nor unlisted types
                    keywords.add(s);
                }
            }
        } catch (Throwable t) {
            //System.err.println("Error in - " + new Integer(i).toString()
            // + " - " + t.toString());
            // ignore the err - just skip that resource
        }
    }
    return keywords.toArray(new String[0]);
}
 
Example 13
Source File: MeasureFormat.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
/**
 * Return a formatter (compiled SimpleFormatter pattern) for a range, such as "{0}–{1}".
 * @param forLocale locale to get the format for
 * @param width the format width
 * @return range formatter, such as "{0}–{1}"
 * @internal
 * @deprecated This API is ICU internal only.
 */
@Deprecated
public static String getRangeFormat(ULocale forLocale, FormatWidth width) {
    // TODO fix Hack for French
    if (forLocale.getLanguage().equals("fr")) {
        return getRangeFormat(ULocale.ROOT, width);
    }
    String result = localeIdToRangeFormat.get(forLocale);
    if (result == null) {
        ICUResourceBundle rb = (ICUResourceBundle)UResourceBundle.
                getBundleInstance(ICUData.ICU_BASE_NAME, forLocale);
        ULocale realLocale = rb.getULocale();
        if (!forLocale.equals(realLocale)) { // if the child would inherit, then add a cache entry for it.
            result = localeIdToRangeFormat.get(forLocale);
            if (result != null) {
                localeIdToRangeFormat.put(forLocale, result);
                return result;
            }
        }
        // At this point, both the forLocale and the realLocale don't have an item
        // So we have to make one.
        NumberingSystem ns = NumberingSystem.getInstance(forLocale);

        String resultString = null;
        try {
            resultString = rb.getStringWithFallback("NumberElements/" + ns.getName() + "/miscPatterns/range");
        } catch ( MissingResourceException ex ) {
            resultString = rb.getStringWithFallback("NumberElements/latn/patterns/range");
        }
        result = SimpleFormatterImpl.compileToStringMinMaxArguments(
                resultString, new StringBuilder(), 2, 2);
        localeIdToRangeFormat.put(forLocale, result);
        if (!forLocale.equals(realLocale)) {
            localeIdToRangeFormat.put(realLocale, result);
        }
    }
    return result;
}
 
Example 14
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 15
Source File: OlsonTimeZone.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
    stream.defaultReadObject();

    if (serialVersionOnStream < 1) {
        // No version - 4.2 or older
        // Just reloading the rule from bundle
        boolean initialized = false;
        String tzid = getID();
        if (tzid != null) {
            try {
                UResourceBundle top = UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME,
                        ZONEINFORES, ICUResourceBundle.ICU_DATA_CLASS_LOADER);
                UResourceBundle res = ZoneMeta.openOlsonResource(top, tzid);
                construct(top, res);
                if (finalZone != null){
                    finalZone.setID(tzid);
                }
                initialized = true;
            } catch (Exception ignored) {
                // throw away
            }
        }
        if (!initialized) {
            // final resort
            constructEmpty();
        }
    }

    // need to rebuild transition rules when requested
    transitionRulesInitialized = false;
}
 
Example 16
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 17
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 18
Source File: ICUResourceTableAccess.java    From fitnotifications with Apache License 2.0 4 votes vote down vote up
/**
 * Utility to fetch locale display data from resource bundle tables.  Uses fallback
 * through the "Fallback" resource if available.
 */
public static String getTableString(ICUResourceBundle bundle, String tableName,
        String subtableName, String item, String defaultValue) {
    String result = null;
    try {
        for (;;) {
            ICUResourceBundle table = bundle.findWithFallback(tableName);
            if (table == null) {
                return defaultValue;
            }
            ICUResourceBundle stable = table;
            if (subtableName != null) {
                stable = table.findWithFallback(subtableName);
            }
            if (stable != null) {
                result = stable.findStringWithFallback(item);
                if (result != null) {
                    break; // possible real exception
                }
            }

            // if we get here, stable was null, or there was no string for the item
            if (subtableName == null) {
                // may be a deprecated code
                String currentName = null;
                if (tableName.equals("Countries")) {
                    currentName = LocaleIDs.getCurrentCountryID(item);
                } else if (tableName.equals("Languages")) {
                    currentName = LocaleIDs.getCurrentLanguageID(item);
                }
                if (currentName != null) {
                    result = table.findStringWithFallback(currentName);
                    if (result != null) {
                        break; // possible real exception
                    }
                }
            }

            // still can't figure it out? try the fallback mechanism
            String fallbackLocale = table.findStringWithFallback("Fallback"); // again, possible exception
            if (fallbackLocale == null) {
                return defaultValue;
            }

            if (fallbackLocale.length() == 0) {
                fallbackLocale = "root";
            }

            if (fallbackLocale.equals(table.getULocale().getName())) {
                return defaultValue;
            }

            bundle = (ICUResourceBundle) UResourceBundle.getBundleInstance(
                    bundle.getBaseName(), fallbackLocale);
        }
    } catch (Exception e) {
        // If something is seriously wrong, we might call getString on a resource that is
        // not a string.  That will throw an exception, which we catch and ignore here.
    }

    // If the result is empty return item instead
    return ((result != null && result.length() > 0) ? result : defaultValue);
}
 
Example 19
Source File: Messages.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resource bundle which is most match to specified locale.
 * <p>
 * As expected, if specified locale hasn't defined valid resource file, we
 * want to load English(default) resource file instead of the resource file
 * of default locale.
 * 
 * @param locale
 *            specified locale.
 * @param baseName
 *            the path of resource.
 * @param clazz
 *            the class whose class loader will be used by loading resource
 *            bundle.
 * @return instance of resource bundle.
 */
@SuppressWarnings("rawtypes")
private static ResourceBundle getMatchedResourceBundle( ULocale locale,
		String baseName, Class clazz )
{
	ResourceBundle bundle;
	bundle = UResourceBundle.getBundleInstance( baseName,
			locale,
			SecurityUtil.getClassLoader( clazz ) );

	if ( bundle != null )
	{
		// Bundle could be in default locale instead of English
		// if resource for the locale cannot be found.
		String language = locale.getLanguage( );
		String country = locale.getCountry( );
		boolean useDefaultResource = true;
		if ( language.length( ) == 0 && country.length( ) == 0 )
		{
			// it is definitely the match, no need to get the
			// default resource file again.
			useDefaultResource = false;
		}
		else
		{
			Locale bundleLocale = bundle.getLocale( );
			if ( bundleLocale.getLanguage( ).length( ) == 0
					&& bundleLocale.getCountry( ).length( ) == 0 )
			{
				// it is the match, no need to get the default
				// resource file again.
				useDefaultResource = false;
			}
			else if ( language.equals( bundleLocale.getLanguage( ) ) )
			{
				// Language matched
				String bundleCountry = bundleLocale.getCountry( );
				if ( country.equals( bundleCountry )
						|| bundleCountry.length( ) == 0 )
				{
					// Country matched or Bundle has no Country
					// specified.
					useDefaultResource = false;
				}
			}
		}
		if ( useDefaultResource )
		{
			bundle = ResourceBundle.getBundle( baseName,
					new Locale( "", "" ) ); //$NON-NLS-1$ //$NON-NLS-2$
		}
	}
	return bundle;
}
 
Example 20
Source File: CalendarData.java    From fitnotifications with Apache License 2.0 2 votes vote down vote up
/**
 * Construct a CalendarData from the given locale.
 * @param loc locale to use. The 'calendar' keyword will be ignored.
 * @param type calendar type. NULL indicates the gregorian calendar. 
 * No default lookup is done.
 */
public CalendarData(ULocale loc, String type) {
    this((ICUResourceBundle)UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME, loc), type);
}