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.FileReader; 32 import java.io.InputStream; 33 import java.io.IOException; 34 import java.io.Serializable; 35 import java.security.AccessController; 36 import java.security.PrivilegedAction; 37 import java.text.ParseException; 38 import java.text.SimpleDateFormat; 39 import java.util.concurrent.ConcurrentHashMap; 40 import java.util.concurrent.ConcurrentMap; 41 import java.util.regex.Pattern; 42 import java.util.regex.Matcher; 43 import java.util.spi.CurrencyNameProvider; 44 import sun.util.locale.provider.CalendarDataUtility; 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 * If the specified {@code locale} contains "cu" and/or "rg" 352 * <a href="./Locale.html#def_locale_extension">Unicode extensions</a>, 353 * the instance returned from this method reflects 354 * the values specified with those extensions. If both "cu" and "rg" are 355 * specified, the currency from the "cu" extension supersedes the implicit one 356 * from the "rg" extension. 357 * <p> 358 * The method returns <code>null</code> for territories that don't 359 * have a currency, such as Antarctica. 360 * 361 * @param locale the locale for whose country a <code>Currency</code> 362 * instance is needed 363 * @return the <code>Currency</code> instance for the country of the given 364 * locale, or {@code null} 365 * @exception NullPointerException if <code>locale</code> 366 * is {@code null} 367 * @exception IllegalArgumentException if the country of the given {@code locale} 368 * is not a supported ISO 3166 country code. 369 */ 370 public static Currency getInstance(Locale locale) { 371 // check for locale overrides 372 String override = locale.getUnicodeLocaleType("cu"); 373 if (override != null) { 374 try { 375 return getInstance(override.toUpperCase(Locale.ROOT)); 376 } catch (IllegalArgumentException iae) { 377 // override currency is invalid. Fall through. 378 } 379 } 380 381 String country = CalendarDataUtility.findRegionOverride(locale).getCountry(); 382 383 if (country == null || !country.matches("^[a-zA-Z]{2}$")) { 384 throw new IllegalArgumentException(); 385 } 386 387 char char1 = country.charAt(0); 388 char char2 = country.charAt(1); 389 int tableEntry = getMainTableEntry(char1, char2); 390 if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK 391 && tableEntry != INVALID_COUNTRY_ENTRY) { 392 char finalChar = (char) ((tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK) + 'A'); 393 int defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT; 394 int numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT; 395 StringBuilder sb = new StringBuilder(country); 396 sb.append(finalChar); 397 return getInstance(sb.toString(), defaultFractionDigits, numericCode); 398 } else { 399 // special cases 400 if (tableEntry == INVALID_COUNTRY_ENTRY) { 401 throw new IllegalArgumentException(); 402 } 403 if (tableEntry == COUNTRY_WITHOUT_CURRENCY_ENTRY) { 404 return null; 405 } else { 406 int index = SpecialCaseEntry.toIndex(tableEntry); 407 SpecialCaseEntry scEntry = specialCasesList.get(index); 408 if (scEntry.cutOverTime == Long.MAX_VALUE 409 || System.currentTimeMillis() < scEntry.cutOverTime) { 410 return getInstance(scEntry.oldCurrency, 411 scEntry.oldCurrencyFraction, 412 scEntry.oldCurrencyNumericCode); 413 } else { 414 return getInstance(scEntry.newCurrency, 415 scEntry.newCurrencyFraction, 416 scEntry.newCurrencyNumericCode); 417 } 418 } 419 } 420 } 421 422 /** 423 * Gets the set of available currencies. The returned set of currencies 424 * contains all of the available currencies, which may include currencies 425 * that represent obsolete ISO 4217 codes. The set can be modified 426 * without affecting the available currencies in the runtime. 427 * 428 * @return the set of available currencies. If there is no currency 429 * available in the runtime, the returned set is empty. 430 * @since 1.7 431 */ 432 public static Set<Currency> getAvailableCurrencies() { 433 synchronized(Currency.class) { 434 if (available == null) { 435 available = new HashSet<>(256); 436 437 // Add simple currencies first 438 for (char c1 = 'A'; c1 <= 'Z'; c1 ++) { 439 for (char c2 = 'A'; c2 <= 'Z'; c2 ++) { 440 int tableEntry = getMainTableEntry(c1, c2); 441 if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK 442 && tableEntry != INVALID_COUNTRY_ENTRY) { 443 char finalChar = (char) ((tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK) + 'A'); 444 int defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT; 445 int numericCode = (tableEntry & NUMERIC_CODE_MASK) >> NUMERIC_CODE_SHIFT; 446 StringBuilder sb = new StringBuilder(); 447 sb.append(c1); 448 sb.append(c2); 449 sb.append(finalChar); 450 available.add(getInstance(sb.toString(), defaultFractionDigits, numericCode)); 451 } else if ((tableEntry & COUNTRY_TYPE_MASK) == SPECIAL_CASE_COUNTRY_MASK 452 && tableEntry != INVALID_COUNTRY_ENTRY 453 && tableEntry != COUNTRY_WITHOUT_CURRENCY_ENTRY) { 454 int index = SpecialCaseEntry.toIndex(tableEntry); 455 SpecialCaseEntry scEntry = specialCasesList.get(index); 456 457 if (scEntry.cutOverTime == Long.MAX_VALUE 458 || System.currentTimeMillis() < scEntry.cutOverTime) { 459 available.add(getInstance(scEntry.oldCurrency, 460 scEntry.oldCurrencyFraction, 461 scEntry.oldCurrencyNumericCode)); 462 } else { 463 available.add(getInstance(scEntry.newCurrency, 464 scEntry.newCurrencyFraction, 465 scEntry.newCurrencyNumericCode)); 466 } 467 } 468 } 469 } 470 471 // Now add other currencies 472 for (OtherCurrencyEntry entry : otherCurrenciesList) { 473 available.add(getInstance(entry.currencyCode)); 474 } 475 } 476 } 477 478 @SuppressWarnings("unchecked") 479 Set<Currency> result = (Set<Currency>) available.clone(); 480 return result; 481 } 482 483 /** 484 * Gets the ISO 4217 currency code of this currency. 485 * 486 * @return the ISO 4217 currency code of this currency. 487 */ 488 public String getCurrencyCode() { 489 return currencyCode; 490 } 491 492 /** 493 * Gets the symbol of this currency for the default 494 * {@link Locale.Category#DISPLAY DISPLAY} locale. 495 * For example, for the US Dollar, the symbol is "$" if the default 496 * locale is the US, while for other locales it may be "US$". If no 497 * symbol can be determined, the ISO 4217 currency code is returned. 498 * <p> 499 * If the default {@link Locale.Category#DISPLAY DISPLAY} locale 500 * contains "rg" (region override) 501 * <a href="./Locale.html#def_locale_extension">Unicode extension</a>, 502 * the symbol returned from this method reflects 503 * the value specified with that extension. 504 * <p> 505 * This is equivalent to calling 506 * {@link #getSymbol(Locale) 507 * getSymbol(Locale.getDefault(Locale.Category.DISPLAY))}. 508 * 509 * @return the symbol of this currency for the default 510 * {@link Locale.Category#DISPLAY DISPLAY} locale 511 */ 512 public String getSymbol() { 513 return getSymbol(Locale.getDefault(Locale.Category.DISPLAY)); 514 } 515 516 /** 517 * Gets the symbol of this currency for the specified locale. 518 * For example, for the US Dollar, the symbol is "$" if the specified 519 * locale is the US, while for other locales it may be "US$". If no 520 * symbol can be determined, the ISO 4217 currency code is returned. 521 * <p> 522 * If the specified {@code locale} contains "rg" (region override) 523 * <a href="./Locale.html#def_locale_extension">Unicode extension</a>, 524 * the symbol returned from this method reflects 525 * the value specified with that extension. 526 * 527 * @param locale the locale for which a display name for this currency is 528 * needed 529 * @return the symbol of this currency for the specified locale 530 * @exception NullPointerException if <code>locale</code> is null 531 */ 532 public String getSymbol(Locale locale) { 533 LocaleServiceProviderPool pool = 534 LocaleServiceProviderPool.getPool(CurrencyNameProvider.class); 535 locale = CalendarDataUtility.findRegionOverride(locale); 536 String symbol = pool.getLocalizedObject( 537 CurrencyNameGetter.INSTANCE, 538 locale, currencyCode, SYMBOL); 539 if (symbol != null) { 540 return symbol; 541 } 542 543 // use currency code as symbol of last resort 544 return currencyCode; 545 } 546 547 /** 548 * Gets the default number of fraction digits used with this currency. 549 * Note that the number of fraction digits is the same as ISO 4217's 550 * minor unit for the currency. 551 * For example, the default number of fraction digits for the Euro is 2, 552 * while for the Japanese Yen it's 0. 553 * In the case of pseudo-currencies, such as IMF Special Drawing Rights, 554 * -1 is returned. 555 * 556 * @return the default number of fraction digits used with this currency 557 */ 558 public int getDefaultFractionDigits() { 559 return defaultFractionDigits; 560 } 561 562 /** 563 * Returns the ISO 4217 numeric code of this currency. 564 * 565 * @return the ISO 4217 numeric code of this currency 566 * @since 1.7 567 */ 568 public int getNumericCode() { 569 return numericCode; 570 } 571 572 /** 573 * Returns the 3 digit ISO 4217 numeric code of this currency as a {@code String}. 574 * Unlike {@link getNumericCode()}, which returns the numeric code as {@code int}, 575 * this method always returns the numeric code as a 3 digit string. 576 * e.g. a numeric value of 32 would be returned as "032", 577 * and a numeric value of 6 would be returned as "006". 578 * 579 * @return the 3 digit ISO 4217 numeric code of this currency as a {@code String} 580 * @since 9 581 */ 582 public String getNumericCodeAsString() { 583 /* numeric code could be returned as a 3 digit string simply by using 584 String.format("%03d",numericCode); which uses regex to parse the format, 585 "%03d" in this case. Parsing a regex gives an extra performance overhead, 586 so String.format() approach is avoided in this scenario. 587 */ 588 if (numericCode < 100) { 589 StringBuilder sb = new StringBuilder(); 590 sb.append('0'); 591 if (numericCode < 10) { 592 sb.append('0'); 593 } 594 return sb.append(numericCode).toString(); 595 } 596 return String.valueOf(numericCode); 597 } 598 599 /** 600 * Gets the name that is suitable for displaying this currency for 601 * the default {@link Locale.Category#DISPLAY DISPLAY} locale. 602 * If there is no suitable display name found 603 * for the default locale, the ISO 4217 currency code is returned. 604 * <p> 605 * This is equivalent to calling 606 * {@link #getDisplayName(Locale) 607 * getDisplayName(Locale.getDefault(Locale.Category.DISPLAY))}. 608 * 609 * @return the display name of this currency for the default 610 * {@link Locale.Category#DISPLAY DISPLAY} locale 611 * @since 1.7 612 */ 613 public String getDisplayName() { 614 return getDisplayName(Locale.getDefault(Locale.Category.DISPLAY)); 615 } 616 617 /** 618 * Gets the name that is suitable for displaying this currency for 619 * the specified locale. If there is no suitable display name found 620 * for the specified locale, the ISO 4217 currency code is returned. 621 * 622 * @param locale the locale for which a display name for this currency is 623 * needed 624 * @return the display name of this currency for the specified locale 625 * @exception NullPointerException if <code>locale</code> is null 626 * @since 1.7 627 */ 628 public String getDisplayName(Locale locale) { 629 LocaleServiceProviderPool pool = 630 LocaleServiceProviderPool.getPool(CurrencyNameProvider.class); 631 String result = pool.getLocalizedObject( 632 CurrencyNameGetter.INSTANCE, 633 locale, currencyCode, DISPLAYNAME); 634 if (result != null) { 635 return result; 636 } 637 638 // use currency code as symbol of last resort 639 return currencyCode; 640 } 641 642 /** 643 * Returns the ISO 4217 currency code of this currency. 644 * 645 * @return the ISO 4217 currency code of this currency 646 */ 647 @Override 648 public String toString() { 649 return currencyCode; 650 } 651 652 /** 653 * Resolves instances being deserialized to a single instance per currency. 654 */ 655 private Object readResolve() { 656 return getInstance(currencyCode); 657 } 658 659 /** 660 * Gets the main table entry for the country whose country code consists 661 * of char1 and char2. 662 */ 663 private static int getMainTableEntry(char char1, char char2) { 664 if (char1 < 'A' || char1 > 'Z' || char2 < 'A' || char2 > 'Z') { 665 throw new IllegalArgumentException(); 666 } 667 return mainTable[(char1 - 'A') * A_TO_Z + (char2 - 'A')]; 668 } 669 670 /** 671 * Sets the main table entry for the country whose country code consists 672 * of char1 and char2. 673 */ 674 private static void setMainTableEntry(char char1, char char2, int entry) { 675 if (char1 < 'A' || char1 > 'Z' || char2 < 'A' || char2 > 'Z') { 676 throw new IllegalArgumentException(); 677 } 678 mainTable[(char1 - 'A') * A_TO_Z + (char2 - 'A')] = entry; 679 } 680 681 /** 682 * Obtains a localized currency names from a CurrencyNameProvider 683 * implementation. 684 */ 685 private static class CurrencyNameGetter 686 implements LocaleServiceProviderPool.LocalizedObjectGetter<CurrencyNameProvider, 687 String> { 688 private static final CurrencyNameGetter INSTANCE = new CurrencyNameGetter(); 689 690 @Override 691 public String getObject(CurrencyNameProvider currencyNameProvider, 692 Locale locale, 693 String key, 694 Object... params) { 695 assert params.length == 1; 696 int type = (Integer)params[0]; 697 698 switch(type) { 699 case SYMBOL: 700 return currencyNameProvider.getSymbol(key, locale); 701 case DISPLAYNAME: 702 return currencyNameProvider.getDisplayName(key, locale); 703 default: 704 assert false; // shouldn't happen 705 } 706 707 return null; 708 } 709 } 710 711 private static int[] readIntArray(DataInputStream dis, int count) throws IOException { 712 int[] ret = new int[count]; 713 for (int i = 0; i < count; i++) { 714 ret[i] = dis.readInt(); 715 } 716 717 return ret; 718 } 719 720 private static List<SpecialCaseEntry> readSpecialCases(DataInputStream dis, 721 int count) 722 throws IOException { 723 724 List<SpecialCaseEntry> list = new ArrayList<>(count); 725 long cutOverTime; 726 String oldCurrency; 727 String newCurrency; 728 int oldCurrencyFraction; 729 int newCurrencyFraction; 730 int oldCurrencyNumericCode; 731 int newCurrencyNumericCode; 732 733 for (int i = 0; i < count; i++) { 734 cutOverTime = dis.readLong(); 735 oldCurrency = dis.readUTF(); 736 newCurrency = dis.readUTF(); 737 oldCurrencyFraction = dis.readInt(); 738 newCurrencyFraction = dis.readInt(); 739 oldCurrencyNumericCode = dis.readInt(); 740 newCurrencyNumericCode = dis.readInt(); 741 SpecialCaseEntry sc = new SpecialCaseEntry(cutOverTime, 742 oldCurrency, newCurrency, 743 oldCurrencyFraction, newCurrencyFraction, 744 oldCurrencyNumericCode, newCurrencyNumericCode); 745 list.add(sc); 746 } 747 return list; 748 } 749 750 private static List<OtherCurrencyEntry> readOtherCurrencies(DataInputStream dis, 751 int count) 752 throws IOException { 753 754 List<OtherCurrencyEntry> list = new ArrayList<>(count); 755 String currencyCode; 756 int fraction; 757 int numericCode; 758 759 for (int i = 0; i < count; i++) { 760 currencyCode = dis.readUTF(); 761 fraction = dis.readInt(); 762 numericCode = dis.readInt(); 763 OtherCurrencyEntry oc = new OtherCurrencyEntry(currencyCode, 764 fraction, 765 numericCode); 766 list.add(oc); 767 } 768 return list; 769 } 770 771 /** 772 * Replaces currency data found in the currencydata.properties file 773 * 774 * @param pattern regex pattern for the properties 775 * @param ctry country code 776 * @param curdata currency data. This is a comma separated string that 777 * consists of "three-letter alphabet code", "three-digit numeric code", 778 * and "one-digit (0-9) default fraction digit". 779 * For example, "JPZ,392,0". 780 * An optional UTC date can be appended to the string (comma separated) 781 * to allow a currency change take effect after date specified. 782 * For example, "JP=JPZ,999,0,2014-01-01T00:00:00" has no effect unless 783 * UTC time is past 1st January 2014 00:00:00 GMT. 784 */ 785 private static void replaceCurrencyData(Pattern pattern, String ctry, String curdata) { 786 787 if (ctry.length() != 2) { 788 // ignore invalid country code 789 info("currency.properties entry for " + ctry + 790 " is ignored because of the invalid country code.", null); 791 return; 792 } 793 794 Matcher m = pattern.matcher(curdata); 795 if (!m.find() || (m.group(4) == null && countOccurrences(curdata, ',') >= 3)) { 796 // format is not recognized. ignore the data 797 // if group(4) date string is null and we've 4 values, bad date value 798 info("currency.properties entry for " + ctry + 799 " ignored because the value format is not recognized.", null); 800 return; 801 } 802 803 try { 804 if (m.group(4) != null && !isPastCutoverDate(m.group(4))) { 805 info("currency.properties entry for " + ctry + 806 " ignored since cutover date has not passed :" + curdata, null); 807 return; 808 } 809 } catch (ParseException ex) { 810 info("currency.properties entry for " + ctry + 811 " ignored since exception encountered :" + ex.getMessage(), null); 812 return; 813 } 814 815 String code = m.group(1); 816 int numeric = Integer.parseInt(m.group(2)); 817 int entry = numeric << NUMERIC_CODE_SHIFT; 818 int fraction = Integer.parseInt(m.group(3)); 819 if (fraction > SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS) { 820 info("currency.properties entry for " + ctry + 821 " ignored since the fraction is more than " + 822 SIMPLE_CASE_COUNTRY_MAX_DEFAULT_DIGITS + ":" + curdata, null); 823 return; 824 } 825 826 int index = SpecialCaseEntry.indexOf(code, fraction, numeric); 827 828 /* if a country switches from simple case to special case or 829 * one special case to other special case which is not present 830 * in the sc arrays then insert the new entry in special case arrays 831 */ 832 if (index == -1 && (ctry.charAt(0) != code.charAt(0) 833 || ctry.charAt(1) != code.charAt(1))) { 834 835 specialCasesList.add(new SpecialCaseEntry(code, fraction, numeric)); 836 index = specialCasesList.size() - 1; 837 } 838 839 if (index == -1) { 840 // simple case 841 entry |= (fraction << SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT) 842 | (code.charAt(2) - 'A'); 843 } else { 844 // special case 845 entry = SPECIAL_CASE_COUNTRY_MASK 846 | (index + SPECIAL_CASE_COUNTRY_INDEX_DELTA); 847 } 848 setMainTableEntry(ctry.charAt(0), ctry.charAt(1), entry); 849 } 850 851 private static boolean isPastCutoverDate(String s) throws ParseException { 852 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT); 853 format.setTimeZone(TimeZone.getTimeZone("UTC")); 854 format.setLenient(false); 855 long time = format.parse(s.trim()).getTime(); 856 return System.currentTimeMillis() > time; 857 858 } 859 860 private static int countOccurrences(String value, char match) { 861 int count = 0; 862 for (char c : value.toCharArray()) { 863 if (c == match) { 864 ++count; 865 } 866 } 867 return count; 868 } 869 870 private static void info(String message, Throwable t) { 871 PlatformLogger logger = PlatformLogger.getLogger("java.util.Currency"); 872 if (logger.isLoggable(PlatformLogger.Level.INFO)) { 873 if (t != null) { 874 logger.info(message, t); 875 } else { 876 logger.info(message); 877 } 878 } 879 } 880 881 /* Used to represent a special case currency entry 882 * - cutOverTime: cut-over time in millis as returned by 883 * System.currentTimeMillis for special case countries that are changing 884 * currencies; Long.MAX_VALUE for countries that are not changing currencies 885 * - oldCurrency: old currencies for special case countries 886 * - newCurrency: new currencies for special case countries that are 887 * changing currencies; null for others 888 * - oldCurrencyFraction: default fraction digits for old currencies 889 * - newCurrencyFraction: default fraction digits for new currencies, 0 for 890 * countries that are not changing currencies 891 * - oldCurrencyNumericCode: numeric code for old currencies 892 * - newCurrencyNumericCode: numeric code for new currencies, 0 for countries 893 * that are not changing currencies 894 */ 895 private static class SpecialCaseEntry { 896 897 final private long cutOverTime; 898 final private String oldCurrency; 899 final private String newCurrency; 900 final private int oldCurrencyFraction; 901 final private int newCurrencyFraction; 902 final private int oldCurrencyNumericCode; 903 final private int newCurrencyNumericCode; 904 905 private SpecialCaseEntry(long cutOverTime, String oldCurrency, String newCurrency, 906 int oldCurrencyFraction, int newCurrencyFraction, 907 int oldCurrencyNumericCode, int newCurrencyNumericCode) { 908 this.cutOverTime = cutOverTime; 909 this.oldCurrency = oldCurrency; 910 this.newCurrency = newCurrency; 911 this.oldCurrencyFraction = oldCurrencyFraction; 912 this.newCurrencyFraction = newCurrencyFraction; 913 this.oldCurrencyNumericCode = oldCurrencyNumericCode; 914 this.newCurrencyNumericCode = newCurrencyNumericCode; 915 } 916 917 private SpecialCaseEntry(String currencyCode, int fraction, 918 int numericCode) { 919 this(Long.MAX_VALUE, currencyCode, "", fraction, 0, numericCode, 0); 920 } 921 922 //get the index of the special case entry 923 private static int indexOf(String code, int fraction, int numeric) { 924 int size = specialCasesList.size(); 925 for (int index = 0; index < size; index++) { 926 SpecialCaseEntry scEntry = specialCasesList.get(index); 927 if (scEntry.oldCurrency.equals(code) 928 && scEntry.oldCurrencyFraction == fraction 929 && scEntry.oldCurrencyNumericCode == numeric 930 && scEntry.cutOverTime == Long.MAX_VALUE) { 931 return index; 932 } 933 } 934 return -1; 935 } 936 937 // get the fraction and numericCode of the sc currencycode 938 private static int[] findEntry(String code) { 939 int[] fractionAndNumericCode = null; 940 int size = specialCasesList.size(); 941 for (int index = 0; index < size; index++) { 942 SpecialCaseEntry scEntry = specialCasesList.get(index); 943 if (scEntry.oldCurrency.equals(code) && (scEntry.cutOverTime == Long.MAX_VALUE 944 || System.currentTimeMillis() < scEntry.cutOverTime)) { 945 //consider only when there is no new currency or cutover time is not passed 946 fractionAndNumericCode = new int[2]; 947 fractionAndNumericCode[0] = scEntry.oldCurrencyFraction; 948 fractionAndNumericCode[1] = scEntry.oldCurrencyNumericCode; 949 break; 950 } else if (scEntry.newCurrency.equals(code) 951 && System.currentTimeMillis() >= scEntry.cutOverTime) { 952 //consider only if the cutover time is passed 953 fractionAndNumericCode = new int[2]; 954 fractionAndNumericCode[0] = scEntry.newCurrencyFraction; 955 fractionAndNumericCode[1] = scEntry.newCurrencyNumericCode; 956 break; 957 } 958 } 959 return fractionAndNumericCode; 960 } 961 962 // convert the special case entry to sc arrays index 963 private static int toIndex(int tableEntry) { 964 return (tableEntry & SPECIAL_CASE_COUNTRY_INDEX_MASK) - SPECIAL_CASE_COUNTRY_INDEX_DELTA; 965 } 966 967 } 968 969 /* Used to represent Other currencies 970 * - currencyCode: currency codes that are not the main currency 971 * of a simple country 972 * - otherCurrenciesDFD: decimal format digits for other currencies 973 * - otherCurrenciesNumericCode: numeric code for other currencies 974 */ 975 private static class OtherCurrencyEntry { 976 977 final private String currencyCode; 978 final private int fraction; 979 final private int numericCode; 980 981 private OtherCurrencyEntry(String currencyCode, int fraction, 982 int numericCode) { 983 this.currencyCode = currencyCode; 984 this.fraction = fraction; 985 this.numericCode = numericCode; 986 } 987 988 //get the instance of the other currency code 989 private static OtherCurrencyEntry findEntry(String code) { 990 int size = otherCurrenciesList.size(); 991 for (int index = 0; index < size; index++) { 992 OtherCurrencyEntry ocEntry = otherCurrenciesList.get(index); 993 if (ocEntry.currencyCode.equalsIgnoreCase(code)) { 994 return ocEntry; 995 } 996 } 997 return null; 998 } 999 1000 } 1001 1002 } 1003 1004