001: /*
002: * @(#)Currency.java 1.7 06/10/10
003: *
004: * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
005: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006: *
007: * This program is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU General Public License version
009: * 2 only, as published by the Free Software Foundation.
010: *
011: * This program is distributed in the hope that it will be useful, but
012: * WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * General Public License version 2 for more details (a copy is
015: * included at /legal/license.txt).
016: *
017: * You should have received a copy of the GNU General Public License
018: * version 2 along with this work; if not, write to the Free Software
019: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020: * 02110-1301 USA
021: *
022: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023: * Clara, CA 95054 or visit www.sun.com if you need additional
024: * information or have any questions.
025: */
026:
027: package java.util;
028:
029: import java.io.Serializable;
030: import java.security.AccessController;
031: import java.security.PrivilegedAction;
032: import sun.text.resources.LocaleData;
033:
034: /**
035: * Represents a currency. Currencies are identified by their ISO 4217 currency
036: * codes. See the
037: * <a href="http://www.bsi-global.com/iso4217currency">
038: * ISO 4217 maintenance agency</a> for more information, including a table of
039: * currency codes.
040: * <p>
041: * The class is designed so that there's never more than one
042: * <code>Currency</code> instance for any given currency. Therefore, there's
043: * no public constructor. You obtain a <code>Currency</code> instance using
044: * the <code>getInstance</code> methods.
045: *
046: * @version 1.7, 10/10/06
047: * @since 1.4
048: */
049: public final class Currency implements Serializable {
050:
051: /**
052: * ISO 4217 currency code for this currency.
053: *
054: * @serial
055: */
056: private String currencyCode;
057:
058: /**
059: * Default fraction digits for this currency.
060: * Set from currency data tables.
061: */
062: transient private int defaultFractionDigits;
063:
064: // class data: instance map
065:
066: private static HashMap instances = new HashMap(7);
067:
068: // Class data: currency data obtained from java.util.CurrencyData.
069: // Purpose:
070: // - determine valid country codes
071: // - determine valid currency codes
072: // - map country codes to currency codes
073: // - obtain default fraction digits for currency codes
074: //
075: // sc = special case; dfd = default fraction digits
076: // Simple countries are those where the country code is a prefix of the
077: // currency code, and there are no known plans to change the currency.
078: //
079: // table formats:
080: // - mainTable:
081: // - maps country code to 8-bit char
082: // - 26*26 entries, corresponding to [A-Z]*[A-Z]
083: // - \u007F -> not valid country
084: // - bit 7 - 1: special case, bits 0-4 indicate which one
085: // 0: simple country, bits 0-4 indicate final char of currency code
086: // - bits 5-6: fraction digits for simple countries, 0 for special cases
087: // - bits 0-4: final char for currency code for simple country, or ID of special case
088: // - special case IDs:
089: // - 0: country has no currency
090: // - other: index into sc* arrays + 1
091: // - scCutOverTimes: cut-over time in millis as returned by
092: // System.currentTimeMillis for special case countries that are changing
093: // currencies; Long.MAX_VALUE for countries that are not changing currencies
094: // - scOldCurrencies: old currencies for special case countries
095: // - scNewCurrencies: new currencies for special case countries that are
096: // changing currencies; null for others
097: // - scOldCurrenciesDFD: default fraction digits for old currencies
098: // - scNewCurrenciesDFD: default fraction digits for new currencies, 0 for
099: // countries that are not changing currencies
100: // - otherCurrencies: concatenation of all currency codes that are not the
101: // main currency of a simple country, separated by "-"
102: // - otherCurrenciesDFD: decimal format digits for currencies in otherCurrencies, same order
103:
104: static String mainTable;
105: static long[] scCutOverTimes;
106: static String[] scOldCurrencies;
107: static String[] scNewCurrencies;
108: static int[] scOldCurrenciesDFD;
109: static int[] scNewCurrenciesDFD;
110: static String otherCurrencies;
111: static int[] otherCurrenciesDFD;
112:
113: // handy constants - must match definitions in GenerateCurrencyData
114: // number of characters from A to Z
115: private static final int A_TO_Z = ('Z' - 'A') + 1;
116: // entry for invalid country codes
117: private static final int INVALID_COUNTRY_ENTRY = 0x007F;
118: // entry for countries without currency
119: private static final int COUNTRY_WITHOUT_CURRENCY_ENTRY = 0x0080;
120: // mask for simple case country entries
121: private static final int SIMPLE_CASE_COUNTRY_MASK = 0x0000;
122: // mask for simple case country entry final character
123: private static final int SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK = 0x001F;
124: // mask for simple case country entry default currency digits
125: private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK = 0x0060;
126: // shift count for simple case country entry default currency digits
127: private static final int SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT = 5;
128: // mask for special case country entries
129: private static final int SPECIAL_CASE_COUNTRY_MASK = 0x0080;
130: // mask for special case country index
131: private static final int SPECIAL_CASE_COUNTRY_INDEX_MASK = 0x001F;
132: // delta from entry index component in main table to index into special case tables
133: private static final int SPECIAL_CASE_COUNTRY_INDEX_DELTA = 1;
134: // mask for distinguishing simple and special case countries
135: private static final int COUNTRY_TYPE_MASK = SIMPLE_CASE_COUNTRY_MASK
136: | SPECIAL_CASE_COUNTRY_MASK;
137:
138: static {
139: AccessController.doPrivileged(new PrivilegedAction() {
140: public Object run() {
141: try {
142: Class data = Class
143: .forName("java.util.CurrencyData");
144: mainTable = (String) data.getDeclaredField(
145: "mainTable").get(data);
146: scCutOverTimes = (long[]) data.getDeclaredField(
147: "scCutOverTimes").get(data);
148: scOldCurrencies = (String[]) data.getDeclaredField(
149: "scOldCurrencies").get(data);
150: scNewCurrencies = (String[]) data.getDeclaredField(
151: "scNewCurrencies").get(data);
152: scOldCurrenciesDFD = (int[]) data.getDeclaredField(
153: "scOldCurrenciesDFD").get(data);
154: scNewCurrenciesDFD = (int[]) data.getDeclaredField(
155: "scNewCurrenciesDFD").get(data);
156: otherCurrencies = (String) data.getDeclaredField(
157: "otherCurrencies").get(data);
158: otherCurrenciesDFD = (int[]) data.getDeclaredField(
159: "otherCurrenciesDFD").get(data);
160: } catch (ClassNotFoundException e) {
161: throw new InternalError();
162: } catch (NoSuchFieldException e) {
163: throw new InternalError();
164: } catch (IllegalAccessException e) {
165: throw new InternalError();
166: }
167: return null;
168: }
169: });
170: }
171:
172: /**
173: * Constructs a <code>Currency</code> instance. The constructor is private
174: * so that we can insure that there's never more than one instance for a
175: * given currency.
176: */
177: private Currency(String currencyCode, int defaultFractionDigits) {
178: this .currencyCode = currencyCode;
179: this .defaultFractionDigits = defaultFractionDigits;
180: }
181:
182: /**
183: * Returns the <code>Currency</code> instance for the given currency code.
184: *
185: * @param currencyCode the ISO 4217 code of the currency
186: * @return the <code>Currency</code> instance for the given currency code
187: * @exception NullPointerException if <code>currencyCode</code> is null
188: * @exception IllegalArgumentException if <code>currencyCode</code> is not
189: * a supported ISO 4217 code.
190: */
191: public static Currency getInstance(String currencyCode) {
192: return getInstance(currencyCode, Integer.MIN_VALUE);
193: }
194:
195: private static Currency getInstance(String currencyCode,
196: int defaultFractionDigits) {
197: synchronized (instances) {
198: // Try to look up the currency code in the instances table.
199: // This does the null pointer check as a side effect.
200: // Also, if there already is an entry, the currencyCode must be valid.
201: Currency instance = (Currency) instances.get(currencyCode);
202: if (instance != null) {
203: return instance;
204: }
205:
206: if (defaultFractionDigits == Integer.MIN_VALUE) {
207: // Currency code not internally generated, need to verify first
208: // A currency code must have 3 characters and exist in the main table
209: // or in the list of other currencies.
210: if (currencyCode.length() != 3) {
211: throw new IllegalArgumentException();
212: }
213: char char1 = currencyCode.charAt(0);
214: char char2 = currencyCode.charAt(1);
215: int tableEntry = getMainTableEntry(char1, char2);
216: if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK
217: && tableEntry != INVALID_COUNTRY_ENTRY
218: && currencyCode.charAt(2) - 'A' == (tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK)) {
219: defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT;
220: } else {
221: // Check for '-' separately so we don't get false hits in the table.
222: if (currencyCode.charAt(2) == '-') {
223: throw new IllegalArgumentException();
224: }
225: int index = otherCurrencies.indexOf(currencyCode);
226: if (index == -1) {
227: throw new IllegalArgumentException();
228: }
229: defaultFractionDigits = otherCurrenciesDFD[index / 4];
230: }
231: }
232:
233: instance = new Currency(currencyCode, defaultFractionDigits);
234: instances.put(currencyCode, instance);
235: return instance;
236: }
237: }
238:
239: /**
240: * Returns the <code>Currency</code> instance for the country of the
241: * given locale. The language and variant components of the locale
242: * are ignored. The result may vary over time, as countries change their
243: * currencies. For example, for the original member countries of the
244: * European Monetary Union, the method returns the old national currencies
245: * until December 31, 2001, and the Euro from January 1, 2002, local time
246: * of the respective countries.
247: * <p>
248: * The method returns <code>null</code> for territories that don't
249: * have a currency, such as Antarctica.
250: *
251: * @param locale the locale for whose country a <code>Currency</code>
252: * instance is needed
253: * @return the <code>Currency</code> instance for the country of the given
254: * locale, or null
255: * @exception NullPointerException if <code>locale</code> or its country
256: * code is null
257: * @exception IllegalArgumentException if the country of the given locale
258: * is not a supported ISO 3166 country code.
259: */
260: public static Currency getInstance(Locale locale) {
261: String country = locale.getCountry();
262: if (country == null) {
263: throw new NullPointerException();
264: }
265:
266: if (country.length() != 2) {
267: throw new IllegalArgumentException();
268: }
269:
270: char char1 = country.charAt(0);
271: char char2 = country.charAt(1);
272: int tableEntry = getMainTableEntry(char1, char2);
273: if ((tableEntry & COUNTRY_TYPE_MASK) == SIMPLE_CASE_COUNTRY_MASK
274: && tableEntry != INVALID_COUNTRY_ENTRY) {
275: char finalChar = (char) ((tableEntry & SIMPLE_CASE_COUNTRY_FINAL_CHAR_MASK) + 'A');
276: int defaultFractionDigits = (tableEntry & SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_MASK) >> SIMPLE_CASE_COUNTRY_DEFAULT_DIGITS_SHIFT;
277: StringBuffer sb = new StringBuffer(country);
278: sb.append(finalChar);
279: return getInstance(sb.toString(), defaultFractionDigits);
280: } else {
281: // special cases
282: if (tableEntry == INVALID_COUNTRY_ENTRY) {
283: throw new IllegalArgumentException();
284: }
285: if (tableEntry == COUNTRY_WITHOUT_CURRENCY_ENTRY) {
286: return null;
287: } else {
288: int index = (tableEntry & SPECIAL_CASE_COUNTRY_INDEX_MASK)
289: - SPECIAL_CASE_COUNTRY_INDEX_DELTA;
290: if (scCutOverTimes[index] == Long.MAX_VALUE
291: || System.currentTimeMillis() < scCutOverTimes[index]) {
292: return getInstance(scOldCurrencies[index],
293: scOldCurrenciesDFD[index]);
294: } else {
295: return getInstance(scNewCurrencies[index],
296: scNewCurrenciesDFD[index]);
297: }
298: }
299: }
300: }
301:
302: /**
303: * Gets the ISO 4217 currency code of this currency.
304: *
305: * @return the ISO 4217 currency code of this currency.
306: */
307: public String getCurrencyCode() {
308: return currencyCode;
309: }
310:
311: /**
312: * Gets the symbol of this currency for the default locale.
313: * For example, for the US Dollar, the symbol is "$" if the default
314: * locale is the US, while for other locales it may be "US$". If no
315: * symbol can be determined, the ISO 4217 currency code is returned.
316: *
317: * @return the symbol of this currency for the default locale
318: */
319: public String getSymbol() {
320: return getSymbol(Locale.getDefault());
321: }
322:
323: /**
324: * Gets the symbol of this currency for the specified locale.
325: * For example, for the US Dollar, the symbol is "$" if the specified
326: * locale is the US, while for other locales it may be "US$". If no
327: * symbol can be determined, the ISO 4217 currency code is returned.
328: *
329: * @param locale the locale for which a display name for this currency is
330: * needed
331: * @return the symbol of this currency for the specified locale
332: * @exception NullPointerException if <code>locale</code> is null
333: */
334: public String getSymbol(Locale locale) {
335: ResourceBundle bundle;
336: try {
337: bundle = LocaleData.getLocaleElements(locale);
338: } catch (MissingResourceException e) {
339: // use currency code as symbol of last resort
340: return currencyCode;
341: }
342: String[][] symbols = (String[][]) bundle
343: .getObject("CurrencySymbols");
344: if (symbols != null) {
345: for (int i = 0; i < symbols.length; i++) {
346: if (symbols[i][0].equals(currencyCode)) {
347: return symbols[i][1];
348: }
349: }
350: }
351: // use currency code as symbol of last resort
352: return currencyCode;
353: }
354:
355: /**
356: * Gets the default number of fraction digits used with this currency.
357: * For example, the default number of fraction digits for the Euro is 2,
358: * while for the Japanese Yen it's 0.
359: * In the case of pseudo-currencies, such as IMF Special Drawing Rights,
360: * -1 is returned.
361: *
362: * @return the default number of fraction digits used with this currency
363: */
364: public int getDefaultFractionDigits() {
365: return defaultFractionDigits;
366: }
367:
368: /**
369: * Returns the ISO 4217 currency code of this currency.
370: *
371: * @return the ISO 4217 currency code of this currency
372: */
373: public String toString() {
374: return currencyCode;
375: }
376:
377: /**
378: * Resolves instances being deserialized to a single instance per currency.
379: */
380: private Object readResolve() {
381: return getInstance(currencyCode);
382: }
383:
384: /**
385: * Gets the main table entry for the country whose country code consists
386: * of char1 and char2.
387: */
388: private static int getMainTableEntry(char char1, char char2) {
389: if (char1 < 'A' || char1 > 'Z' || char2 < 'A' || char2 > 'Z') {
390: throw new IllegalArgumentException();
391: }
392: return mainTable.charAt((char1 - 'A') * A_TO_Z + (char2 - 'A'));
393: }
394: }
|