sun.util.resources.LocaleData Java Examples

The following examples show how to use sun.util.resources.LocaleData. 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: DecimalFormat.java    From jdk-1.7-annotated with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a DecimalFormat using the default pattern and symbols
 * for the default locale. This is a convenient way to obtain a
 * DecimalFormat when internationalization is not the main concern.
 * <p>
 * To obtain standard formats for a given locale, use the factory methods
 * on NumberFormat such as getNumberInstance. These factories will
 * return the most appropriate sub-class of NumberFormat for a given
 * locale.
 *
 * @see java.text.NumberFormat#getInstance
 * @see java.text.NumberFormat#getNumberInstance
 * @see java.text.NumberFormat#getCurrencyInstance
 * @see java.text.NumberFormat#getPercentInstance
 */
public DecimalFormat() {
    Locale def = Locale.getDefault(Locale.Category.FORMAT);
    // try to get the pattern from the cache
    String pattern = cachedLocaleData.get(def);
    if (pattern == null) {  /* cache miss */
        // Get the pattern for the default locale.
        ResourceBundle rb = LocaleData.getNumberFormatData(def);
        String[] all = rb.getStringArray("NumberPatterns");
        pattern = all[0];
        /* update cache */
        cachedLocaleData.putIfAbsent(def, pattern);
    }

    // Always applyPattern after the symbols are set
    this.symbols = new DecimalFormatSymbols(def);
    applyPattern(pattern, false);
}
 
Example #2
Source File: Locale.java    From jdk-1.7-annotated with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a name for the locale's variant code that is appropriate for display to the
 * user.  If possible, the name will be localized for inLocale.  If the locale
 * doesn't specify a variant code, this function returns the empty string.
 *
 * @exception NullPointerException if <code>inLocale</code> is <code>null</code>
 */
public String getDisplayVariant(Locale inLocale) {
    if (baseLocale.getVariant().length() == 0)
        return "";

    OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);

    String names[] = getDisplayVariantArray(bundle, inLocale);

    // Get the localized patterns for formatting a list, and use
    // them to format the list.
    String listPattern = null;
    String listCompositionPattern = null;
    try {
        listPattern = bundle.getString("ListPattern");
        listCompositionPattern = bundle.getString("ListCompositionPattern");
    } catch (MissingResourceException e) {
    }
    return formatList(names, listPattern, listCompositionPattern);
}
 
Example #3
Source File: Currency.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the name that is suitable for displaying this currency for
 * the specified locale.  If there is no suitable display name found
 * for the specified locale, the ISO 4217 currency code is returned.
 *
 * @param locale the locale for which a display name for this currency is
 * needed
 * @return the display name of this currency for the specified locale
 * @exception NullPointerException if <code>locale</code> is null
 * @since 1.7
 */
public String getDisplayName(Locale locale) {
    try {
        OpenListResourceBundle bundle = LocaleData.getCurrencyNames(locale);
        String result = null;
        String bundleKey = currencyCode.toLowerCase(Locale.ROOT);

        // Check whether a provider can provide an implementation that's closer
        // to the requested locale than what the Java runtime itself can provide.
        LocaleServiceProviderPool pool =
            LocaleServiceProviderPool.getPool(CurrencyNameProvider.class);
        if (pool.hasProviders()) {
            result = pool.getLocalizedObject(
                                CurrencyNameGetter.INSTANCE,
                                locale, bundleKey, bundle, currencyCode, DISPLAYNAME);
        }

        if (result == null) {
            result = bundle.getString(bundleKey);
        }

        if (result != null) {
            return result;
        }
    } catch (MissingResourceException e) {
        // fall through
    }

    // use currency code as symbol of last resort
    return currencyCode;
}
 
Example #4
Source File: NumberFormat.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
private static NumberFormat getInstance(Locale desiredLocale,
                                       int choice) {
    // Check whether a provider can provide an implementation that's closer
    // to the requested locale than what the Java runtime itself can provide.
    LocaleServiceProviderPool pool =
        LocaleServiceProviderPool.getPool(NumberFormatProvider.class);
    if (pool.hasProviders()) {
        NumberFormat providersInstance = pool.getLocalizedObject(
                                NumberFormatGetter.INSTANCE,
                                desiredLocale,
                                choice);
        if (providersInstance != null) {
            return providersInstance;
        }
    }

    /* try the cache first */
    String[] numberPatterns = (String[])cachedLocaleData.get(desiredLocale);
    if (numberPatterns == null) { /* cache miss */
        ResourceBundle resource = LocaleData.getNumberFormatData(desiredLocale);
        numberPatterns = resource.getStringArray("NumberPatterns");
        /* update cache */
        cachedLocaleData.put(desiredLocale, numberPatterns);
    }

    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(desiredLocale);
    int entry = (choice == INTEGERSTYLE) ? NUMBERSTYLE : choice;
    DecimalFormat format = new DecimalFormat(numberPatterns[entry], symbols);

    if (choice == INTEGERSTYLE) {
        format.setMaximumFractionDigits(0);
        format.setDecimalSeparatorAlwaysShown(false);
        format.setParseIntegerOnly(true);
    } else if (choice == CURRENCYSTYLE) {
        format.adjustForCurrencyDefaultFractionDigits();
    }

    return format;
}
 
Example #5
Source File: DateFormatSymbols.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
private void initializeData(Locale desiredLocale) {
    locale = desiredLocale;

    // Copy values of a cached instance if any.
    SoftReference<DateFormatSymbols> ref = cachedInstances.get(locale);
    DateFormatSymbols dfs;
    if (ref != null && (dfs = ref.get()) != null) {
        copyMembers(dfs, this);
        return;
    }

    // Initialize the fields from the ResourceBundle for locale.
    ResourceBundle resource = LocaleData.getDateFormatData(locale);

    eras = resource.getStringArray("Eras");
    months = resource.getStringArray("MonthNames");
    shortMonths = resource.getStringArray("MonthAbbreviations");
    ampms = resource.getStringArray("AmPmMarkers");
    localPatternChars = resource.getString("DateTimePatternChars");

    // Day of week names are stored in a 1-based array.
    weekdays = toOneBasedArray(resource.getStringArray("DayNames"));
    shortWeekdays = toOneBasedArray(resource.getStringArray("DayAbbreviations"));
}
 
Example #6
Source File: Locale.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
private String getDisplayString(String code, Locale inLocale, int type) {
    if (code.length() == 0) {
        return "";
    }

    if (inLocale == null) {
        throw new NullPointerException();
    }

    try {
        OpenListResourceBundle bundle = LocaleData.getLocaleNames(inLocale);
        String key = (type == DISPLAY_VARIANT ? "%%"+code : code);
        String result = null;

        // Check whether a provider can provide an implementation that's closer
        // to the requested locale than what the Java runtime itself can provide.
        LocaleServiceProviderPool pool =
            LocaleServiceProviderPool.getPool(LocaleNameProvider.class);
        if (pool.hasProviders()) {
            result = pool.getLocalizedObject(
                                LocaleNameGetter.INSTANCE,
                                inLocale, bundle, key,
                                type, code);
        }

        if (result == null) {
            result = bundle.getString(key);
        }

        if (result != null) {
            return result;
        }
    }
    catch (Exception e) {
        // just fall through
    }
    return code;
}
 
