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