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