Example #7
Source File: Currency.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the symbol of this currency for the specified locale.
 * For example, for the US Dollar, the symbol is "$" if the specified
 * locale is the US, while for other locales it may be "US$". If no
 * symbol can be determined, the ISO 4217 currency code is returned.
 *
 * @param locale the locale for which a display name for this currency is
 * needed
 * @return the symbol of this currency for the specified locale
 * @exception NullPointerException if <code>locale</code> is null
 */
public String getSymbol(Locale locale) {
    try {
        // Check whether a provider can provide an implementation that's closer
        // to the requested locale than what the Java runtime itself can provide.
        LocaleServiceProviderPool pool =
            LocaleServiceProviderPool.getPool(CurrencyNameProvider.class);

        if (pool.hasProviders()) {
            // Assuming that all the country locales include necessary currency
            // symbols in the Java runtime's resources,  so there is no need to
            // examine whether Java runtime's currency resource bundle is missing
            // names.  Therefore, no resource bundle is provided for calling this
            // method.
            String symbol = pool.getLocalizedObject(
                                CurrencyNameGetter.INSTANCE,
                                locale, (OpenListResourceBundle)null,
                                currencyCode, SYMBOL);
            if (symbol != null) {
                return symbol;
            }
        }

        ResourceBundle bundle = LocaleData.getCurrencyNames(locale);
        return bundle.getString(currencyCode);
    } catch (MissingResourceException e) {
        // use currency code as symbol of last resort
        return currencyCode;
    }
}
 
Example #8
Source File: Calendar.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
/**
 * Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.
 * They are used to figure out the week count for a specific date for
 * a given locale. These must be set when a Calendar is constructed.
 * @param desiredLocale the given locale.
 */
private void setWeekCountData(Locale desiredLocale)
{
    /* try to get the Locale data from the cache */
    int[] data = cachedLocaleData.get(desiredLocale);
    if (data == null) {  /* cache miss */
        ResourceBundle bundle = LocaleData.getCalendarData(desiredLocale);
        data = new int[2];
        data[0] = Integer.parseInt(bundle.getString("firstDayOfWeek"));
        data[1] = Integer.parseInt(bundle.getString("minimalDaysInFirstWeek"));
        cachedLocaleData.putIfAbsent(desiredLocale, data);
    }
    firstDayOfWeek = data[0];
    minimalDaysInFirstWeek = data[1];
}
 
Example #9
Source File: JapaneseImperialCalendar.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
public String getDisplayName(int field, int style, Locale locale) {
    if (!checkDisplayNameParams(field, style, SHORT, LONG, locale,
                                ERA_MASK|YEAR_MASK|MONTH_MASK|DAY_OF_WEEK_MASK|AM_PM_MASK)) {
        return null;
    }

    // "GanNen" is supported only in the LONG style.
    if (field == YEAR
        && (style == SHORT || get(YEAR) != 1 || get(ERA) == 0)) {
        return null;
    }

    ResourceBundle rb = LocaleData.getDateFormatData(locale);
    String name = null;
    String key = getKey(field, style);
    if (key != null) {
        String[] strings = rb.getStringArray(key);
        if (field == YEAR) {
            if (strings.length > 0) {
                name = strings[0];
            }
        } else {
            int index = get(field);
            // If the ERA value is out of range for strings, then
            // try to get its name or abbreviation from the Era instance.
            if (field == ERA && index >= strings.length && index < eras.length) {
                Era era = eras[index];
                name = (style == SHORT) ? era.getAbbreviation() : era.getName();
            } else {
                if (field == DAY_OF_WEEK)
                    --index;
                name = strings[index];
            }
        }
    }
    return name;
}
 
Example #10
Source File: JapaneseImperialCalendar.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
private Map<String,Integer> getDisplayNamesImpl(int field, int style, Locale locale) {
    ResourceBundle rb = LocaleData.getDateFormatData(locale);
    String key = getKey(field, style);
    Map<String,Integer> map = new HashMap<String,Integer>();
    if (key != null) {
        String[] strings = rb.getStringArray(key);
        if (field == YEAR) {
            if (strings.length > 0) {
                map.put(strings[0], 1);
            }
        } else {
            int base = (field == DAY_OF_WEEK) ? 1 : 0;
            for (int i = 0; i < strings.length; i++) {
                map.put(strings[i], base + i);
            }
            // If strings[] has fewer than eras[], get more names from eras[].
            if (field == ERA && strings.length < eras.length) {
                for (int i = strings.length; i < eras.length; i++) {
                    Era era = eras[i];
                    String name = (style == SHORT) ? era.getAbbreviation() : era.getName();
                    map.put(name, i);
                }
            }
        }
    }
    return map.size() > 0 ? map : null;
}
 
Example #11
Source File: NumberTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Bug 4122840
 * Make sure that the currency symbol is not hard-coded in any locale.
 */
public void TestCurrencySubstitution() {
    final String SYM = "<currency>";
    final String INTL_SYM = "<intl.currency>";
    Locale[] locales = NumberFormat.getAvailableLocales();
    for (int i=0; i<locales.length; ++i) {
        NumberFormat nf = NumberFormat.getCurrencyInstance(locales[i]);
        if (nf instanceof DecimalFormat) {
            DecimalFormat df = (DecimalFormat)nf;
            String genericPos = df.format(1234.5678);
            String genericNeg = df.format(-1234.5678);
            DecimalFormatSymbols sym = df.getDecimalFormatSymbols();
            sym.setCurrencySymbol(SYM);
            sym.setInternationalCurrencySymbol(INTL_SYM);
            // We have to make a new DecimalFormat from scratch in order
            // to make the new symbols 'take'.  This may be a bug or
            // design flaw in DecimalFormat.
            String[] patterns = LocaleData.getBundle("sun.text.resources.FormatData", locales[i])
                                          .getStringArray("NumberPatterns");
            df = new DecimalFormat(patterns[1 /*CURRENCYSTYLE*/], sym);
            String customPos = df.format(1234.5678);
            String customNeg = df.format(-1234.5678);
            if (genericPos.equals(customPos) || genericNeg.equals(customNeg)) {
                errln("FAIL: " + locales[i] +
                      " not using currency symbol substitution: " + genericPos);
            }
            else {
                if (customPos.indexOf(SYM) >= 0) {
                    if (customNeg.indexOf(INTL_SYM) >= 0)
                        errln("Fail: Positive and negative patterns use different symbols");
                    else
                        logln("Ok: " + locales[i] +
                              " uses currency symbol: " + genericPos +
                              ", " + customPos);
                }
                else if (customPos.indexOf(INTL_SYM) >= 0) {
                    if (customNeg.indexOf(SYM) >= 0)
                        errln("Fail: Positive and negative patterns use different symbols");
                    else
                        logln("Ok: " + locales[i] +
                              " uses intl. currency symbol: " + genericPos +
                              ", " + customPos);
                }
                else {
                    errln("FAIL: " + locales[i] +
                          " contains no currency symbol (impossible!)");
                }
            }
        }
        else logln("Skipping " + locales[i] + "; not a DecimalFormat");
    }
}
 
Example #12
Source File: NumberTest.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Bug 4122840
 * Make sure that the currency symbol is not hard-coded in any locale.
 */
