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