1 /*
   2  * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util;
  27 
  28 import java.io.BufferedInputStream;
  29 import java.io.DataInputStream;
  30 import java.io.File;
  31 import java.io.FileInputStream;
  32 import java.io.FileReader;
  33 import java.io.InputStream;
  34 import java.io.IOException;
  35 import java.io.Serializable;
  36 import java.security.AccessController;
  37 import java.security.PrivilegedAction;
  38 import java.text.ParseException;
  39 import java.text.SimpleDateFormat;
  40 import java.util.concurrent.ConcurrentHashMap;
  41 import java.util.concurrent.ConcurrentMap;
  42 import java.util.regex.Pattern;
  43 import java.util.regex.Matcher;
  44 import java.util.spi.CurrencyNameProvider;
  45 import sun.util.locale.provider.LocaleServiceProviderPool;
  46 import sun.util.logging.PlatformLogger;
  47 
  48 
  49 /**
  50  * Represents a currency. Currencies are identified by their ISO 4217 currency
  51  * codes. Visit the <a href="http://www.iso.org/iso/home/standards/currency_codes.htm">
  52  * ISO web site</a> for more information.
  53  * <p>
  54  * The class is designed so that there's never more than one
  55  * <code>Currency</code> instance for any given currency. Therefore, there's
  56  * no public constructor. You obtain a <code>Currency</code> instance using
  57  * the <code>getInstance</code> methods.
  58  * <p>
  59  * Users can supersede the Java runtime currency data by means of the system
  60  * property {@code java.util.currency.data}. If this system property is
  61  * defined then its value is the location of a properties file, the contents of
  62  * which are key/value pairs of the ISO 3166 country codes and the ISO 4217
  63  * currency data respectively.  The value part consists of three ISO 4217 values
  64  * of a currency, i.e., an alphabetic code, a numeric code, and a minor unit.
  65  * Those three ISO 4217 values are separated by commas.
  66  * The lines which start with '#'s are considered comment lines. An optional UTC
  67  * timestamp may be specified per currency entry if users need to specify a
  68  * cutover date indicating when the new data comes into effect. The timestamp is
  69  * appended to the end of the currency properties and uses a comma as a separator.
  70  * If a UTC datestamp is present and valid, the JRE will only use the new currency
  71  * properties if the current UTC date is later than the date specified at class
  72  * loading time. The format of the timestamp must be of ISO 8601 format :
  73  * {@code 'yyyy-MM-dd'T'HH:mm:ss'}. For example,
  74  * <p>
  75  * <code>
  76  * #Sample currency properties<br>
  77  * JP=JPZ,999,0
  78  * </code>
  79  * <p>
  80  * will supersede the currency data for Japan.
  81  *
  82  * <p>
  83  * <code>
  84  * #Sample currency properties with cutover date<br>
  85  * JP=JPZ,999,0,2014-01-01T00:00:00
  86  * </code>
  87  * <p>
  88  * will supersede the currency data for Japan if {@code Currency} class is loaded after
  89  * 1st January 2014 00:00:00 GMT.
  90  * <p>
  91  * Where syntactically malformed entries are encountered, the entry is ignored
  92  * and the remainder of entries in file are processed. For instances where duplicate
  93  * country code entries exist, the behavior of the Currency information for that
  94  * {@code Currency} is undefined and the remainder of entries in file are processed.
  95  * <p>
  96  * It is recommended to use {@link java.math.BigDecimal} class while dealing
  97  * with {@code Currency} or monetary values as it provides better handling of floating
  98  * point numbers and their operations.
  99  *
 100  * @see java.math.BigDecimal
 101  * @since 1.4
 102  */
 103 public final class Currency implements Serializable {
 104 
 105     private static final long serialVersionUID = -158308464356906721L;
 106 
 107     /**
 108      * ISO 4217 currency code for this currency.
 109      *
 110      * @serial
 111      */
 112     private final String currencyCode;
 113 
 114     /**
 115      * Default fraction digits for this currency.
 116      * Set from currency data tables.
 117      */
 118     private final transient int defaultFractionDigits;
 119 
 120     /**
 121      * ISO 4217 numeric code for this currency.
 122      * Set from currency data tables.
 123      */
 124     private final transient int numericCode;
 125 
 126 
 127     // class data: instance map
 128 
 129     private static ConcurrentMap<String, Currency> instances = new ConcurrentHashMap<>(7);
 130     private static HashSet<Currency> available;
 131 
 132     // Class data: currency data obtained from currency.data file.
 133     // Purpose:
 134     // - determine valid country codes
 135     // - determine valid currency codes
 136     // - map country codes to currency codes
 137     // - obtain default fraction digits for currency codes
 138     //
 139     // sc = special case; dfd = default fraction digits
 140     // Simple countries are those where the country code is a prefix of the
 141     // currency code, and there are no known plans to change the currency.
 142     //
 143     // table formats:
 144     // - mainTable:
 145     //   - maps country code to 32-bit int
 146     //   - 26*26 entries, corresponding to [A-Z]*[A-Z]
 147     //   - \u007F -> not valid country
 148     //   - bits 20-31: unused
 149     //   - bits 10-19: numeric code (0 to 1023)
 150     //   - bit 9: 1 - special case, bits 0-4 indicate which one
 151     //            0 - simple country, bits 0-4 indicate final char of currency code
 152     //   - bits 5-8: fraction digits for simple countries, 0 for special cases
 153     //   - bits 0-4: final char for currency code for simple country, or ID of special case
 154     // - special case IDs:
 155     //   - 0: country has no currency
 156     //   - other: index into sc* arrays + 1
 157     // - scCutOverTimes: cut-over time in millis as returned by
 158     //   System.currentTimeMillis for special case countries that are changing
 159     //   currencies; Long.MAX_VALUE for countries that are not changing currencies
 160     // - scOldCurrencies: old currencies for special case countries
 161     // - scNewCurrencies: new currencies for special case countries that are
 162     //   changing currencies; null for others
 163     // - scOldCurrenciesDFD: default fraction digits for old currencies
 164     // - scNewCurrenciesDFD: default fraction digits for new currencies, 0 for
 165     //   countries that are not changing currencies
 166     // - otherCurrencies: concatenation of all currency codes that are not the
 167     //   main currency of a simple country, separated by "-"
 168     // - otherCurrenciesDFD: decimal format digits for currencies in otherCurrencies, same order
 169 
 170     static int formatVersion;
 171     static int dataVersion;
 172     static int[] mainTable;
 173     static long[] scCutOverTimes;
 174     static String[] scOldCurrencies;
 175     static String[] scNewCurrencies;
 176     static int[] scOldCurrenciesDFD;
 177     static int[] scNewCurrenciesDFD;
 178     static int[] scOldCurrenciesNumericCode;
 179     static int[] scNewCurrenciesNumericCode;
 180     static String otherCurrencies;
 181     static int[] otherCurrenciesDFD;
 182     static int[] otherCurrenciesNumericCode;
 183 
 184     // handy constants - must match definitions in GenerateCurrencyData
 185     // magic number
 186     private static final int MAGIC_NUMBER = 0x43757244;
 187     // number of characters from A to Z
 188     private static final int A_TO_Z = ('Z' - 'A') + 1;
 189     // entry for invalid country codes
 190     private static final int INVALID_COUNTRY_ENTRY = 0x0000007F;
 191     // entry for countries without currency
 192     private static final int COUNTRY_WITHOUT_CURRENCY_ENTRY = 0x00000200;
 193     // mask for simple case country entries
 194     private static final int SIMPLE_CASE_COUNTRY_MASK = 0x00000000;
 195     // mask for simple case country entry final character
 196     private static final int SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK = 0x0000001F;
 197     // mask for simple case country entry default currency digits
 198     private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK = 0x000001E0;
 199     // shift count for simple case country entry default currency digits
 200     private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT = 5;
 201     // maximum number for simple case country entry default currency digits
 202     private static final int SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS = 9;
 203     // mask for special case country entries
 204     private static final int SPECIAL_CASE_COUNTRY_MASK = 0x00000200;
 205     // mask for special case country index
 206     private static final int SPECIAL_CASE_COUNTRY_INDEX_MASK = 0x0000001F;
 207     // delta from entry index component in main table to index into special case tables
 208     private static final int SPECIAL_CASE_COUNTRY_INDEX_DELTA = 1;
 209     // mask for distinguishing simple and special case countries
 210     private static final int COUNTRY_TYPE_MASK = SIMPLE_CASE_COUNTRY_MASK | SPECIAL_CASE_COUNTRY_MASK;
 211     // mask for the numeric code of the currency
 212     private static final int NUMERIC_CODE_MASK = 0x000FFC00;
 213     // shift count for the numeric code of the currency
 214     private static final int NUMERIC_CODE_SHIFT = 10;
 215 
 216     // Currency data format version
 217     private static final int VALID_FORMAT_VERSION = 2;
 218 
 219     static {
 220         AccessController.doPrivileged(new PrivilegedAction<>() {
 221             @Override
 222             public Void run() {
 223                 try {
 224                     try (InputStream in = getClass().getResourceAsStream("/java/util/currency.data")) {
 225                         if (in == null) {
 226                             throw new InternalError("Currency data not found");
 227                         }
 228                         DataInputStream dis = new DataInputStream(new BufferedInputStream(in));
 229                         if (dis.readInt() != MAGIC_NUMBER) {
 230                             throw new InternalError("Currency data is possibly corrupted");
 231                         }
 232                         formatVersion = dis.readInt();
 233                         if (formatVersion != VALID_FORMAT_VERSION) {
 234                             throw new InternalError("Currency data format is incorrect");
 235                         }
 236                         dataVersion = dis.readInt();
 237                         mainTable = readIntArray(dis, A_TO_Z * A_TO_Z);
 238                         int scCount = dis.readInt();
 239                         scCutOverTimes = readLongArray(dis, scCount);
 240                         scOldCurrencies = readStringArray(dis, scCount);
 241                         scNewCurrencies = readStringArray(dis, scCount);
 242                         scOldCurrenciesDFD = readIntArray(dis, scCount);
 243                         scNewCurrenciesDFD = readIntArray(dis, scCount);
 244                         scOldCurrenciesNumericCode = readIntArray(dis, scCount);
 245                         scNewCurrenciesNumericCode = readIntArray(dis, scCount);
 246                         int ocCount = dis.readInt();
 247                         otherCurrencies = dis.readUTF();
 248                         otherCurrenciesDFD = readIntArray(dis, ocCount);
 249                         otherCurrenciesNumericCode = readIntArray(dis, ocCount);
 250                     }
 251                 } catch (IOException e) {
 252                     throw new InternalError(e);
 253                 }
 254 
 255                 // look for the properties file for overrides
 256                 String propsFile = System.getProperty("java.util.currency.data");
 257                 if (propsFile == null) {
 258                     propsFile = System.getProperty("java.home") + File.separator + "lib" +
 259                         File.separator + "currency.properties";
 260                 }
 261                 try {
 262                     File propFile = new File(propsFile);
 263                     if (propFile.exists()) {
 264                         Properties props = new Properties();
 265                         try (FileReader fr = new FileReader(propFile)) {
 266                             props.load(fr);
 267                         }
 268                         Set<String> keys = props.stringPropertyNames();
 269                         Pattern propertiesPattern =
 270                             Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*" +
 271                                 "(\\d+)\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" +
 272                                 "\\d{2}:\\d{2})?");
 273                         for (String key : keys) {
 274                            replaceCurrencyData(propertiesPattern,
 275                                key.toUpperCase(Locale.ROOT),
 276                                props.getProperty(key).toUpperCase(Locale.ROOT));
 277                         }
 278                     }
 279                 } catch (IOException e) {
 280                     info("currency.properties is ignored because of an IOException", e);
 281                 }
 282                 return null;
 283             }
 284         });
 285     }
 286 
 287     /**
 288      * Constants for retrieving localized names from the name providers.
 289      */
 290     private static final int SYMBOL = 0;
 291     private static final int DISPLAYNAME = 1;
 292 
 293 
 294     /**
 295      * Constructs a <code>Currency</code> instance. The constructor is private
 296      * so that we can insure that there's never more than one instance for a
 297      * given currency.
 298      */
 299     private Currency(String currencyCode, int defaultFractionDigits, int numericCode) {
 300         this.currencyCode = currencyCode;
 301         this.defaultFractionDigits = defaultFractionDigits;
 302         this.numericCode = numericCode;
 303     }
 304 
 305     /**
 306      * Returns the <code>Currency</code> instance for the given currency code.
 307      *
 308      * @param currencyCode the ISO 4217 code of the currency
 309      * @return the <code>Currency</code> instance for the given currency code
 310      * @exception NullPointerException if <code>currencyCode</code> is null
 311      * @exception IllegalArgumentException if <code>currencyCode</code> is not
 312      * a supported ISO 4217 code.
 313      */
 314     public static Currency getInstance(String currencyCode) {
 315         return getInstance(currencyCode, Integer.MIN_VALUE, 0);
 316     }
 317 
 318     private static Currency getInstance(String currencyCode, int defaultFractionDigits,
 319         int numericCode) {
 320         // Try to look up the currency code in the instances table.
 321         // This does the null pointer check as a side effect.
 322         // Also, if there already is an entry, the currencyCode must be valid.
 323         Currency instance = instances.get(currencyCode);
 324         if (instance != null) {
 325             return instance;
 326         }
 327 
 328         if (defaultFractionDigits == Integer.MIN_VALUE) {
 329             // Currency code not internally generated, need to verify first
 330             // A currency code must have 3 characters and exist in the main table
 331             // or in the list of other currencies.
 332             if (currencyCode.length() != 3) {
 333                 throw new IllegalArgumentException();
 334             }
 335             char char1 = currencyCode.charAt(0);
 336             char char2 = currencyCode.charAt(1);
 337             int tableEntry = getMainTableEntry(char1, char2);
 338             if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK
 339                     && tableEntry != INVALID_COUNTRY_ENTRY
 340                     && currencyCode.charAt(2) - 'A' == (tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK)) {
 341                 defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT;
 342                 numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT;
 343             } else {
 344                 // Check for '-' separately so we don't get false hits in the table.
 345                 if (currencyCode.charAt(2) == '-') {
 346                     throw new IllegalArgumentException();
 347                 }
 348                 int index = otherCurrencies.indexOf(currencyCode);
 349                 if (index == -1) {
 350                     throw new IllegalArgumentException();
 351                 }
 352                 defaultFractionDigits = otherCurrenciesDFD[index / 4];
 353                 numericCode = otherCurrenciesNumericCode[index / 4];
 354             }
 355         }
 356 
 357         Currency currencyVal =
 358             new Currency(currencyCode, defaultFractionDigits, numericCode);
 359         instance = instances.putIfAbsent(currencyCode, currencyVal);
 360         return (instance != null ? instance : currencyVal);
 361     }
 362 
 363     /**
 364      * Returns the <code>Currency</code> instance for the country of the
 365      * given locale. The language and variant components of the locale
 366      * are ignored. The result may vary over time, as countries change their
 367      * currencies. For example, for the original member countries of the
 368      * European Monetary Union, the method returns the old national currencies
 369      * until December 31, 2001, and the Euro from January 1, 2002, local time
 370      * of the respective countries.
 371      * <p>
 372      * The method returns <code>null</code> for territories that don't
 373      * have a currency, such as Antarctica.
 374      *
 375      * @param locale the locale for whose country a <code>Currency</code>
 376      * instance is needed
 377      * @return the <code>Currency</code> instance for the country of the given
 378      * locale, or {@code null}
 379      * @exception NullPointerException if <code>locale</code>
 380      * is {@code null}
 381      * @exception IllegalArgumentException if the country of the given {@code locale}
 382      * is not a supported ISO 3166 country code.
 383      */
 384     public static Currency getInstance(Locale locale) {
 385         String country = locale.getCountry();
 386         if (country == null) {
 387             throw new NullPointerException();
 388         }
 389 
 390         if (country.length() != 2) {
 391             throw new IllegalArgumentException();
 392         }
 393 
 394         char char1 = country.charAt(0);
 395         char char2 = country.charAt(1);
 396         int tableEntry = getMainTableEntry(char1, char2);
 397         if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK
 398                     && tableEntry != INVALID_COUNTRY_ENTRY) {
 399             char finalChar = (char) ((tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK) + 'A');
 400             int defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT;
 401             int numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT;
 402             StringBuilder sb = new StringBuilder(country);
 403             sb.append(finalChar);
 404             return getInstance(sb.toString(), defaultFractionDigits, numericCode);
 405         } else {
 406             // special cases
 407             if (tableEntry == INVALID_COUNTRY_ENTRY) {
 408                 throw new IllegalArgumentException();
 409             }
 410             if (tableEntry == COUNTRY_WITHOUT_CURRENCY_ENTRY) {
 411                 return null;
 412             } else {
 413                 int index = (tableEntry & SPECIAL_CASE_COUNTRY_INDEX_MASK) - SPECIAL_CASE_COUNTRY_INDEX_DELTA;
 414                 if (scCutOverTimes[index] == Long.MAX_VALUE || System.currentTimeMillis() < scCutOverTimes[index]) {
 415                     return getInstance(scOldCurrencies[index], scOldCurrenciesDFD[index],
 416                         scOldCurrenciesNumericCode[index]);
 417                 } else {
 418                     return getInstance(scNewCurrencies[index], scNewCurrenciesDFD[index],
 419                         scNewCurrenciesNumericCode[index]);
 420                 }
 421             }
 422         }
 423     }
 424 
 425     /**
 426      * Gets the set of available currencies.  The returned set of currencies
 427      * contains all of the available currencies, which may include currencies
 428      * that represent obsolete ISO 4217 codes.  The set can be modified
 429      * without affecting the available currencies in the runtime.
 430      *
 431      * @return the set of available currencies.  If there is no currency
 432      *    available in the runtime, the returned set is empty.
 433      * @since 1.7
 434      */
 435     public static Set<Currency> getAvailableCurrencies() {
 436         synchronized(Currency.class) {
 437             if (available == null) {
 438                 available = new HashSet<>(256);
 439 
 440                 // Add simple currencies first
 441                 for (char c1 = 'A'; c1 <= 'Z'; c1 ++) {
 442                     for (char c2 = 'A'; c2 <= 'Z'; c2 ++) {
 443                         int tableEntry = getMainTableEntry(c1, c2);
 444                         if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK
 445                              && tableEntry != INVALID_COUNTRY_ENTRY) {
 446                             char finalChar = (char) ((tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK) + 'A');
 447                             int defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT;
 448                             int numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT;
 449                             StringBuilder sb = new StringBuilder();
 450                             sb.append(c1);
 451                             sb.append(c2);
 452                             sb.append(finalChar);
 453                             available.add(getInstance(sb.toString(), defaultFractionDigits, numericCode));
 454                         }
 455                     }
 456                 }
 457 
 458                 // Now add other currencies
 459                 StringTokenizer st = new StringTokenizer(otherCurrencies, "-");
 460                 while (st.hasMoreElements()) {
 461                     available.add(getInstance((String)st.nextElement()));
 462                 }
 463             }
 464         }
 465 
 466         @SuppressWarnings("unchecked")
 467         Set<Currency> result = (Set<Currency>) available.clone();
 468         return result;
 469     }
 470 
 471     /**
 472      * Gets the ISO 4217 currency code of this currency.
 473      *
 474      * @return the ISO 4217 currency code of this currency.
 475      */
 476     public String getCurrencyCode() {
 477         return currencyCode;
 478     }
 479 
 480     /**
 481      * Gets the symbol of this currency for the default
 482      * {@link Locale.Category#DISPLAY DISPLAY} locale.
 483      * For example, for the US Dollar, the symbol is "$" if the default
 484      * locale is the US, while for other locales it may be "US$". If no
 485      * symbol can be determined, the ISO 4217 currency code is returned.
 486      * <p>
 487      * This is equivalent to calling
 488      * {@link #getSymbol(Locale)
 489      *     getSymbol(Locale.getDefault(Locale.Category.DISPLAY))}.
 490      *
 491      * @return the symbol of this currency for the default
 492      *     {@link Locale.Category#DISPLAY DISPLAY} locale
 493      */
 494     public String getSymbol() {
 495         return getSymbol(Locale.getDefault(Locale.Category.DISPLAY));
 496     }
 497 
 498     /**
 499      * Gets the symbol of this currency for the specified locale.
 500      * For example, for the US Dollar, the symbol is "$" if the specified
 501      * locale is the US, while for other locales it may be "US$". If no
 502      * symbol can be determined, the ISO 4217 currency code is returned.
 503      *
 504      * @param locale the locale for which a display name for this currency is
 505      * needed
 506      * @return the symbol of this currency for the specified locale
 507      * @exception NullPointerException if <code>locale</code> is null
 508      */
 509     public String getSymbol(Locale locale) {
 510         LocaleServiceProviderPool pool =
 511             LocaleServiceProviderPool.getPool(CurrencyNameProvider.class);
 512         String symbol = pool.getLocalizedObject(
 513                                 CurrencyNameGetter.INSTANCE,
 514                                 locale, currencyCode, SYMBOL);
 515         if (symbol != null) {
 516             return symbol;
 517         }
 518 
 519         // use currency code as symbol of last resort
 520         return currencyCode;
 521     }
 522 
 523     /**
 524     * Gets the default number of fraction digits used with this currency.
 525     * Note that the number of fraction digits is the same as ISO 4217's
 526     * minor unit for the currency.
 527     * For example, the default number of fraction digits for the Euro is 2,
 528     * while for the Japanese Yen it's 0.
 529     * In the case of pseudo-currencies, such as IMF Special Drawing Rights,
 530     * -1 is returned.
 531     *
 532     * @return the default number of fraction digits used with this currency
 533     */
 534     public int getDefaultFractionDigits() {
 535         return defaultFractionDigits;
 536     }
 537 
 538     /**
 539      * Returns the ISO 4217 numeric code of this currency.
 540      *
 541      * @return the ISO 4217 numeric code of this currency
 542      * @since 1.7
 543      */
 544     public int getNumericCode() {
 545         return numericCode;
 546     }
 547 
 548     /**
 549      * Gets the name that is suitable for displaying this currency for
 550      * the default {@link Locale.Category#DISPLAY DISPLAY} locale.
 551      * If there is no suitable display name found
 552      * for the default locale, the ISO 4217 currency code is returned.
 553      * <p>
 554      * This is equivalent to calling
 555      * {@link #getDisplayName(Locale)
 556      *     getDisplayName(Locale.getDefault(Locale.Category.DISPLAY))}.
 557      *
 558      * @return the display name of this currency for the default
 559      *     {@link Locale.Category#DISPLAY DISPLAY} locale
 560      * @since 1.7
 561      */
 562     public String getDisplayName() {
 563         return getDisplayName(Locale.getDefault(Locale.Category.DISPLAY));
 564     }
 565 
 566     /**
 567      * Gets the name that is suitable for displaying this currency for
 568      * the specified locale.  If there is no suitable display name found
 569      * for the specified locale, the ISO 4217 currency code is returned.
 570      *
 571      * @param locale the locale for which a display name for this currency is
 572      * needed
 573      * @return the display name of this currency for the specified locale
 574      * @exception NullPointerException if <code>locale</code> is null
 575      * @since 1.7
 576      */
 577     public String getDisplayName(Locale locale) {
 578         LocaleServiceProviderPool pool =
 579             LocaleServiceProviderPool.getPool(CurrencyNameProvider.class);
 580         String result = pool.getLocalizedObject(
 581                                 CurrencyNameGetter.INSTANCE,
 582                                 locale, currencyCode, DISPLAYNAME);
 583         if (result != null) {
 584             return result;
 585         }
 586 
 587         // use currency code as symbol of last resort
 588         return currencyCode;
 589     }
 590 
 591     /**
 592      * Returns the ISO 4217 currency code of this currency.
 593      *
 594      * @return the ISO 4217 currency code of this currency
 595      */
 596     @Override
 597     public String toString() {
 598         return currencyCode;
 599     }
 600 
 601     /**
 602      * Resolves instances being deserialized to a single instance per currency.
 603      */
 604     private Object readResolve() {
 605         return getInstance(currencyCode);
 606     }
 607 
 608     /**
 609      * Gets the main table entry for the country whose country code consists
 610      * of char1 and char2.
 611      */
 612     private static int getMainTableEntry(char char1, char char2) {
 613         if (char1 < 'A' || char1 > 'Z' || char2 < 'A' || char2 > 'Z') {
 614             throw new IllegalArgumentException();
 615         }
 616         return mainTable[(char1 - 'A') * A_TO_Z + (char2 - 'A')];
 617     }
 618 
 619     /**
 620      * Sets the main table entry for the country whose country code consists
 621      * of char1 and char2.
 622      */
 623     private static void setMainTableEntry(char char1, char char2, int entry) {
 624         if (char1 < 'A' || char1 > 'Z' || char2 < 'A' || char2 > 'Z') {
 625             throw new IllegalArgumentException();
 626         }
 627         mainTable[(char1 - 'A') * A_TO_Z + (char2 - 'A')] = entry;
 628     }
 629 
 630     /**
 631      * Obtains a localized currency names from a CurrencyNameProvider
 632      * implementation.
 633      */
 634     private static class CurrencyNameGetter
 635         implements LocaleServiceProviderPool.LocalizedObjectGetter<CurrencyNameProvider,
 636                                                                    String> {
 637         private static final CurrencyNameGetter INSTANCE = new CurrencyNameGetter();
 638 
 639         @Override
 640         public String getObject(CurrencyNameProvider currencyNameProvider,
 641                                 Locale locale,
 642                                 String key,
 643                                 Object... params) {
 644             assert params.length == 1;
 645             int type = (Integer)params[0];
 646 
 647             switch(type) {
 648             case SYMBOL:
 649                 return currencyNameProvider.getSymbol(key, locale);
 650             case DISPLAYNAME:
 651                 return currencyNameProvider.getDisplayName(key, locale);
 652             default:
 653                 assert false; // shouldn't happen
 654             }
 655 
 656             return null;
 657         }
 658     }
 659 
 660     private static int[] readIntArray(DataInputStream dis, int count) throws IOException {
 661         int[] ret = new int[count];
 662         for (int i = 0; i < count; i++) {
 663             ret[i] = dis.readInt();
 664         }
 665 
 666         return ret;
 667     }
 668 
 669     private static long[] readLongArray(DataInputStream dis, int count) throws IOException {
 670         long[] ret = new long[count];
 671         for (int i = 0; i < count; i++) {
 672             ret[i] = dis.readLong();
 673         }
 674 
 675         return ret;
 676     }
 677 
 678     private static String[] readStringArray(DataInputStream dis, int count) throws IOException {
 679         String[] ret = new String[count];
 680         for (int i = 0; i < count; i++) {
 681             ret[i] = dis.readUTF();
 682         }
 683 
 684         return ret;
 685     }
 686 
 687     /**
 688      * Replaces currency data found in the currencydata.properties file
 689      *
 690      * @param pattern regex pattern for the properties
 691      * @param ctry country code
 692      * @param curdata currency data.  This is a comma separated string that
 693      *    consists of "three-letter alphabet code", "three-digit numeric code",
 694      *    and "one-digit (0-9) default fraction digit".
 695      *    For example, "JPZ,392,0".
 696      *    An optional UTC date can be appended to the string (comma separated)
 697      *    to allow a currency change take effect after date specified.
 698      *    For example, "JP=JPZ,999,0,2014-01-01T00:00:00" has no effect unless
 699      *    UTC time is past 1st January 2014 00:00:00 GMT.
 700      */
 701     private static void replaceCurrencyData(Pattern pattern, String ctry, String curdata) {
 702 
 703         if (ctry.length() != 2) {
 704             // ignore invalid country code
 705             info("currency.properties entry for " + ctry +
 706                     " is ignored because of the invalid country code.", null);
 707             return;
 708         }
 709 
 710         Matcher m = pattern.matcher(curdata);
 711         if (!m.find() || (m.group(4) == null && countOccurrences(curdata, ',') >= 3)) {
 712             // format is not recognized.  ignore the data
 713             // if group(4) date string is null and we've 4 values, bad date value
 714             info("currency.properties entry for " + ctry +
 715                     " ignored because the value format is not recognized.", null);
 716             return;
 717         }
 718 
 719         try {
 720             if (m.group(4) != null && !isPastCutoverDate(m.group(4))) {
 721                 info("currency.properties entry for " + ctry +
 722                         " ignored since cutover date has not passed :" + curdata, null);
 723                 return;
 724             }
 725         } catch (ParseException ex) {
 726             info("currency.properties entry for " + ctry +
 727                         " ignored since exception encountered :" + ex.getMessage(), null);
 728             return;
 729         }
 730 
 731         String code = m.group(1);
 732         int numeric = Integer.parseInt(m.group(2));
 733         int entry = numeric << NUMERIC_CODE_SHIFT;
 734         int fraction = Integer.parseInt(m.group(3));
 735         if (fraction > SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS) {
 736             info("currency.properties entry for " + ctry +
 737                 " ignored since the fraction is more than " +
 738                 SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS + ":" + curdata, null);
 739             return;
 740         }
 741 
 742         int index;
 743         for (index = 0; index < scOldCurrencies.length; index++) {
 744             if (scOldCurrencies[index].equals(code)) {
 745                 break;
 746             }
 747         }
 748 
 749         if (index == scOldCurrencies.length) {
 750             // simple case
 751             entry |= (fraction << SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT) |
 752                      (code.charAt(2) - 'A');
 753         } else {
 754             // special case
 755             entry |= SPECIAL_CASE_COUNTRY_MASK |
 756                      (index + SPECIAL_CASE_COUNTRY_INDEX_DELTA);
 757         }
 758         setMainTableEntry(ctry.charAt(0), ctry.charAt(1), entry);
 759     }
 760 
 761     private static boolean isPastCutoverDate(String s) throws ParseException {
 762         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT);
 763         format.setTimeZone(TimeZone.getTimeZone("UTC"));
 764         format.setLenient(false);
 765         long time = format.parse(s.trim()).getTime();
 766         return System.currentTimeMillis() > time;
 767 
 768     }
 769 
 770     private static int countOccurrences(String value, char match) {
 771         int count = 0;
 772         for (char c : value.toCharArray()) {
 773             if (c == match) {
 774                ++count;
 775             }
 776         }
 777         return count;
 778     }
 779 
 780     private static void info(String message, Throwable t) {
 781         PlatformLogger logger = PlatformLogger.getLogger("java.util.Currency");
 782         if (logger.isLoggable(PlatformLogger.Level.INFO)) {
 783             if (t != null) {
 784                 logger.info(message, t);
 785             } else {
 786                 logger.info(message);
 787             }
 788         }
 789     }
 790 }