1. /*
  2. * @(#)Currency.java 1.4 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util;
  8. import java.io.Serializable;
  9. import java.security.AccessController;
  10. import java.security.PrivilegedAction;
  11. import sun.text.resources.LocaleData;
  12. /**
  13. * Represents a currency. Currencies are identified by their ISO 4217 currency
  14. * codes. See the
  15. * <a href="http://www.bsi-global.com/iso4217currency">
  16. * ISO 4217 maintenance agency</a> for more information, including a table of
  17. * currency codes.
  18. * <p>
  19. * The class is designed so that there's never more than one
  20. * <code>Currency</code> instance for any given currency. Therefore, there's
  21. * no public constructor. You obtain a <code>Currency</code> instance using
  22. * the <code>getInstance</code> methods.
  23. *
  24. * @version 1.4, 01/23/03
  25. * @since 1.4
  26. */
  27. public final class Currency implements Serializable {
  28. /**
  29. * ISO 4217 currency code for this currency.
  30. *
  31. * @serial
  32. */
  33. private String currencyCode;
  34. /**
  35. * Default fraction digits for this currency.
  36. * Set from currency data tables.
  37. */
  38. transient private int defaultFractionDigits;
  39. // class data: instance map
  40. private static HashMap instances = new HashMap(7);
  41. // Class data: currency data obtained from java.util.CurrencyData.
  42. // Purpose:
  43. // - determine valid country codes
  44. // - determine valid currency codes
  45. // - map country codes to currency codes
  46. // - obtain default fraction digits for currency codes
  47. //
  48. // sc = special case; dfd = default fraction digits
  49. // Simple countries are those where the country code is a prefix of the
  50. // currency code, and there are no known plans to change the currency.
  51. //
  52. // table formats:
  53. // - mainTable:
  54. // - maps country code to 8-bit char
  55. // - 26*26 entries, corresponding to [A-Z]*[A-Z]
  56. // - \u007F -> not valid country
  57. // - bit 7 - 1: special case, bits 0-4 indicate which one
  58. // 0: simple country, bits 0-4 indicate final char of currency code
  59. // - bits 5-6: fraction digits for simple countries, 0 for special cases
  60. // - bits 0-4: final char for currency code for simple country, or ID of special case
  61. // - special case IDs:
  62. // - 0: country has no currency
  63. // - other: index into sc* arrays + 1
  64. // - scCutOverTimes: cut-over time in millis as returned by
  65. // System.currentTimeMillis for special case countries that are changing
  66. // currencies; Long.MAX_VALUE for countries that are not changing currencies
  67. // - scOldCurrencies: old currencies for special case countries
  68. // - scNewCurrencies: new currencies for special case countries that are
  69. // changing currencies; null for others
  70. // - scOldCurrenciesDFD: default fraction digits for old currencies
  71. // - scNewCurrenciesDFD: default fraction digits for new currencies, 0 for
  72. // countries that are not changing currencies
  73. // - otherCurrencies: concatenation of all currency codes that are not the
  74. // main currency of a simple country, separated by "-"
  75. // - otherCurrenciesDFD: decimal format digits for currencies in otherCurrencies, same order
  76. static String mainTable;
  77. static long[] scCutOverTimes;
  78. static String[] scOldCurrencies;
  79. static String[] scNewCurrencies;
  80. static int[] scOldCurrenciesDFD;
  81. static int[] scNewCurrenciesDFD;
  82. static String otherCurrencies;
  83. static int[] otherCurrenciesDFD;
  84. // handy constants - must match definitions in GenerateCurrencyData
  85. // number of characters from A to Z
  86. private static final int A_TO_Z = ('Z' - 'A') + 1;
  87. // entry for invalid country codes
  88. private static final int INVALID_COUNTRY_ENTRY = 0x007F;
  89. // entry for countries without currency
  90. private static final int COUNTRY_WITHOUT_CURRENCY_ENTRY = 0x0080;
  91. // mask for simple case country entries
  92. private static final int SIMPLE_CASE_COUNTRY_MASK = 0x0000;
  93. // mask for simple case country entry final character
  94. private static final int SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK = 0x001F;
  95. // mask for simple case country entry default currency digits
  96. private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK = 0x0060;
  97. // shift count for simple case country entry default currency digits
  98. private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT = 5;
  99. // mask for special case country entries
  100. private static final int SPECIAL_CASE_COUNTRY_MASK = 0x0080;
  101. // mask for special case country index
  102. private static final int SPECIAL_CASE_COUNTRY_INDEX_MASK = 0x001F;
  103. // delta from entry index component in main table to index into special case tables
  104. private static final int SPECIAL_CASE_COUNTRY_INDEX_DELTA = 1;
  105. // mask for distinguishing simple and special case countries
  106. private static final int COUNTRY_TYPE_MASK = SIMPLE_CASE_COUNTRY_MASK | SPECIAL_CASE_COUNTRY_MASK;
  107. static {
  108. AccessController.doPrivileged(new PrivilegedAction() {
  109. public Object run() {
  110. try {
  111. Class data = Class.forName("java.util.CurrencyData");
  112. mainTable = (String) data.getDeclaredField("mainTable").get(data);
  113. scCutOverTimes = (long[]) data.getDeclaredField("scCutOverTimes").get(data);
  114. scOldCurrencies = (String[]) data.getDeclaredField("scOldCurrencies").get(data);
  115. scNewCurrencies = (String[]) data.getDeclaredField("scNewCurrencies").get(data);
  116. scOldCurrenciesDFD = (int[]) data.getDeclaredField("scOldCurrenciesDFD").get(data);
  117. scNewCurrenciesDFD = (int[]) data.getDeclaredField("scNewCurrenciesDFD").get(data);
  118. otherCurrencies = (String) data.getDeclaredField("otherCurrencies").get(data);
  119. otherCurrenciesDFD = (int[]) data.getDeclaredField("otherCurrenciesDFD").get(data);
  120. } catch (ClassNotFoundException e) {
  121. throw new InternalError();
  122. } catch (NoSuchFieldException e) {
  123. throw new InternalError();
  124. } catch (IllegalAccessException e) {
  125. throw new InternalError();
  126. }
  127. return null;
  128. }
  129. });
  130. }
  131. /**
  132. * Constructs a <code>Currency</code> instance. The constructor is private
  133. * so that we can insure that there's never more than one instance for a
  134. * given currency.
  135. */
  136. private Currency(String currencyCode, int defaultFractionDigits) {
  137. this.currencyCode = currencyCode;
  138. this.defaultFractionDigits = defaultFractionDigits;
  139. }
  140. /**
  141. * Returns the <code>Currency</code> instance for the given currency code.
  142. *
  143. * @param currencyCode the ISO 4217 code of the currency
  144. * @return the <code>Currency</code> instance for the given currency code
  145. * @exception NullPointerException if <code>currencyCode</code> is null
  146. * @exception IllegalArgumentException if <code>currencyCode</code> is not
  147. * a supported ISO 4217 code.
  148. */
  149. public static Currency getInstance(String currencyCode) {
  150. return getInstance(currencyCode, Integer.MIN_VALUE);
  151. }
  152. private static Currency getInstance(String currencyCode, int defaultFractionDigits) {
  153. synchronized (instances) {
  154. // Try to look up the currency code in the instances table.
  155. // This does the null pointer check as a side effect.
  156. // Also, if there already is an entry, the currencyCode must be valid.
  157. Currency instance = (Currency) instances.get(currencyCode);
  158. if (instance != null) {
  159. return instance;
  160. }
  161. if (defaultFractionDigits == Integer.MIN_VALUE) {
  162. // Currency code not internally generated, need to verify first
  163. // A currency code must have 3 characters and exist in the main table
  164. // or in the list of other currencies.
  165. if (currencyCode.length() != 3) {
  166. throw new IllegalArgumentException();
  167. }
  168. char char1 = currencyCode.charAt(0);
  169. char char2 = currencyCode.charAt(1);
  170. int tableEntry = getMainTableEntry(char1, char2);
  171. if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK
  172. && tableEntry != INVALID_COUNTRY_ENTRY
  173. && currencyCode.charAt(2) - 'A' == (tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK)) {
  174. defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT;
  175. } else {
  176. // Check for '-' separately so we don't get false hits in the table.
  177. if (currencyCode.charAt(2) == '-') {
  178. throw new IllegalArgumentException();
  179. }
  180. int index = otherCurrencies.indexOf(currencyCode);
  181. if (index == -1) {
  182. throw new IllegalArgumentException();
  183. }
  184. defaultFractionDigits = otherCurrenciesDFD[index / 4];
  185. }
  186. }
  187. instance = new Currency(currencyCode, defaultFractionDigits);
  188. instances.put(currencyCode, instance);
  189. return instance;
  190. }
  191. }
  192. /**
  193. * Returns the <code>Currency</code> instance for the country of the
  194. * given locale. The language and variant components of the locale
  195. * are ignored. The result may vary over time, as countries change their
  196. * currencies. For example, for the original member countries of the
  197. * European Monetary Union, the method returns the old national currencies
  198. * until December 31, 2001, and the Euro from January 1, 2002, local time
  199. * of the respective countries.
  200. * <p>
  201. * The method returns <code>null</code> for territories that don't
  202. * have a currency, such as Antarctica.
  203. *
  204. * @param locale the locale for whose country a <code>Currency</code>
  205. * instance is needed
  206. * @return the <code>Currency</code> instance for the country of the given
  207. * locale, or null
  208. * @exception NullPointerException if <code>locale</code> or its country
  209. * code is null
  210. * @exception IllegalArgumentException if the country of the given locale
  211. * is not a supported ISO 3166 country code.
  212. */
  213. public static Currency getInstance(Locale locale) {
  214. String country = locale.getCountry();
  215. if (country == null) {
  216. throw new NullPointerException();
  217. }
  218. if (country.length() != 2) {
  219. throw new IllegalArgumentException();
  220. }
  221. char char1 = country.charAt(0);
  222. char char2 = country.charAt(1);
  223. int tableEntry = getMainTableEntry(char1, char2);
  224. if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK
  225. && tableEntry != INVALID_COUNTRY_ENTRY) {
  226. char finalChar = (char) ((tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK) + 'A');
  227. int defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT;
  228. StringBuffer sb = new StringBuffer(country);
  229. sb.append(finalChar);
  230. return getInstance(sb.toString(), defaultFractionDigits);
  231. } else {
  232. // special cases
  233. if (tableEntry == INVALID_COUNTRY_ENTRY) {
  234. throw new IllegalArgumentException();
  235. }
  236. if (tableEntry == COUNTRY_WITHOUT_CURRENCY_ENTRY) {
  237. return null;
  238. } else {
  239. int index = (tableEntry & SPECIAL_CASE_COUNTRY_INDEX_MASK) - SPECIAL_CASE_COUNTRY_INDEX_DELTA;
  240. if (scCutOverTimes[index] == Long.MAX_VALUE || System.currentTimeMillis() < scCutOverTimes[index]) {
  241. return getInstance(scOldCurrencies[index], scOldCurrenciesDFD[index]);
  242. } else {
  243. return getInstance(scNewCurrencies[index], scNewCurrenciesDFD[index]);
  244. }
  245. }
  246. }
  247. }
  248. /**
  249. * Gets the ISO 4217 currency code of this currency.
  250. *
  251. * @return the ISO 4217 currency code of this currency.
  252. */
  253. public String getCurrencyCode() {
  254. return currencyCode;
  255. }
  256. /**
  257. * Gets the symbol of this currency for the default locale.
  258. * For example, for the US Dollar, the symbol is "$" if the default
  259. * locale is the US, while for other locales it may be "US$". If no
  260. * symbol can be determined, the ISO 4217 currency code is returned.
  261. *
  262. * @return the symbol of this currency for the default locale
  263. */
  264. public String getSymbol() {
  265. return getSymbol(Locale.getDefault());
  266. }
  267. /**
  268. * Gets the symbol of this currency for the specified locale.
  269. * For example, for the US Dollar, the symbol is "$" if the specified
  270. * locale is the US, while for other locales it may be "US$". If no
  271. * symbol can be determined, the ISO 4217 currency code is returned.
  272. *
  273. * @param locale the locale for which a display name for this currency is
  274. * needed
  275. * @return the symbol of this currency for the specified locale
  276. * @exception NullPointerException if <code>locale</code> is null
  277. */
  278. public String getSymbol(Locale locale) {
  279. ResourceBundle bundle;
  280. try {
  281. bundle = LocaleData.getLocaleElements(locale);
  282. } catch (MissingResourceException e) {
  283. // use currency code as symbol of last resort
  284. return currencyCode;
  285. }
  286. String[][] symbols =
  287. (String[][]) bundle.getObject("CurrencySymbols");
  288. if (symbols != null) {
  289. for (int i = 0; i < symbols.length; i++) {
  290. if (symbols[i][0].equals(currencyCode)) {
  291. return symbols[i][1];
  292. }
  293. }
  294. }
  295. // use currency code as symbol of last resort
  296. return currencyCode;
  297. }
  298. /**
  299. * Gets the default number of fraction digits used with this currency.
  300. * For example, the default number of fraction digits for the Euro is 2,
  301. * while for the Japanese Yen it's 0.
  302. * In the case of pseudo-currencies, such as IMF Special Drawing Rights,
  303. * -1 is returned.
  304. *
  305. * @return the default number of fraction digits used with this currency
  306. */
  307. public int getDefaultFractionDigits() {
  308. return defaultFractionDigits;
  309. }
  310. /**
  311. * Returns the ISO 4217 currency code of this currency.
  312. *
  313. * @return the ISO 4217 currency code of this currency
  314. */
  315. public String toString() {
  316. return currencyCode;
  317. }
  318. /**
  319. * Resolves instances being deserialized to a single instance per currency.
  320. */
  321. private Object readResolve() {
  322. return getInstance(currencyCode);
  323. }
  324. /**
  325. * Gets the main table entry for the country whose country code consists
  326. * of char1 and char2.
  327. */
  328. private static int getMainTableEntry(char char1, char char2) {
  329. if (char1 < 'A' || char1 > 'Z' || char2 < 'A' || char2 > 'Z') {
  330. throw new IllegalArgumentException();
  331. }
  332. return mainTable.charAt((char1 - 'A') * A_TO_Z + (char2 - 'A'));
  333. }
  334. }