public void TestCurrencySubstitution() {
    final String SYM = "<currency>";
    final String INTL_SYM = "<intl.currency>";
    Locale[] locales = NumberFormat.getAvailableLocales();
    for (int i=0; i<locales.length; ++i) {
        NumberFormat nf = NumberFormat.getCurrencyInstance(locales[i]);
        if (nf instanceof DecimalFormat) {
            DecimalFormat df = (DecimalFormat)nf;
            String genericPos = df.format(1234.5678);
            String genericNeg = df.format(-1234.5678);
            DecimalFormatSymbols sym = df.getDecimalFormatSymbols();
            sym.setCurrencySymbol(SYM);
            sym.setInternationalCurrencySymbol(INTL_SYM);
            // We have to make a new DecimalFormat from scratch in order
            // to make the new symbols 'take'.  This may be a bug or
            // design flaw in DecimalFormat.
            String[] patterns = LocaleData.getBundle("sun.text.resources.FormatData", locales[i])
                                          .getStringArray("NumberPatterns");
            df = new DecimalFormat(patterns[1 /*CURRENCYSTYLE*/], sym);
            String customPos = df.format(1234.5678);
            String customNeg = df.format(-1234.5678);
            if (genericPos.equals(customPos) || genericNeg.equals(customNeg)) {
                errln("FAIL: " + locales[i] +
                      " not using currency symbol substitution: " + genericPos);
            }
            else {
                if (customPos.indexOf(SYM) >= 0) {
                    if (customNeg.indexOf(INTL_SYM) >= 0)
                        errln("Fail: Positive and negative patterns use different symbols");
                    else
                        logln("Ok: " + locales[i] +
                              " uses currency symbol: " + genericPos +
                              ", " + customPos);
                }
                else if (customPos.indexOf(INTL_SYM) >= 0) {
                    if (customNeg.indexOf(SYM) >= 0)
                        errln("Fail: Positive and negative patterns use different symbols");
                    else
                        logln("Ok: " + locales[i] +
                              " uses intl. currency symbol: " + genericPos +
                              ", " + customPos);
                }
                else {
                    errln("FAIL: " + locales[i] +
                          " contains no currency symbol (impossible!)");
                }
            }
        }
        else logln("Skipping " + locales[i] + "; not a DecimalFormat");
    }
}
 
Example #13
Source File: NumberRegression.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Locale data should use generic currency symbol
 *
 * 1) Make sure that all currency formats use the generic currency symbol.
 * 2) Make sure we get the same results using the generic symbol or a
 *    hard-coded one.
 */
public void Test4122840()
{
    Locale[] locales = NumberFormat.getAvailableLocales();

    for (int i = 0; i < locales.length; i++) {
        ResourceBundle rb = LocaleData.getBundle("sun.text.resources.FormatData",
                                                 locales[i]);
        //
        // Get the currency pattern for this locale.  We have to fish it
        // out of the ResourceBundle directly, since DecimalFormat.toPattern
        // will return the localized symbol, not \00a4
        //
        String[] numPatterns = (String[])rb.getObject("NumberPatterns");
        String pattern = numPatterns[1];

        if (pattern.indexOf("\u00A4") == -1 ) {
            errln("Currency format for " + locales[i] +
                    " does not contain generic currency symbol:" +
                    pattern );
        }

        // Create a DecimalFormat using the pattern we got and format a number
        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locales[i]);
        DecimalFormat fmt1 = new DecimalFormat(pattern, symbols);

        String result1 = fmt1.format(1.111);

        //
        // Now substitute in the locale's currency symbol and create another
        // pattern.  Replace the decimal separator with the monetary separator.
        //
        char decSep = symbols.getDecimalSeparator();
        char monSep = symbols.getMonetaryDecimalSeparator();
        StringBuffer buf = new StringBuffer(pattern);
        for (int j = 0; j < buf.length(); j++) {
            if (buf.charAt(j) == '\u00a4') {
                String cur = "'" + symbols.getCurrencySymbol() + "'";
                buf.replace(j, j+1, cur);
                j += cur.length() - 1;
            }
        }
        symbols.setDecimalSeparator(monSep);
        DecimalFormat fmt2 = new DecimalFormat(buf.toString(), symbols);

        String result2 = fmt2.format(1.111);

        if (!result1.equals(result2)) {
            errln("Results for " + locales[i] + " differ: " +
                  result1 + " vs " + result2);
        }
    }
}
 
Example #14
Source File: TimeZoneTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test the basic functionality of the getDisplayName() API.
 *
 * Bug 4112869
 * Bug 4028006
 *
 * See also API change request A41.
 *
 * 4/21/98 - make smarter, so the test works if the ext resources
 * are present or not.
 */
public void TestDisplayName() {
    TimeZone zone = TimeZone.getTimeZone("PST");
    String name = zone.getDisplayName(Locale.ENGLISH);
    logln("PST->" + name);
    if (!name.equals("Pacific Standard Time"))
        errln("Fail: Expected \"Pacific Standard Time\"");

    //*****************************************************************
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    //*****************************************************************
    Object[] DATA = {
        new Boolean(false), new Integer(TimeZone.SHORT), "PST",
        new Boolean(true),  new Integer(TimeZone.SHORT), "PDT",
        new Boolean(false), new Integer(TimeZone.LONG),  "Pacific Standard Time",
        new Boolean(true),  new Integer(TimeZone.LONG),  "Pacific Daylight Time",
    };

    for (int i=0; i<DATA.length; i+=3) {
        name = zone.getDisplayName(((Boolean)DATA[i]).booleanValue(),
                                   ((Integer)DATA[i+1]).intValue(),
                                   Locale.ENGLISH);
        if (!name.equals(DATA[i+2]))
            errln("Fail: Expected " + DATA[i+2] + "; got " + name);
    }

    // Make sure that we don't display the DST name by constructing a fake
    // PST zone that has DST all year long.
    SimpleTimeZone zone2 = new SimpleTimeZone(0, "PST");
    zone2.setStartRule(Calendar.JANUARY, 1, 0);
    zone2.setEndRule(Calendar.DECEMBER, 31, 0);
    logln("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date()));
    name = zone2.getDisplayName(Locale.ENGLISH);
    logln("Modified PST->" + name);
    if (!name.equals("Pacific Standard Time"))
        errln("Fail: Expected \"Pacific Standard Time\"");

    // Make sure we get the default display format for Locales
    // with no display name data.
    Locale zh_CN = Locale.SIMPLIFIED_CHINESE;
    name = zone.getDisplayName(zh_CN);
    //*****************************************************************
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    //*****************************************************************
    logln("PST(zh_CN)->" + name);

    // Now be smart -- check to see if zh resource is even present.
    // If not, we expect the en fallback behavior.
    ResourceBundle enRB = LocaleData.getBundle("sun.util.resources.TimeZoneNames",
                                               Locale.ENGLISH);
    ResourceBundle zhRB = LocaleData.getBundle("sun.util.resources.TimeZoneNames",
                                               zh_CN);

    boolean noZH = enRB == zhRB;

    if (noZH) {
        logln("Warning: Not testing the zh_CN behavior because resource is absent");
        if (!name.equals("Pacific Standard Time"))
            errln("Fail: Expected Pacific Standard Time");
    }
    else if (!name.equals("Pacific Standard Time") &&
             !name.equals("\u592a\u5e73\u6d0b\u6807\u51c6\u65f6\u95f4") &&
             !name.equals("GMT-08:00") &&
             !name.equals("GMT-8:00") &&
             !name.equals("GMT-0800") &&
             !name.equals("GMT-800")) {
        errln("Fail: Expected GMT-08:00 or something similar");
        errln("************************************************************");
        errln("THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED");
        errln("************************************************************");
    }

    // Now try a non-existent zone
    zone2 = new SimpleTimeZone(90*60*1000, "xyzzy");
    name = zone2.getDisplayName(Locale.ENGLISH);
    logln("GMT+90min->" + name);
    if (!name.equals("GMT+01:30") &&
        !name.equals("GMT+1:30") &&
        !name.equals("GMT+0130") &&
        !name.equals("GMT+130"))
        errln("Fail: Expected GMT+01:30 or something similar");
}
 
Example #15
Source File: NumberRegression.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Locale data should use generic currency symbol
 *
 * 1) Make sure that all currency formats use the generic currency symbol.
 * 2) Make sure we get the same results using the generic symbol or a
 *    hard-coded one.
 */
