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