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