public void Test4122840()
{
    Locale[] locales = NumberFormat.getAvailableLocales();

    for (int i = 0; i < locales.length; i++) {
        ResourceBundle rb = LocaleData.getBundle("sun.text.resources.FormatData",
                                                 locales[i]);
        //
        // Get the currency pattern for this locale.  We have to fish it
        // out of the ResourceBundle directly, since DecimalFormat.toPattern
        // will return the localized symbol, not \00a4
        //
        String[] numPatterns = (String[])rb.getObject("NumberPatterns");
        String pattern = numPatterns[1];

        if (pattern.indexOf("\u00A4") == -1 ) {
            errln("Currency format for " + locales[i] +
                    " does not contain generic currency symbol:" +
                    pattern );
        }

        // Create a DecimalFormat using the pattern we got and format a number
        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locales[i]);
        DecimalFormat fmt1 = new DecimalFormat(pattern, symbols);

        String result1 = fmt1.format(1.111);

        //
        // Now substitute in the locale's currency symbol and create another
        // pattern.  Replace the decimal separator with the monetary separator.
        //
        char decSep = symbols.getDecimalSeparator();
        char monSep = symbols.getMonetaryDecimalSeparator();
        StringBuffer buf = new StringBuffer(pattern);
        for (int j = 0; j < buf.length(); j++) {
            if (buf.charAt(j) == '\u00a4') {
                String cur = "'" + symbols.getCurrencySymbol() + "'";
                buf.replace(j, j+1, cur);
                j += cur.length() - 1;
            }
        }
        symbols.setDecimalSeparator(monSep);
        DecimalFormat fmt2 = new DecimalFormat(buf.toString(), symbols);

        String result2 = fmt2.format(1.111);

        if (!result1.equals(result2)) {
            errln("Results for " + locales[i] + " differ: " +
                  result1 + " vs " + result2);
        }
    }
}
 
Example #16
Source File: NumberTest.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Bug 4122840
 * Make sure that the currency symbol is not hard-coded in any locale.
 */
public void TestCurrencySubstitution() {
    final String SYM = "<currency>";
    final String INTL_SYM = "<intl.currency>";
    Locale[] locales = NumberFormat.getAvailableLocales();
    for (int i=0; i<locales.length; ++i) {
        NumberFormat nf = NumberFormat.getCurrencyInstance(locales[i]);
        if (nf instanceof DecimalFormat) {
            DecimalFormat df = (DecimalFormat)nf;
            String genericPos = df.format(1234.5678);
            String genericNeg = df.format(-1234.5678);
            DecimalFormatSymbols sym = df.getDecimalFormatSymbols();
            sym.setCurrencySymbol(SYM);
            sym.setInternationalCurrencySymbol(INTL_SYM);
            // We have to make a new DecimalFormat from scratch in order
            // to make the new symbols 'take'.  This may be a bug or
            // design flaw in DecimalFormat.
            String[] patterns = LocaleData.getBundle("sun.text.resources.FormatData", locales[i])
                                          .getStringArray("NumberPatterns");
            df = new DecimalFormat(patterns[1 /*CURRENCYSTYLE*/], sym);
            String customPos = df.format(1234.5678);
            String customNeg = df.format(-1234.5678);
            if (genericPos.equals(customPos) || genericNeg.equals(customNeg)) {
                errln("FAIL: " + locales[i] +
                      " not using currency symbol substitution: " + genericPos);
            }
            else {
                if (customPos.indexOf(SYM) >= 0) {
                    if (customNeg.indexOf(INTL_SYM) >= 0)
                        errln("Fail: Positive and negative patterns use different symbols");
                    else
                        logln("Ok: " + locales[i] +
                              " uses currency symbol: " + genericPos +
                              ", " + customPos);
                }
                else if (customPos.indexOf(INTL_SYM) >= 0) {
                    if (customNeg.indexOf(SYM) >= 0)
                        errln("Fail: Positive and negative patterns use different symbols");
                    else
                        logln("Ok: " + locales[i] +
                              " uses intl. currency symbol: " + genericPos +
                              ", " + customPos);
                }
                else {
                    errln("FAIL: " + locales[i] +
                          " contains no currency symbol (impossible!)");
                }
            }
        }
        else logln("Skipping " + locales[i] + "; not a DecimalFormat");
    }
}
 
Example #17
Source File: SimpleDateFormat.java    From jdk-1.7-annotated with Apache License 2.0 4 votes vote down vote up
SimpleDateFormat(int timeStyle, int dateStyle, Locale loc) {
    if (loc == null) {
        throw new NullPointerException();
    }

    this.locale = loc;
    // initialize calendar and related fields
    initializeCalendar(loc);

    /* try the cache first */
    String[] dateTimePatterns = cachedLocaleData.get(loc);
    if (dateTimePatterns == null) { /* cache miss */
        ResourceBundle r = LocaleData.getDateFormatData(loc);
        if (!isGregorianCalendar()) {
            try {
                dateTimePatterns = r.getStringArray(getCalendarName() + ".DateTimePatterns");
            } catch (MissingResourceException e) {
            }
        }
        if (dateTimePatterns == null) {
            dateTimePatterns = r.getStringArray("DateTimePatterns");
        }
        /* update cache */
        cachedLocaleData.putIfAbsent(loc, dateTimePatterns);
    }
    formatData = DateFormatSymbols.getInstanceRef(loc);
    if ((timeStyle >= 0) && (dateStyle >= 0)) {
        Object[] dateTimeArgs = {dateTimePatterns[timeStyle],
                                 dateTimePatterns[dateStyle + 4]};
        pattern = MessageFormat.format(dateTimePatterns[8], dateTimeArgs);
    }
    else if (timeStyle >= 0) {
        pattern = dateTimePatterns[timeStyle];
    }
    else if (dateStyle >= 0) {
        pattern = dateTimePatterns[dateStyle + 4];
    }
    else {
        throw new IllegalArgumentException("No date or time style specified");
    }

    initialize(loc);
}
 
