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 specialCasesList
 157 
 158     static int formatVersion;
 159     static int dataVersion;
 160     static int[] mainTable;
 161     static List<SpecialCaseEntry> specialCasesList;
 162     static List<OtherCurrencyEntry> otherCurrenciesList;
 163 
 164     // handy constants - must match definitions in GenerateCurrencyData
 165     // magic number
 166     private static final int MAGIC_NUMBER = 0x43757244;
 167     // number of characters from A to Z
 168     private static final int A_TO_Z = ('Z' - 'A') + 1;
 169     // entry for invalid country codes
 170     private static final int INVALID_COUNTRY_ENTRY = 0x0000007F;
 171     // entry for countries without currency
 172     private static final int COUNTRY_WITHOUT_CURRENCY_ENTRY = 0x00000200;
 173     // mask for simple case country entries
 174     private static final int SIMPLE_CASE_COUNTRY_MASK = 0x00000000;
 175     // mask for simple case country entry final character
 176     private static final int SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK = 0x0000001F;
 177     // mask for simple case country entry default currency digits
 178     private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK = 0x000001E0;
 179     // shift count for simple case country entry default currency digits
 180     private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT = 5;
 181     // maximum number for simple case country entry default currency digits
 182     private static final int SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS = 9;
 183     // mask for special case country entries
 184     private static final int SPECIAL_CASE_COUNTRY_MASK = 0x00000200;
 185     // mask for special case country index
 186     private static final int SPECIAL_CASE_COUNTRY_INDEX_MASK = 0x0000001F;
 187     // delta from entry index component in main table to index into special case tables
 188     private static final int SPECIAL_CASE_COUNTRY_INDEX_DELTA = 1;
 189     // mask for distinguishing simple and special case countries
 190     private static final int COUNTRY_TYPE_MASK = SIMPLE_CASE_COUNTRY_MASK | SPECIAL_CASE_COUNTRY_MASK;
 191     // mask for the numeric code of the currency
 192     private static final int NUMERIC_CODE_MASK = 0x000FFC00;
 193     // shift count for the numeric code of the currency
 194     private static final int NUMERIC_CODE_SHIFT = 10;
 195 
 196     // Currency data format version
 197     private static final int VALID_FORMAT_VERSION = 3;
 198 
 199     static {
 200         AccessController.doPrivileged(new PrivilegedAction<>() {
 201             @Override
 202             public Void run() {
 203                 try {
 204                     try (InputStream in = getClass().getResourceAsStream("/java/util/currency.data")) {
 205                         if (in == null) {
 206                             throw new InternalError("Currency data not found");
 207                         }
 208                         DataInputStream dis = new DataInputStream(new BufferedInputStream(in));
 209                         if (dis.readInt() != MAGIC_NUMBER) {
 210                             throw new InternalError("Currency data is possibly corrupted");
 211                         }
 212                         formatVersion = dis.readInt();
 213                         if (formatVersion != VALID_FORMAT_VERSION) {
 214                             throw new InternalError("Currency data format is incorrect");
 215                         }
 216                         dataVersion = dis.readInt();
 217                         mainTable = readIntArray(dis, A_TO_Z * A_TO_Z);
 218                         int scCount = dis.readInt();
 219                         specialCasesList = readSpecialCases(dis, scCount);
 220                         int ocCount = dis.readInt();
 221                         otherCurrenciesList = readOtherCurrencies(dis, ocCount);
 222                     }
 223                 } catch (IOException e) {
 224                     throw new InternalError(e);
 225                 }
 226 
 227                 // look for the properties file for overrides
 228                 String propsFile = System.getProperty("java.util.currency.data");
 229                 if (propsFile == null) {
 230                     propsFile = System.getProperty("java.home") + File.separator + "lib" +
 231                         File.separator + "currency.properties";
 232                 }
 233                 try {
 234                     File propFile = new File(propsFile);
 235                     if (propFile.exists()) {
 236                         Properties props = new Properties();
 237                         try (FileReader fr = new FileReader(propFile)) {
 238                             props.load(fr);
 239                         }
 240                         Set<String> keys = props.stringPropertyNames();
 241                         Pattern propertiesPattern =
 242                             Pattern.compile("([A-Z]{3})\\s*,\\s*(\\d{3})\\s*,\\s*" +
 243                                 "(\\d+)\\s*,?\\s*(\\d{4}-\\d{2}-\\d{2}T\\d{2}:" +
 244                                 "\\d{2}:\\d{2})?");
 245                         for (String key : keys) {
 246                            replaceCurrencyData(propertiesPattern,
 247                                key.toUpperCase(Locale.ROOT),
 248                                props.getProperty(key).toUpperCase(Locale.ROOT));
 249                         }
 250                     }
 251                 } catch (IOException e) {
 252                     info("currency.properties is ignored because of an IOException", e);
 253                 }
 254                 return null;
 255             }
 256         });
 257     }
 258 
 259     /**
 260      * Constants for retrieving localized names from the name providers.
 261      */
 262     private static final int SYMBOL = 0;
 263     private static final int DISPLAYNAME = 1;
 264 
 265 
 266     /**
 267      * Constructs a <code>Currency</code> instance. The constructor is private
 268      * so that we can insure that there's never more than one instance for a
 269      * given currency.
 270      */
 271     private Currency(String currencyCode, int defaultFractionDigits, int numericCode) {
 272         this.currencyCode = currencyCode;
 273         this.defaultFractionDigits = defaultFractionDigits;
 274         this.numericCode = numericCode;
 275     }
 276 
 277     /**
 278      * Returns the <code>Currency</code> instance for the given currency code.
 279      *
 280      * @param currencyCode the ISO 4217 code of the currency
 281      * @return the <code>Currency</code> instance for the given currency code
 282      * @exception NullPointerException if <code>currencyCode</code> is null
 283      * @exception IllegalArgumentException if <code>currencyCode</code> is not
 284      * a supported ISO 4217 code.
 285      */
 286     public static Currency getInstance(String currencyCode) {
 287         return getInstance(currencyCode, Integer.MIN_VALUE, 0);
 288     }
 289 
 290     private static Currency getInstance(String currencyCode, int defaultFractionDigits,
 291         int numericCode) {
 292         // Try to look up the currency code in the instances table.
 293         // This does the null pointer check as a side effect.
 294         // Also, if there already is an entry, the currencyCode must be valid.
 295         Currency instance = instances.get(currencyCode);
 296         if (instance != null) {
 297             return instance;
 298         }
 299 
 300         if (defaultFractionDigits == Integer.MIN_VALUE) {
 301             // Currency code not internally generated, need to verify first
 302             // A currency code must have 3 characters and exist in the main table
 303             // or in the list of other currencies.
 304             boolean found = false;
 305             if (currencyCode.length() != 3) {
 306                 throw new IllegalArgumentException();
 307             }
 308             char char1 = currencyCode.charAt(0);
 309             char char2 = currencyCode.charAt(1);
 310             int tableEntry = getMainTableEntry(char1, char2);
 311             if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK
 312                     && tableEntry != INVALID_COUNTRY_ENTRY
 313                     && currencyCode.charAt(2) - 'A' == (tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK)) {
 314                 defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT;
 315                 numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT;
 316                 found = true;
 317             } else { //special case
 318                 int[] fractionAndNumericCode = SpecialCaseEntry.findEntry(currencyCode);
 319                 if (fractionAndNumericCode != null) {
 320                     defaultFractionDigits = fractionAndNumericCode[0];
 321                     numericCode = fractionAndNumericCode[1];
 322                     found = true;
 323                 }
 324             }
 325 
 326             if (!found) {
 327                 OtherCurrencyEntry ocEntry = OtherCurrencyEntry.findEntry(currencyCode);
 328                 if (ocEntry == null) {
 329                     throw new IllegalArgumentException();
 330                 }
 331                 defaultFractionDigits = ocEntry.fraction;
 332                 numericCode = ocEntry.numericCode;
 333             }
 334         }
 335 
 336         Currency currencyVal =
 337             new Currency(currencyCode, defaultFractionDigits, numericCode);
 338         instance = instances.putIfAbsent(currencyCode, currencyVal);
 339         return (instance != null ? instance : currencyVal);
 340     }
 341 
 342     /**
 343      * Returns the <code>Currency</code> instance for the country of the
 344      * given locale. The language and variant components of the locale
 345      * are ignored. The result may vary over time, as countries change their
 346      * currencies. For example, for the original member countries of the
 347      * European Monetary Union, the method returns the old national currencies
 348      * until December 31, 2001, and the Euro from January 1, 2002, local time
 349      * of the respective countries.
 350      * <p>
 351      * The method returns <code>null</code> for territories that don't
 352      * have a currency, such as Antarctica.
 353      *
 354      * @param locale the locale for whose country a <code>Currency</code>
 355      * instance is needed
 356      * @return the <code>Currency</code> instance for the country of the given
 357      * locale, or {@code null}
 358      * @exception NullPointerException if <code>locale</code>
 359      * is {@code null}
 360      * @exception IllegalArgumentException if the country of the given {@code locale}
 361      * is not a supported ISO 3166 country code.
 362      */
 363     public static Currency getInstance(Locale locale) {
 364         String country = locale.getCountry();
 365         if (country == null) {
 366             throw new NullPointerException();
 367         }
 368 
 369         if (country.length() != 2) {
 370             throw new IllegalArgumentException();
 371         }
 372 
 373         char char1 = country.charAt(0);
 374         char char2 = country.charAt(1);
 375         int tableEntry = getMainTableEntry(char1, char2);
 376         if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK
 377                     && tableEntry != INVALID_COUNTRY_ENTRY) {
 378             char finalChar = (char) ((tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK) + 'A');
 379             int defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT;
 380             int numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT;
 381             StringBuilder sb = new StringBuilder(country);
 382             sb.append(finalChar);
 383             return getInstance(sb.toString(), defaultFractionDigits, numericCode);
 384         } else {
 385             // special cases
 386             if (tableEntry == INVALID_COUNTRY_ENTRY) {
 387                 throw new IllegalArgumentException();
 388             }
 389             if (tableEntry == COUNTRY_WITHOUT_CURRENCY_ENTRY) {
 390                 return null;
 391             } else {
 392                 int index = SpecialCaseEntry.toIndex(tableEntry);
 393                 SpecialCaseEntry scEntry = specialCasesList.get(index);
 394                 if (scEntry.cutOverTime == Long.MAX_VALUE
 395                         || System.currentTimeMillis() < scEntry.cutOverTime) {
 396                     return getInstance(scEntry.oldCurrency,
 397                             scEntry.oldCurrencyFraction,
 398                             scEntry.oldCurrencyNumericCode);
 399                 } else {
 400                     return getInstance(scEntry.newCurrency,
 401                             scEntry.newCurrencyFraction,
 402                             scEntry.newCurrencyNumericCode);
 403                 }
 404             }
 405         }
 406     }
 407 
 408     /**
 409      * Gets the set of available currencies.  The returned set of currencies
 410      * contains all of the available currencies, which may include currencies
 411      * that represent obsolete ISO 4217 codes.  The set can be modified
 412      * without affecting the available currencies in the runtime.
 413      *
 414      * @return the set of available currencies.  If there is no currency
 415      *    available in the runtime, the returned set is empty.
 416      * @since 1.7
 417      */
 418     public static Set<Currency> getAvailableCurrencies() {
 419         synchronized(Currency.class) {
 420             if (available == null) {
 421                 available = new HashSet<>(256);
 422 
 423                 // Add simple currencies first
 424                 for (char c1 = 'A'; c1 <= 'Z'; c1 ++) {
 425                     for (char c2 = 'A'; c2 <= 'Z'; c2 ++) {
 426                         int tableEntry = getMainTableEntry(c1, c2);
 427                         if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK
 428                              && tableEntry != INVALID_COUNTRY_ENTRY) {
 429                             char finalChar = (char) ((tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK) + 'A');
 430                             int defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT;
 431                             int numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT;
 432                             StringBuilder sb = new StringBuilder();
 433                             sb.append(c1);
 434                             sb.append(c2);
 435                             sb.append(finalChar);
 436                             available.add(getInstance(sb.toString(), defaultFractionDigits, numericCode));
 437                         } else if ((tableEntry & COUNTRY_TYPE_MASK) == SPECIAL_CASE_COUNTRY_MASK
 438                                 && tableEntry != INVALID_COUNTRY_ENTRY
 439                                 && tableEntry != COUNTRY_WITHOUT_CURRENCY_ENTRY) {
 440                             int index = SpecialCaseEntry.toIndex(tableEntry);
 441                             SpecialCaseEntry scEntry = specialCasesList.get(index);
 442 
 443                             if (scEntry.cutOverTime == Long.MAX_VALUE
 444                                     || System.currentTimeMillis() < scEntry.cutOverTime) {
 445                                 available.add(getInstance(scEntry.oldCurrency,
 446                                         scEntry.oldCurrencyFraction,
 447                                         scEntry.oldCurrencyNumericCode));
 448                             } else {
 449                                 available.add(getInstance(scEntry.newCurrency,
 450                                         scEntry.newCurrencyFraction,
 451                                         scEntry.newCurrencyNumericCode));
 452                             }
 453                         }
 454                     }
 455                 }
 456 
 457                 // Now add other currencies
 458                 for (OtherCurrencyEntry entry : otherCurrenciesList) {
 459                     available.add(getInstance(entry.currencyCode));
 460                 }
 461             }
 462         }
 463 
 464         @SuppressWarnings("unchecked")
 465         Set<Currency> result = (Set<Currency>) available.clone();
 466         return result;
 467     }
 468 
 469     /**
 470      * Gets the ISO 4217 currency code of this currency.
 471      *
 472      * @return the ISO 4217 currency code of this currency.
 473      */
 474     public String getCurrencyCode() {
 475         return currencyCode;
 476     }
 477 
 478     /**
 479      * Gets the symbol of this currency for the default
 480      * {@link Locale.Category#DISPLAY DISPLAY} locale.
 481      * For example, for the US Dollar, the symbol is "$" if the default
 482      * locale is the US, while for other locales it may be "US$". If no
 483      * symbol can be determined, the ISO 4217 currency code is returned.
 484      * <p>
 485      * This is equivalent to calling
 486      * {@link #getSymbol(Locale)
 487      *     getSymbol(Locale.getDefault(Locale.Category.DISPLAY))}.
 488      *
 489      * @return the symbol of this currency for the default
 490      *     {@link Locale.Category#DISPLAY DISPLAY} locale
 491      */
 492     public String getSymbol() {
 493         return getSymbol(Locale.getDefault(Locale.Category.DISPLAY));
 494     }
 495 
 496     /**
 497      * Gets the symbol of this currency for the specified locale.
 498      * For example, for the US Dollar, the symbol is "$" if the specified
 499      * locale is the US, while for other locales it may be "US$". If no
 500      * symbol can be determined, the ISO 4217 currency code is returned.
 501      *
 502      * @param locale the locale for which a display name for this currency is
 503      * needed
 504      * @return the symbol of this currency for the specified locale
 505      * @exception NullPointerException if <code>locale</code> is null
 506      */
 507     public String getSymbol(Locale locale) {
 508         LocaleServiceProviderPool pool =
 509             LocaleServiceProviderPool.getPool(CurrencyNameProvider.class);
 510         String symbol = pool.getLocalizedObject(
 511                                 CurrencyNameGetter.INSTANCE,
 512                                 locale, currencyCode, SYMBOL);
 513         if (symbol != null) {
 514             return symbol;
 515         }
 516 
 517         // use currency code as symbol of last resort
 518         return currencyCode;
 519     }
 520 
 521     /**
 522      * Gets the default number of fraction digits used with this currency.
 523      * Note that the number of fraction digits is the same as ISO 4217's
 524      * minor unit for the currency.
 525      * For example, the default number of fraction digits for the Euro is 2,
 526      * while for the Japanese Yen it's 0.
 527      * In the case of pseudo-currencies, such as IMF Special Drawing Rights,
 528      * -1 is returned.
 529      *
 530      * @return the default number of fraction digits used with this currency
 531     */
 532     public int getDefaultFractionDigits() {
 533         return defaultFractionDigits;
 534     }
 535 
 536     /**
 537      * Returns the ISO 4217 numeric code of this currency.
 538      *
 539      * @return the ISO 4217 numeric code of this currency
 540      * @since 1.7
 541      */
 542     public int getNumericCode() {
 543         return numericCode;
 544     }
 545 
 546     /**
 547      * Gets the name that is suitable for displaying this currency for
 548      * the default {@link Locale.Category#DISPLAY DISPLAY} locale.
 549      * If there is no suitable display name found
 550      * for the default locale, the ISO 4217 currency code is returned.
 551      * <p>
 552      * This is equivalent to calling
 553      * {@link #getDisplayName(Locale)
 554      *     getDisplayName(Locale.getDefault(Locale.Category.DISPLAY))}.
 555      *
 556      * @return the display name of this currency for the default
 557      *     {@link Locale.Category#DISPLAY DISPLAY} locale
 558      * @since 1.7
 559      */
 560     public String getDisplayName() {
 561         return getDisplayName(Locale.getDefault(Locale.Category.DISPLAY));
 562     }
 563 
 564     /**
 565      * Gets the name that is suitable for displaying this currency for
 566      * the specified locale.  If there is no suitable display name found
 567      * for the specified locale, the ISO 4217 currency code is returned.
 568      *
 569      * @param locale the locale for which a display name for this currency is
 570      * needed
 571      * @return the display name of this currency for the specified locale
 572      * @exception NullPointerException if <code>locale</code> is null
 573      * @since 1.7
 574      */
 575     public String getDisplayName(Locale locale) {
 576         LocaleServiceProviderPool pool =
 577             LocaleServiceProviderPool.getPool(CurrencyNameProvider.class);
 578         String result = pool.getLocalizedObject(
 579                                 CurrencyNameGetter.INSTANCE,
 580                                 locale, currencyCode, DISPLAYNAME);
 581         if (result != null) {
 582             return result;
 583         }
 584 
 585         // use currency code as symbol of last resort
 586         return currencyCode;
 587     }
 588 
 589     /**
 590      * Returns the ISO 4217 currency code of this currency.
 591      *
 592      * @return the ISO 4217 currency code of this currency
 593      */
 594     @Override
 595     public String toString() {
 596         return currencyCode;
 597     }
 598 
 599     /**
 600      * Resolves instances being deserialized to a single instance per currency.
 601      */
 602     private Object readResolve() {
 603         return getInstance(currencyCode);
 604     }
 605 
 606     /**
 607      * Gets the main table entry for the country whose country code consists
 608      * of char1 and char2.
 609      */
 610     private static int getMainTableEntry(char char1, char char2) {
 611         if (char1 < 'A' || char1 > 'Z' || char2 < 'A' || char2 > 'Z') {
 612             throw new IllegalArgumentException();
 613         }
 614         return mainTable[(char1 - 'A') * A_TO_Z + (char2 - 'A')];
 615     }
 616 
 617     /**
 618      * Sets the main table entry for the country whose country code consists
 619      * of char1 and char2.
 620      */
 621     private static void setMainTableEntry(char char1, char char2, int entry) {
 622         if (char1 < 'A' || char1 > 'Z' || char2 < 'A' || char2 > 'Z') {
 623             throw new IllegalArgumentException();
 624         }
 625         mainTable[(char1 - 'A') * A_TO_Z + (char2 - 'A')] = entry;
 626     }
 627 
 628     /**
 629      * Obtains a localized currency names from a CurrencyNameProvider
 630      * implementation.
 631      */
 632     private static class CurrencyNameGetter
 633         implements LocaleServiceProviderPool.LocalizedObjectGetter<CurrencyNameProvider,
 634                                                                    String> {
 635         private static final CurrencyNameGetter INSTANCE = new CurrencyNameGetter();
 636 
 637         @Override
 638         public String getObject(CurrencyNameProvider currencyNameProvider,
 639                                 Locale locale,
 640                                 String key,
 641                                 Object... params) {
 642             assert params.length == 1;
 643             int type = (Integer)params[0];
 644 
 645             switch(type) {
 646             case SYMBOL:
 647                 return currencyNameProvider.getSymbol(key, locale);
 648             case DISPLAYNAME:
 649                 return currencyNameProvider.getDisplayName(key, locale);
 650             default:
 651                 assert false; // shouldn't happen
 652             }
 653 
 654             return null;
 655         }
 656     }
 657 
 658     private static int[] readIntArray(DataInputStream dis, int count) throws IOException {
 659         int[] ret = new int[count];
 660         for (int i = 0; i < count; i++) {
 661             ret[i] = dis.readInt();
 662         }
 663 
 664         return ret;
 665     }
 666 
 667     private static List<SpecialCaseEntry> readSpecialCases(DataInputStream dis,
 668             int count)
 669             throws IOException {
 670 
 671         List<SpecialCaseEntry> list = new ArrayList<>(count);
 672         long cutOverTime;
 673         String oldCurrency;
 674         String newCurrency;
 675         int oldCurrencyFraction;
 676         int newCurrencyFraction;
 677         int oldCurrencyNumericCode;
 678         int newCurrencyNumericCode;
 679 
 680         for (int i = 0; i < count; i++) {
 681             cutOverTime = dis.readLong();
 682             oldCurrency = dis.readUTF();
 683             newCurrency = dis.readUTF();
 684             oldCurrencyFraction = dis.readInt();
 685             newCurrencyFraction = dis.readInt();
 686             oldCurrencyNumericCode = dis.readInt();
 687             newCurrencyNumericCode = dis.readInt();
 688             SpecialCaseEntry sc = new SpecialCaseEntry(cutOverTime,
 689                     oldCurrency, newCurrency,
 690                     oldCurrencyFraction, newCurrencyFraction,
 691                     oldCurrencyNumericCode, newCurrencyNumericCode);
 692             list.add(sc);
 693         }
 694         return list;
 695     }
 696         
 697     private static List<OtherCurrencyEntry> readOtherCurrencies(DataInputStream dis,
 698             int count)
 699             throws IOException {
 700 
 701         List<OtherCurrencyEntry> list = new ArrayList<>(count);
 702         String currencyCode;
 703         int fraction;
 704         int numericCode;
 705 
 706         for (int i = 0; i < count; i++) {
 707             currencyCode = dis.readUTF();
 708             fraction = dis.readInt();
 709             numericCode = dis.readInt();
 710             OtherCurrencyEntry oc = new OtherCurrencyEntry(currencyCode,
 711                     fraction,
 712                     numericCode);
 713             list.add(oc);
 714         }
 715         return list;
 716     }
 717 
 718     /**
 719      * Replaces currency data found in the currencydata.properties file
 720      *
 721      * @param pattern regex pattern for the properties
 722      * @param ctry country code
 723      * @param curdata currency data.  This is a comma separated string that
 724      *    consists of "three-letter alphabet code", "three-digit numeric code",
 725      *    and "one-digit (0-9) default fraction digit".
 726      *    For example, "JPZ,392,0".
 727      *    An optional UTC date can be appended to the string (comma separated)
 728      *    to allow a currency change take effect after date specified.
 729      *    For example, "JP=JPZ,999,0,2014-01-01T00:00:00" has no effect unless
 730      *    UTC time is past 1st January 2014 00:00:00 GMT.
 731      */
 732     private static void replaceCurrencyData(Pattern pattern, String ctry, String curdata) {
 733 
 734         if (ctry.length() != 2) {
 735             // ignore invalid country code
 736             info("currency.properties entry for " + ctry +
 737                     " is ignored because of the invalid country code.", null);
 738             return;
 739         }
 740 
 741         Matcher m = pattern.matcher(curdata);
 742         if (!m.find() || (m.group(4) == null && countOccurrences(curdata, ',') >= 3)) {
 743             // format is not recognized.  ignore the data
 744             // if group(4) date string is null and we've 4 values, bad date value
 745             info("currency.properties entry for " + ctry +
 746                     " ignored because the value format is not recognized.", null);
 747             return;
 748         }
 749 
 750         try {
 751             if (m.group(4) != null && !isPastCutoverDate(m.group(4))) {
 752                 info("currency.properties entry for " + ctry +
 753                         " ignored since cutover date has not passed :" + curdata, null);
 754                 return;
 755             }
 756         } catch (ParseException ex) {
 757             info("currency.properties entry for " + ctry +
 758                         " ignored since exception encountered :" + ex.getMessage(), null);
 759             return;
 760         }
 761 
 762         String code = m.group(1);
 763         int numeric = Integer.parseInt(m.group(2));
 764         int entry = numeric << NUMERIC_CODE_SHIFT;
 765         int fraction = Integer.parseInt(m.group(3));
 766         if (fraction > SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS) {
 767             info("currency.properties entry for " + ctry +
 768                 " ignored since the fraction is more than " +
 769                 SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS + ":" + curdata, null);
 770             return;
 771         }
 772 
 773         int index = SpecialCaseEntry.indexOf(code, fraction, numeric);
 774 
 775         /* if a country switches from simple case to special case or
 776          * one special case to other special case which is not present
 777          * in the sc arrays then insert the new entry in special case arrays
 778          */
 779         if (index == -1 && (ctry.charAt(0) != code.charAt(0)
 780                 || ctry.charAt(1) != code.charAt(1))) {
 781 
 782             specialCasesList.add(new SpecialCaseEntry(code, fraction, numeric));
 783             index = specialCasesList.size() - 1;
 784         }
 785 
 786         if (index == -1) {
 787             // simple case
 788             entry |= (fraction << SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT)
 789                     | (code.charAt(2) - 'A');
 790         } else {
 791             // special case
 792             entry = SPECIAL_CASE_COUNTRY_MASK
 793                     | (index + SPECIAL_CASE_COUNTRY_INDEX_DELTA);
 794         }
 795         setMainTableEntry(ctry.charAt(0), ctry.charAt(1), entry);
 796     }
 797 
 798     private static boolean isPastCutoverDate(String s) throws ParseException {
 799         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT);
 800         format.setTimeZone(TimeZone.getTimeZone("UTC"));
 801         format.setLenient(false);
 802         long time = format.parse(s.trim()).getTime();
 803         return System.currentTimeMillis() > time;
 804 
 805     }
 806 
 807     private static int countOccurrences(String value, char match) {
 808         int count = 0;
 809         for (char c : value.toCharArray()) {
 810             if (c == match) {
 811                ++count;
 812             }
 813         }
 814         return count;
 815     }
 816 
 817     private static void info(String message, Throwable t) {
 818         PlatformLogger logger = PlatformLogger.getLogger("java.util.Currency");
 819         if (logger.isLoggable(PlatformLogger.Level.INFO)) {
 820             if (t != null) {
 821                 logger.info(message, t);
 822             } else {
 823                 logger.info(message);
 824             }
 825         }
 826     }
 827 
 828     /* Used to represent a special case currency entry
 829      * - cutOverTime: cut-over time in millis as returned by
 830      *   System.currentTimeMillis for special case countries that are changing
 831      *   currencies; Long.MAX_VALUE for countries that are not changing currencies
 832      * - oldCurrency: old currencies for special case countries
 833      * - newCurrency: new currencies for special case countries that are
 834      *   changing currencies; null for others
 835      * - oldCurrencyFraction: default fraction digits for old currencies
 836      * - newCurrencyFraction: default fraction digits for new currencies, 0 for
 837      *   countries that are not changing currencies
 838      * - oldCurrencyNumericCode: numeric code for old currencies
 839      * - newCurrencyNumericCode: numeric code for new currencies, 0 for countries
 840      *   that are not changing currencies
 841     */
 842     private static class SpecialCaseEntry {
 843 
 844         final private long cutOverTime;
 845         final private String oldCurrency;
 846         final private String newCurrency;
 847         final private int oldCurrencyFraction;
 848         final private int newCurrencyFraction;
 849         final private int oldCurrencyNumericCode;
 850         final private int newCurrencyNumericCode;
 851 
 852         private SpecialCaseEntry(long cutOverTime, String oldCurrency, String newCurrency,
 853                 int oldCurrencyFraction, int newCurrencyFraction,
 854                 int oldCurrencyNumericCode, int newCurrencyNumericCode) {
 855             this.cutOverTime = cutOverTime;
 856             this.oldCurrency = oldCurrency;
 857             this.newCurrency = newCurrency;
 858             this.oldCurrencyFraction = oldCurrencyFraction;
 859             this.newCurrencyFraction = newCurrencyFraction;
 860             this.oldCurrencyNumericCode = oldCurrencyNumericCode;
 861             this.newCurrencyNumericCode = newCurrencyNumericCode;
 862         }
 863 
 864         private SpecialCaseEntry(String currencyCode, int fraction,
 865                 int numericCode) {
 866             this(Long.MAX_VALUE, currencyCode, "", fraction, 0, numericCode, 0);
 867         }
 868 
 869         //get the index of the special case entry
 870         private static int indexOf(String code, int fraction, int numeric) {
 871             int size = specialCasesList.size();
 872             for (int index = 0; index < size; index++) {
 873                 SpecialCaseEntry scEntry = specialCasesList.get(index);
 874                 if (scEntry.oldCurrency.equals(code)
 875                         && scEntry.oldCurrencyFraction == fraction
 876                         && scEntry.oldCurrencyNumericCode == numeric
 877                         && scEntry.cutOverTime == Long.MAX_VALUE) {
 878                     return index;
 879                 }
 880             }
 881             return -1;
 882         }
 883 
 884         // get the fraction and numericCode of the sc currencycode
 885         private static int[] findEntry(String code) {
 886             int[] fractionAndNumericCode = null;
 887             int size = specialCasesList.size();
 888             for (int index = 0; index < size; index++) {
 889                 SpecialCaseEntry scEntry = specialCasesList.get(index);
 890                 if (scEntry.oldCurrency.equals(code) && (scEntry.cutOverTime == Long.MAX_VALUE
 891                         || System.currentTimeMillis() < scEntry.cutOverTime)) {
 892                     //consider only when there is no new currency or cutover time is not passed
 893                     fractionAndNumericCode = new int[2];
 894                     fractionAndNumericCode[0] = scEntry.oldCurrencyFraction;
 895                     fractionAndNumericCode[1] = scEntry.oldCurrencyNumericCode;
 896                     break;
 897                 } else if (scEntry.newCurrency.equals(code)
 898                         && System.currentTimeMillis() >= scEntry.cutOverTime) {
 899                     //consider only if the cutover time is passed
 900                     fractionAndNumericCode = new int[2];
 901                     fractionAndNumericCode[0] = scEntry.newCurrencyFraction;
 902                     fractionAndNumericCode[1] = scEntry.newCurrencyNumericCode;
 903                     break;
 904                 }
 905             }
 906             return fractionAndNumericCode;
 907         }
 908 
 909         // convert the special case entry to sc arrays index
 910         private static int toIndex(int tableEntry) {
 911             return (tableEntry & SPECIAL_CASE_COUNTRY_INDEX_MASK) - SPECIAL_CASE_COUNTRY_INDEX_DELTA;
 912         }
 913 
 914     }
 915 
 916     /* Used to represent Other currencies
 917      * - currencyCode: currency codes that are not the main currency
 918      *   of a simple country
 919      * - otherCurrenciesDFD: decimal format digits for other currencies
 920      * - otherCurrenciesNumericCode: numeric code for other currencies
 921      */
 922     private static class OtherCurrencyEntry {
 923 
 924         final private String currencyCode;
 925         final private int fraction;
 926         final private int numericCode;
 927 
 928         private OtherCurrencyEntry(String currencyCode, int fraction,
 929                 int numericCode) {
 930             this.currencyCode = currencyCode;
 931             this.fraction = fraction;
 932             this.numericCode = numericCode;
 933         }
 934 
 935         //get the instance of the other currency code
 936         private static OtherCurrencyEntry findEntry(String code) {
 937             int size = otherCurrenciesList.size();
 938             for (int index = 0; index < size; index++) {
 939                 OtherCurrencyEntry ocEntry = otherCurrenciesList.get(index);
 940                 if (ocEntry.currencyCode.equalsIgnoreCase(code)) {
 941                     return ocEntry;
 942                 }
 943             }
 944             return null;
 945         }
 946 
 947     }
 948 
 949 }
 950