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