Example #18
Source File: TimeZoneTest.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test the basic functionality of the getDisplayName() API.
 *
 * Bug 4112869
 * Bug 4028006
 *
 * See also API change request A41.
 *
 * 4/21/98 - make smarter, so the test works if the ext resources
 * are present or not.
 */
public void TestDisplayName() {
    TimeZone zone = TimeZone.getTimeZone("PST");
    String name = zone.getDisplayName(Locale.ENGLISH);
    logln("PST->" + name);
    if (!name.equals("Pacific Standard Time"))
        errln("Fail: Expected \"Pacific Standard Time\"");

    //*****************************************************************
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    //*****************************************************************
    Object[] DATA = {
        new Boolean(false), new Integer(TimeZone.SHORT), "PST",
        new Boolean(true),  new Integer(TimeZone.SHORT), "PDT",
        new Boolean(false), new Integer(TimeZone.LONG),  "Pacific Standard Time",
        new Boolean(true),  new Integer(TimeZone.LONG),  "Pacific Daylight Time",
    };

    for (int i=0; i<DATA.length; i+=3) {
        name = zone.getDisplayName(((Boolean)DATA[i]).booleanValue(),
                                   ((Integer)DATA[i+1]).intValue(),
                                   Locale.ENGLISH);
        if (!name.equals(DATA[i+2]))
            errln("Fail: Expected " + DATA[i+2] + "; got " + name);
    }

    // Make sure that we don't display the DST name by constructing a fake
    // PST zone that has DST all year long.
    SimpleTimeZone zone2 = new SimpleTimeZone(0, "PST");
    zone2.setStartRule(Calendar.JANUARY, 1, 0);
    zone2.setEndRule(Calendar.DECEMBER, 31, 0);
    logln("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date()));
    name = zone2.getDisplayName(Locale.ENGLISH);
    logln("Modified PST->" + name);
    if (!name.equals("Pacific Standard Time"))
        errln("Fail: Expected \"Pacific Standard Time\"");

    // Make sure we get the default display format for Locales
    // with no display name data.
    Locale zh_CN = Locale.SIMPLIFIED_CHINESE;
    name = zone.getDisplayName(zh_CN);
    //*****************************************************************
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    //*****************************************************************
    logln("PST(zh_CN)->" + name);

    // Now be smart -- check to see if zh resource is even present.
    // If not, we expect the en fallback behavior.
    ResourceBundle enRB = LocaleData.getBundle("sun.util.resources.TimeZoneNames",
                                               Locale.ENGLISH);
    ResourceBundle zhRB = LocaleData.getBundle("sun.util.resources.TimeZoneNames",
                                               zh_CN);

    boolean noZH = enRB == zhRB;

    if (noZH) {
        logln("Warning: Not testing the zh_CN behavior because resource is absent");
        if (!name.equals("Pacific Standard Time"))
            errln("Fail: Expected Pacific Standard Time");
    }
    else if (!name.equals("Pacific Standard Time") &&
             !name.equals("\u592a\u5e73\u6d0b\u6807\u51c6\u65f6\u95f4") &&
             !name.equals("GMT-08:00") &&
             !name.equals("GMT-8:00") &&
             !name.equals("GMT-0800") &&
             !name.equals("GMT-800")) {
        errln("Fail: Expected GMT-08:00 or something similar");
        errln("************************************************************");
        errln("THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED");
        errln("************************************************************");
    }

    // Now try a non-existent zone
    zone2 = new SimpleTimeZone(90*60*1000, "xyzzy");
    name = zone2.getDisplayName(Locale.ENGLISH);
    logln("GMT+90min->" + name);
    if (!name.equals("GMT+01:30") &&
        !name.equals("GMT+1:30") &&
        !name.equals("GMT+0130") &&
        !name.equals("GMT+130"))
        errln("Fail: Expected GMT+01:30 or something similar");
}
 
Example #19
Source File: Collator.java    From jdk-1.7-annotated with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the Collator for the desired locale.
 * @param desiredLocale the desired locale.
 * @return the Collator for the desired locale.
 * @see java.util.Locale
 * @see java.util.ResourceBundle
 */
public static synchronized
Collator getInstance(Locale desiredLocale)
{
    Collator result = (Collator) cache.get(desiredLocale);
    if (result != null) {
             return (Collator)result.clone();  // make the world safe
    }

    // Check whether a provider can provide an implementation that's closer
    // to the requested locale than what the Java runtime itself can provide.
    LocaleServiceProviderPool pool =
        LocaleServiceProviderPool.getPool(CollatorProvider.class);
    if (pool.hasProviders()) {
        Collator providersInstance = pool.getLocalizedObject(
                                        CollatorGetter.INSTANCE,
                                        desiredLocale,
                                        desiredLocale);
        if (providersInstance != null) {
            return providersInstance;
        }
    }

    // Load the resource of the desired locale from resource
    // manager.
    String colString = "";
    try {
        ResourceBundle resource = LocaleData.getCollationData(desiredLocale);

        colString = resource.getString("Rule");
    } catch (MissingResourceException e) {
        // Use default values
    }
    try
    {
        result = new RuleBasedCollator( CollationRules.DEFAULTRULES +
                                        colString,
                                        CANONICAL_DECOMPOSITION );
    }
    catch(ParseException foo)
    {
        // predefined tables should contain correct grammar
        try {
            result = new RuleBasedCollator( CollationRules.DEFAULTRULES );
        } catch (ParseException bar) {
            // do nothing
        }
    }
    // Now that RuleBasedCollator adds expansions for pre-composed characters
    // into their decomposed equivalents, the default collators don't need
    // to have decomposition turned on.  Laura, 5/5/98, bug 4114077
    result.setDecomposition(NO_DECOMPOSITION);

    cache.put(desiredLocale,result);
    return (Collator)result.clone();
}
 
Example #20
Source File: TimeZoneTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test the basic functionality of the getDisplayName() API.
 *
 * Bug 4112869
 * Bug 4028006
 *
 * See also API change request A41.
 *
 * 4/21/98 - make smarter, so the test works if the ext resources
 * are present or not.
 */
public void TestDisplayName() {
    TimeZone zone = TimeZone.getTimeZone("PST");
    String name = zone.getDisplayName(Locale.ENGLISH);
    logln("PST->" + name);
    if (!name.equals("Pacific Standard Time"))
        errln("Fail: Expected \"Pacific Standard Time\"");

    //*****************************************************************
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    //*****************************************************************
    Object[] DATA = {
        new Boolean(false), new Integer(TimeZone.SHORT), "PST",
        new Boolean(true),  new Integer(TimeZone.SHORT), "PDT",
        new Boolean(false), new Integer(TimeZone.LONG),  "Pacific Standard Time",
        new Boolean(true),  new Integer(TimeZone.LONG),  "Pacific Daylight Time",
    };

    for (int i=0; i<DATA.length; i+=3) {
        name = zone.getDisplayName(((Boolean)DATA[i]).booleanValue(),
                                   ((Integer)DATA[i+1]).intValue(),
                                   Locale.ENGLISH);
        if (!name.equals(DATA[i+2]))
            errln("Fail: Expected " + DATA[i+2] + "; got " + name);
    }

    // Make sure that we don't display the DST name by constructing a fake
    // PST zone that has DST all year long.
    SimpleTimeZone zone2 = new SimpleTimeZone(0, "PST");
    zone2.setStartRule(Calendar.JANUARY, 1, 0);
    zone2.setEndRule(Calendar.DECEMBER, 31, 0);
    logln("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date()));
    name = zone2.getDisplayName(Locale.ENGLISH);
    logln("Modified PST->" + name);
    if (!name.equals("Pacific Standard Time"))
        errln("Fail: Expected \"Pacific Standard Time\"");

    // Make sure we get the default display format for Locales
    // with no display name data.
    Locale zh_CN = Locale.SIMPLIFIED_CHINESE;
    name = zone.getDisplayName(zh_CN);
    //*****************************************************************
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    //*****************************************************************
    logln("PST(zh_CN)->" + name);

    // Now be smart -- check to see if zh resource is even present.
    // If not, we expect the en fallback behavior.
    ResourceBundle enRB = LocaleData.getBundle("sun.util.resources.TimeZoneNames",
                                               Locale.ENGLISH);
    ResourceBundle zhRB = LocaleData.getBundle("sun.util.resources.TimeZoneNames",
                                               zh_CN);

    boolean noZH = enRB == zhRB;

    if (noZH) {
        logln("Warning: Not testing the zh_CN behavior because resource is absent");
        if (!name.equals("Pacific Standard Time"))
            errln("Fail: Expected Pacific Standard Time");
    }
    else if (!name.equals("Pacific Standard Time") &&
             !name.equals("\u592a\u5e73\u6d0b\u6807\u51c6\u65f6\u95f4") &&
             !name.equals("GMT-08:00") &&
             !name.equals("GMT-8:00") &&
             !name.equals("GMT-0800") &&
             !name.equals("GMT-800")) {
        errln("Fail: Expected GMT-08:00 or something similar");
        errln("************************************************************");
        errln("THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED");
        errln("************************************************************");
    }

    // Now try a non-existent zone
    zone2 = new SimpleTimeZone(90*60*1000, "xyzzy");
    name = zone2.getDisplayName(Locale.ENGLISH);
    logln("GMT+90min->" + name);
    if (!name.equals("GMT+01:30") &&
        !name.equals("GMT+1:30") &&
        !name.equals("GMT+0130") &&
        !name.equals("GMT+130"))
        errln("Fail: Expected GMT+01:30 or something similar");
}
 
Example #21
Source File: NumberRegression.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Locale data should use generic currency symbol
 *
 * 1) Make sure that all currency formats use the generic currency symbol.
 * 2) Make sure we get the same results using the generic symbol or a
 *    hard-coded one.
 */
public void Test4122840()
{
    Locale[] locales = NumberFormat.getAvailableLocales();

    for (int i = 0; i < locales.length; i++) {
        ResourceBundle rb = LocaleData.getBundle("sun.text.resources.FormatData",
                                                 locales[i]);
        //
        // Get the currency pattern for this locale.  We have to fish it
        // out of the ResourceBundle directly, since DecimalFormat.toPattern
        // will return the localized symbol, not \00a4
        //
        String[] numPatterns = (String[])rb.getObject("NumberPatterns");
        String pattern = numPatterns[1];

        if (pattern.indexOf("\u00A4") == -1 ) {
            errln("Currency format for " + locales[i] +
                    " does not contain generic currency symbol:" +
                    pattern );
        }

        // Create a DecimalFormat using the pattern we got and format a number
        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locales[i]);
        DecimalFormat fmt1 = new DecimalFormat(pattern, symbols);

        String result1 = fmt1.format(1.111);

        //
        // Now substitute in the locale's currency symbol and create another
        // pattern.  Replace the decimal separator with the monetary separator.
        //
        char decSep = symbols.getDecimalSeparator();
        char monSep = symbols.getMonetaryDecimalSeparator();
        StringBuffer buf = new StringBuffer(pattern);
        for (int j = 0; j < buf.length(); j++) {
            if (buf.charAt(j) == '\u00a4') {
                String cur = "'" + symbols.getCurrencySymbol() + "'";
                buf.replace(j, j+1, cur);
                j += cur.length() - 1;
            }
        }
        symbols.setDecimalSeparator(monSep);
        DecimalFormat fmt2 = new DecimalFormat(buf.toString(), symbols);

        String result2 = fmt2.format(1.111);

        if (!result1.equals(result2)) {
            errln("Results for " + locales[i] + " differ: " +
                  result1 + " vs " + result2);
        }
    }
}
 
Example #22
Source File: NumberTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Bug 4122840
 * Make sure that the currency symbol is not hard-coded in any locale.
 */
public void TestCurrencySubstitution() {
    final String SYM = "<currency>";
    final String INTL_SYM = "<intl.currency>";
    Locale[] locales = NumberFormat.getAvailableLocales();
    for (int i=0; i<locales.length; ++i) {
        NumberFormat nf = NumberFormat.getCurrencyInstance(locales[i]);
        if (nf instanceof DecimalFormat) {
            DecimalFormat df = (DecimalFormat)nf;
            String genericPos = df.format(1234.5678);
            String genericNeg = df.format(-1234.5678);
            DecimalFormatSymbols sym = df.getDecimalFormatSymbols();
            sym.setCurrencySymbol(SYM);
            sym.setInternationalCurrencySymbol(INTL_SYM);
            // We have to make a new DecimalFormat from scratch in order
            // to make the new symbols 'take'.  This may be a bug or
            // design flaw in DecimalFormat.
            String[] patterns = LocaleData.getBundle("sun.text.resources.FormatData", locales[i])
                                          .getStringArray("NumberPatterns");
            df = new DecimalFormat(patterns[1 /*CURRENCYSTYLE*/], sym);
            String customPos = df.format(1234.5678);
            String customNeg = df.format(-1234.5678);
            if (genericPos.equals(customPos) || genericNeg.equals(customNeg)) {
                errln("FAIL: " + locales[i] +
                      " not using currency symbol substitution: " + genericPos);
            }
            else {
                if (customPos.indexOf(SYM) >= 0) {
                    if (customNeg.indexOf(INTL_SYM) >= 0)
                        errln("Fail: Positive and negative patterns use different symbols");
                    else
                        logln("Ok: " + locales[i] +
                              " uses currency symbol: " + genericPos +
                              ", " + customPos);
                }
                else if (customPos.indexOf(INTL_SYM) >= 0) {
                    if (customNeg.indexOf(SYM) >= 0)
                        errln("Fail: Positive and negative patterns use different symbols");
                    else
                        logln("Ok: " + locales[i] +
                              " uses intl. currency symbol: " + genericPos +
                              ", " + customPos);
                }
                else {
                    errln("FAIL: " + locales[i] +
                          " contains no currency symbol (impossible!)");
                }
            }
        }
        else logln("Skipping " + locales[i] + "; not a DecimalFormat");
    }
}
 
Example #23
Source File: NumberRegression.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Locale data should use generic currency symbol
 *
 * 1) Make sure that all currency formats use the generic currency symbol.
 * 2) Make sure we get the same results using the generic symbol or a
 *    hard-coded one.
 */
public void Test4122840()
{
    Locale[] locales = NumberFormat.getAvailableLocales();

    for (int i = 0; i < locales.length; i++) {
        ResourceBundle rb = LocaleData.getBundle("sun.text.resources.FormatData",
                                                 locales[i]);
        //
        // Get the currency pattern for this locale.  We have to fish it
        // out of the ResourceBundle directly, since DecimalFormat.toPattern
        // will return the localized symbol, not \00a4
        //
        String[] numPatterns = (String[])rb.getObject("NumberPatterns");
        String pattern = numPatterns[1];

        if (pattern.indexOf("\u00A4") == -1 ) {
            errln("Currency format for " + locales[i] +
                    " does not contain generic currency symbol:" +
                    pattern );
        }

        // Create a DecimalFormat using the pattern we got and format a number
        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locales[i]);
        DecimalFormat fmt1 = new DecimalFormat(pattern, symbols);

        String result1 = fmt1.format(1.111);

        //
        // Now substitute in the locale's currency symbol and create another
        // pattern.  Replace the decimal separator with the monetary separator.
        //
        char decSep = symbols.getDecimalSeparator();
        char monSep = symbols.getMonetaryDecimalSeparator();
        StringBuffer buf = new StringBuffer(pattern);
        for (int j = 0; j < buf.length(); j++) {
            if (buf.charAt(j) == '\u00a4') {
                String cur = "'" + symbols.getCurrencySymbol() + "'";
                buf.replace(j, j+1, cur);
                j += cur.length() - 1;
            }
        }
        symbols.setDecimalSeparator(monSep);
        DecimalFormat fmt2 = new DecimalFormat(buf.toString(), symbols);

        String result2 = fmt2.format(1.111);

        if (!result1.equals(result2)) {
            errln("Results for " + locales[i] + " differ: " +
                  result1 + " vs " + result2);
        }
    }
}
 
Example #24
Source File: TimeZoneTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test the basic functionality of the getDisplayName() API.
 *
 * Bug 4112869
 * Bug 4028006
 *
 * See also API change request A41.
 *
 * 4/21/98 - make smarter, so the test works if the ext resources
 * are present or not.
 */
public void TestDisplayName() {
    TimeZone zone = TimeZone.getTimeZone("PST");
    String name = zone.getDisplayName(Locale.ENGLISH);
    logln("PST->" + name);
    if (!name.equals("Pacific Standard Time"))
        errln("Fail: Expected \"Pacific Standard Time\"");

    //*****************************************************************
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    //*****************************************************************
    Object[] DATA = {
        new Boolean(false), new Integer(TimeZone.SHORT), "PST",
        new Boolean(true),  new Integer(TimeZone.SHORT), "PDT",
        new Boolean(false), new Integer(TimeZone.LONG),  "Pacific Standard Time",
        new Boolean(true),  new Integer(TimeZone.LONG),  "Pacific Daylight Time",
    };

    for (int i=0; i<DATA.length; i+=3) {
        name = zone.getDisplayName(((Boolean)DATA[i]).booleanValue(),
                                   ((Integer)DATA[i+1]).intValue(),
                                   Locale.ENGLISH);
        if (!name.equals(DATA[i+2]))
            errln("Fail: Expected " + DATA[i+2] + "; got " + name);
    }

    // Make sure that we don't display the DST name by constructing a fake
    // PST zone that has DST all year long.
    SimpleTimeZone zone2 = new SimpleTimeZone(0, "PST");
    zone2.setStartRule(Calendar.JANUARY, 1, 0);
    zone2.setEndRule(Calendar.DECEMBER, 31, 0);
    logln("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date()));
    name = zone2.getDisplayName(Locale.ENGLISH);
    logln("Modified PST->" + name);
    if (!name.equals("Pacific Standard Time"))
        errln("Fail: Expected \"Pacific Standard Time\"");

    // Make sure we get the default display format for Locales
    // with no display name data.
    Locale zh_CN = Locale.SIMPLIFIED_CHINESE;
    name = zone.getDisplayName(zh_CN);
    //*****************************************************************
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    //*****************************************************************
    logln("PST(zh_CN)->" + name);

    // Now be smart -- check to see if zh resource is even present.
    // If not, we expect the en fallback behavior.
    ResourceBundle enRB = LocaleData.getBundle("sun.util.resources.TimeZoneNames",
                                               Locale.ENGLISH);
    ResourceBundle zhRB = LocaleData.getBundle("sun.util.resources.TimeZoneNames",
                                               zh_CN);

    boolean noZH = enRB == zhRB;

    if (noZH) {
        logln("Warning: Not testing the zh_CN behavior because resource is absent");
        if (!name.equals("Pacific Standard Time"))
            errln("Fail: Expected Pacific Standard Time");
    }
    else if (!name.equals("Pacific Standard Time") &&
             !name.equals("\u592a\u5e73\u6d0b\u6807\u51c6\u65f6\u95f4") &&
             !name.equals("GMT-08:00") &&
             !name.equals("GMT-8:00") &&
             !name.equals("GMT-0800") &&
             !name.equals("GMT-800")) {
        errln("Fail: Expected GMT-08:00 or something similar");
        errln("************************************************************");
        errln("THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED");
        errln("************************************************************");
    }

    // Now try a non-existent zone
    zone2 = new SimpleTimeZone(90*60*1000, "xyzzy");
    name = zone2.getDisplayName(Locale.ENGLISH);
    logln("GMT+90min->" + name);
    if (!name.equals("GMT+01:30") &&
        !name.equals("GMT+1:30") &&
        !name.equals("GMT+0130") &&
        !name.equals("GMT+130"))
        errln("Fail: Expected GMT+01:30 or something similar");
}
 
Example #25
Source File: TimeZoneTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test the basic functionality of the getDisplayName() API.
 *
 * Bug 4112869
 * Bug 4028006
 *
 * See also API change request A41.
 *
 * 4/21/98 - make smarter, so the test works if the ext resources
 * are present or not.
 */
public void TestDisplayName() {
    TimeZone zone = TimeZone.getTimeZone("PST");
    String name = zone.getDisplayName(Locale.ENGLISH);
    logln("PST->" + name);
    if (!name.equals("Pacific Standard Time"))
        errln("Fail: Expected \"Pacific Standard Time\"");

    //*****************************************************************
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES
    //*****************************************************************
    Object[] DATA = {
        new Boolean(false), new Integer(TimeZone.SHORT), "PST",
        new Boolean(true),  new Integer(TimeZone.SHORT), "PDT",
        new Boolean(false), new Integer(TimeZone.LONG),  "Pacific Standard Time",
        new Boolean(true),  new Integer(TimeZone.LONG),  "Pacific Daylight Time",
    };

    for (int i=0; i<DATA.length; i+=3) {
        name = zone.getDisplayName(((Boolean)DATA[i]).booleanValue(),
                                   ((Integer)DATA[i+1]).intValue(),
                                   Locale.ENGLISH);
        if (!name.equals(DATA[i+2]))
            errln("Fail: Expected " + DATA[i+2] + "; got " + name);
    }

    // Make sure that we don't display the DST name by constructing a fake
    // PST zone that has DST all year long.
    SimpleTimeZone zone2 = new SimpleTimeZone(0, "PST");
    zone2.setStartRule(Calendar.JANUARY, 1, 0);
    zone2.setEndRule(Calendar.DECEMBER, 31, 0);
    logln("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date()));
    name = zone2.getDisplayName(Locale.ENGLISH);
    logln("Modified PST->" + name);
    if (!name.equals("Pacific Standard Time"))
        errln("Fail: Expected \"Pacific Standard Time\"");

    // Make sure we get the default display format for Locales
    // with no display name data.
    Locale zh_CN = Locale.SIMPLIFIED_CHINESE;
    name = zone.getDisplayName(zh_CN);
    //*****************************************************************
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES
    //*****************************************************************
    logln("PST(zh_CN)->" + name);

    // Now be smart -- check to see if zh resource is even present.
    // If not, we expect the en fallback behavior.
    ResourceBundle enRB = LocaleData.getBundle("sun.util.resources.TimeZoneNames",
                                               Locale.ENGLISH);
    ResourceBundle zhRB = LocaleData.getBundle("sun.util.resources.TimeZoneNames",
                                               zh_CN);

    boolean noZH = enRB == zhRB;

    if (noZH) {
        logln("Warning: Not testing the zh_CN behavior because resource is absent");
        if (!name.equals("Pacific Standard Time"))
            errln("Fail: Expected Pacific Standard Time");
    }
    else if (!name.equals("Pacific Standard Time") &&
             !name.equals("\u592a\u5e73\u6d0b\u6807\u51c6\u65f6\u95f4") &&
             !name.equals("GMT-08:00") &&
             !name.equals("GMT-8:00") &&
             !name.equals("GMT-0800") &&
             !name.equals("GMT-800")) {
        errln("Fail: Expected GMT-08:00 or something similar");
        errln("************************************************************");
        errln("THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED");
        errln("************************************************************");
    }

    // Now try a non-existent zone
    zone2 = new SimpleTimeZone(90*60*1000, "xyzzy");
    name = zone2.getDisplayName(Locale.ENGLISH);
    logln("GMT+90min->" + name);
    if (!name.equals("GMT+01:30") &&
        !name.equals("GMT+1:30") &&
        !name.equals("GMT+0130") &&
        !name.equals("GMT+130"))
        errln("Fail: Expected GMT+01:30 or something similar");
}
 
Example #26
Source File: NumberRegression.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Locale data should use generic currency symbol
 *
 * 1) Make sure that all currency formats use the generic currency symbol.
 * 2) Make sure we get the same results using the generic symbol or a
 *    hard-coded one.
 */
public void Test4122840()
{
    Locale[] locales = NumberFormat.getAvailableLocales();

    for (int i = 0; i < locales.length; i++) {
        ResourceBundle rb = LocaleData.getBundle("sun.text.resources.FormatData",
                                                 locales[i]);
        //
        // Get the currency pattern for this locale.  We have to fish it
        // out of the ResourceBundle directly, since DecimalFormat.toPattern
        // will return the localized symbol, not \00a4
        //
        String[] numPatterns = (String[])rb.getObject("NumberPatterns");
        String pattern = numPatterns[1];

        if (pattern.indexOf("\u00A4") == -1 ) {
            errln("Currency format for " + locales[i] +
                    " does not contain generic currency symbol:" +
                    pattern );
        }

        // Create a DecimalFormat using the pattern we got and format a number
        DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locales[i]);
        DecimalFormat fmt1 = new DecimalFormat(pattern, symbols);

        String result1 = fmt1.format(1.111);

        //
        // Now substitute in the locale's currency symbol and create another
        // pattern.  Replace the decimal separator with the monetary separator.
        //
        char decSep = symbols.getDecimalSeparator();
        char monSep = symbols.getMonetaryDecimalSeparator();
        StringBuffer buf = new StringBuffer(pattern);
        for (int j = 0; j < buf.length(); j++) {
            if (buf.charAt(j) == '\u00a4') {
                String cur = "'" + symbols.getCurrencySymbol() + "'";
                buf.replace(j, j+1, cur);
                j += cur.length() - 1;
            }
        }
        symbols.setDecimalSeparator(monSep);
        DecimalFormat fmt2 = new DecimalFormat(buf.toString(), symbols);

        String result2 = fmt2.format(1.111);

        if (!result1.equals(result2)) {
            errln("Results for " + locales[i] + " differ: " +
                  result1 + " vs " + result2);
        }
    }
}
 
Example #27
Source File: NumberTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Bug 4122840
 * Make sure that the currency symbol is not hard-coded in any locale.
 */
public void TestCurrencySubstitution() {
    final String SYM = "<currency>";
    final String INTL_SYM = "<intl.currency>";
    Locale[] locales = NumberFormat.getAvailableLocales();
    for (int i=0; i<locales.length; ++i) {
        NumberFormat nf = NumberFormat.getCurrencyInstance(locales[i]);
        if (nf instanceof DecimalFormat) {
            DecimalFormat df = (DecimalFormat)nf;
            String genericPos = df.format(1234.5678);
            String genericNeg = df.format(-1234.5678);
            DecimalFormatSymbols sym = df.getDecimalFormatSymbols();
            sym.setCurrencySymbol(SYM);
            sym.setInternationalCurrencySymbol(INTL_SYM);
            // We have to make a new DecimalFormat from scratch in order
            // to make the new symbols 'take'.  This may be a bug or
            // design flaw in DecimalFormat.
            String[] patterns = LocaleData.getBundle("sun.text.resources.FormatData", locales[i])
                                          .getStringArray("NumberPatterns");
            df = new DecimalFormat(patterns[1 /*CURRENCYSTYLE*/], sym);
            String customPos = df.format(1234.5678);
            String customNeg = df.format(-1234.5678);
            if (genericPos.equals(customPos) || genericNeg.equals(customNeg)) {
                errln("FAIL: " + locales[i] +
                      " not using currency symbol substitution: " + genericPos);
            }
            else {
                if (customPos.indexOf(SYM) >= 0) {
                    if (customNeg.indexOf(INTL_SYM) >= 0)
                        errln("Fail: Positive and negative patterns use different symbols");
                    else
                        logln("Ok: " + locales[i] +
                              " uses currency symbol: " + genericPos +
                              ", " + customPos);
                }
                else if (customPos.indexOf(INTL_SYM) >= 0) {
                    if (customNeg.indexOf(SYM) >= 0)
                        errln("Fail: Positive and negative patterns use different symbols");
                    else
                        logln("Ok: " + locales[i] +
                              " uses intl. currency symbol: " + genericPos +
                              ", " + customPos);
                }
                else {
                    errln("FAIL: " + locales[i] +
                          " contains no currency symbol (impossible!)");
                }
            }
        }
        else logln("Skipping " + locales[i] + "; not a DecimalFormat");
    }
}
 
Example #28
Source File: ResourceBundleBasedAdapter.java    From dragonwell8_jdk with GNU General Public License v2.0 votes vote down vote up
public LocaleData getLocaleData(); 
Example #29
Source File: ResourceBundleBasedAdapter.java    From jdk8u-dev-jdk with GNU General Public License v2.0 votes vote down vote up
public LocaleData getLocaleData(); 
Example #30
Source File: ResourceBundleBasedAdapter.java    From jdk8u-jdk with GNU General Public License v2.0 votes vote down vote up
public LocaleData getLocaleData();