Currency.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. /* Currency.java -- Representation of a currency
  2. Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util;
  32. import gnu.java.locale.LocaleHelper;
  33. import java.io.IOException;
  34. import java.io.ObjectStreamException;
  35. import java.io.Serializable;
  36. import java.util.spi.CurrencyNameProvider;
  37. /**
  38. * Representation of a currency for a particular locale. Each currency
  39. * is identified by its ISO 4217 code, and only one instance of this
  40. * class exists per currency. As a result, instances are created
  41. * via the <code>getInstance()</code> methods rather than by using
  42. * a constructor.
  43. *
  44. * @see java.util.Locale
  45. * @author Guilhem Lavaux (guilhem.lavaux@free.fr)
  46. * @author Dalibor Topic (robilad@kaffe.org)
  47. * @author Bryce McKinlay (mckinlay@redhat.com)
  48. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  49. * @since 1.4
  50. */
  51. public final class Currency
  52. implements Serializable
  53. {
  54. /**
  55. * For compatability with Sun's JDK
  56. */
  57. static final long serialVersionUID = -158308464356906721L;
  58. /**
  59. * The set of properties which map a currency to
  60. * the currency information such as the ISO 4217
  61. * currency code and the number of decimal points.
  62. *
  63. * @see #getCurrencyCode()
  64. * @serial ignored.
  65. */
  66. private static transient Properties properties;
  67. /**
  68. * The ISO 4217 currency code associated with this
  69. * particular instance.
  70. *
  71. * @see #getCurrencyCode()
  72. * @serial the ISO 4217 currency code
  73. */
  74. private String currencyCode;
  75. /**
  76. * The number of fraction digits associated with this
  77. * particular instance.
  78. *
  79. * @see #getDefaultFractionDigits()
  80. * @serial the number of fraction digits
  81. */
  82. private transient int fractionDigits;
  83. /**
  84. * A cached map of country codes
  85. * instances to international currency code
  86. * <code>String</code>s. Seperating this
  87. * from the <code>Currency</code> instances
  88. * ensures we have a common lookup between
  89. * the two <code>getInstance()</code> methods.
  90. *
  91. * @see #getInstance(java.util.Locale)
  92. * @serial ignored.
  93. */
  94. private static transient Map countryMap;
  95. /**
  96. * A cache of <code>Currency</code> instances to
  97. * ensure the singleton nature of this class. The key
  98. * is the international currency code.
  99. *
  100. * @see #getInstance(java.util.Locale)
  101. * @see #getInstance(java.lang.String)
  102. * @see #readResolve()
  103. * @serial ignored.
  104. */
  105. private static transient Map cache;
  106. /**
  107. * Instantiates the cache and reads in the properties.
  108. */
  109. static
  110. {
  111. /* Create a hash map for the locale mappings */
  112. countryMap = new HashMap();
  113. /* Create a hash map for the cache */
  114. cache = new HashMap();
  115. /* Create the properties object */
  116. properties = new Properties();
  117. /* Try and load the properties from our iso4217.properties resource */
  118. try
  119. {
  120. properties.load(Currency.class.getResourceAsStream("iso4217.properties"));
  121. }
  122. catch (IOException exception)
  123. {
  124. throw new InternalError("Failed to load currency resource: " + exception);
  125. }
  126. }
  127. /**
  128. * Default constructor for deserialization
  129. */
  130. private Currency()
  131. {
  132. }
  133. /**
  134. * Constructor to create a <code>Currency</code> object
  135. * for a particular <code>Locale</code>.
  136. * All components of the given locale, other than the
  137. * country code, are ignored. The results of calling this
  138. * method may vary over time, as the currency associated with
  139. * a particular country changes. For countries without
  140. * a given currency (e.g. Antarctica), the result is null.
  141. *
  142. * @param loc the locale for the new currency, or null if
  143. * there is no country code specified or a currency
  144. * for this country.
  145. */
  146. private Currency(Locale loc)
  147. {
  148. String countryCode;
  149. String currencyKey;
  150. String fractionDigitsKey;
  151. int commaPosition;
  152. /* Retrieve the country code from the locale */
  153. countryCode = loc.getCountry();
  154. /* If there is no country code, return */
  155. if (countryCode.equals(""))
  156. {
  157. throw new
  158. IllegalArgumentException("Invalid (empty) country code for locale:"
  159. + loc);
  160. }
  161. /* Construct the key for the currency */
  162. currencyKey = countryCode + ".currency";
  163. /* Construct the key for the fraction digits */
  164. fractionDigitsKey = countryCode + ".fractionDigits";
  165. /* Retrieve the currency */
  166. currencyCode = properties.getProperty(currencyKey);
  167. /* Return if the currency code is null */
  168. if (currencyCode == null)
  169. {
  170. return;
  171. }
  172. /* Split off the first currency code (we only use the first for now) */
  173. commaPosition = currencyCode.indexOf(",");
  174. if (commaPosition != -1)
  175. {
  176. currencyCode = currencyCode.substring(0, commaPosition);
  177. }
  178. /* Retrieve the fraction digits */
  179. fractionDigits = Integer.parseInt(properties.getProperty(fractionDigitsKey));
  180. }
  181. /**
  182. * Constructor for the "XXX" special case. This allows
  183. * a Currency to be constructed from an assumed good
  184. * currency code.
  185. *
  186. * @param code the code to use.
  187. */
  188. private Currency(String code)
  189. {
  190. currencyCode = code;
  191. fractionDigits = -1; /* Pseudo currency */
  192. }
  193. /**
  194. * Returns the ISO4217 currency code of this currency.
  195. *
  196. * @return a <code>String</code> containing currency code.
  197. */
  198. public String getCurrencyCode()
  199. {
  200. return currencyCode;
  201. }
  202. /**
  203. * Returns the number of digits which occur after the decimal point
  204. * for this particular currency. For example, currencies such
  205. * as the U.S. dollar, the Euro and the Great British pound have two
  206. * digits following the decimal point to indicate the value which exists
  207. * in the associated lower-valued coinage (cents in the case of the first
  208. * two, pennies in the latter). Some currencies such as the Japanese
  209. * Yen have no digits after the decimal point. In the case of pseudo
  210. * currencies, such as IMF Special Drawing Rights, -1 is returned.
  211. *
  212. * @return the number of digits after the decimal separator for this currency.
  213. */
  214. public int getDefaultFractionDigits()
  215. {
  216. return fractionDigits;
  217. }
  218. /**
  219. * Builds a new currency instance for this locale.
  220. * All components of the given locale, other than the
  221. * country code, are ignored. The results of calling this
  222. * method may vary over time, as the currency associated with
  223. * a particular country changes. For countries without
  224. * a given currency (e.g. Antarctica), the result is null.
  225. *
  226. * @param locale a <code>Locale</code> instance.
  227. * @return a new <code>Currency</code> instance.
  228. * @throws NullPointerException if the locale or its
  229. * country code is null.
  230. * @throws IllegalArgumentException if the country of
  231. * the given locale is not a supported ISO3166 code.
  232. */
  233. public static Currency getInstance(Locale locale)
  234. {
  235. /**
  236. * The new instance must be the only available instance
  237. * for the currency it supports. We ensure this happens,
  238. * while maintaining a suitable performance level, by
  239. * creating the appropriate object on the first call to
  240. * this method, and returning the cached instance on
  241. * later calls.
  242. */
  243. Currency newCurrency;
  244. String country = locale.getCountry();
  245. if (locale == null || country == null)
  246. {
  247. throw new
  248. NullPointerException("The locale or its country is null.");
  249. }
  250. /* Check that country of locale given is valid. */
  251. if (country.length() != 2)
  252. throw new IllegalArgumentException();
  253. /* Attempt to get the currency from the cache */
  254. String code = (String) countryMap.get(country);
  255. if (code == null)
  256. {
  257. /* Create the currency for this locale */
  258. newCurrency = new Currency(locale);
  259. /*
  260. * If the currency code is null, then creation failed
  261. * and we return null.
  262. */
  263. code = newCurrency.getCurrencyCode();
  264. if (code == null)
  265. {
  266. return null;
  267. }
  268. else
  269. {
  270. /* Cache it */
  271. countryMap.put(country, code);
  272. cache.put(code, newCurrency);
  273. }
  274. }
  275. else
  276. {
  277. newCurrency = (Currency) cache.get(code);
  278. }
  279. /* Return the instance */
  280. return newCurrency;
  281. }
  282. /**
  283. * Builds the currency corresponding to the specified currency code.
  284. *
  285. * @param currencyCode a string representing a currency code.
  286. * @return a new <code>Currency</code> instance.
  287. * @throws NullPointerException if currencyCode is null.
  288. * @throws IllegalArgumentException if the supplied currency code
  289. * is not a supported ISO 4217 code.
  290. */
  291. public static Currency getInstance(String currencyCode)
  292. {
  293. Locale[] allLocales;
  294. /*
  295. * Throw a null pointer exception explicitly if currencyCode is null.
  296. * One is not thrown otherwise. It results in an
  297. * IllegalArgumentException.
  298. */
  299. if (currencyCode == null)
  300. {
  301. throw new NullPointerException("The supplied currency code is null.");
  302. }
  303. /* Nasty special case to allow an erroneous currency... blame Sun */
  304. if (currencyCode.equals("XXX"))
  305. return new Currency("XXX");
  306. Currency newCurrency = (Currency) cache.get(currencyCode);
  307. if (newCurrency == null)
  308. {
  309. /* Get all locales */
  310. allLocales = Locale.getAvailableLocales();
  311. /* Loop through each locale, looking for the code */
  312. for (int i = 0;i < allLocales.length; i++)
  313. {
  314. try
  315. {
  316. Currency testCurrency = getInstance (allLocales[i]);
  317. if (testCurrency != null &&
  318. testCurrency.getCurrencyCode().equals(currencyCode))
  319. {
  320. return testCurrency;
  321. }
  322. }
  323. catch (IllegalArgumentException exception)
  324. {
  325. /* Ignore locales without valid countries */
  326. }
  327. }
  328. /*
  329. * If we get this far, the code is not supported by any of
  330. * our locales.
  331. */
  332. throw new IllegalArgumentException("The currency code, " + currencyCode +
  333. ", is not supported.");
  334. }
  335. else
  336. {
  337. return newCurrency;
  338. }
  339. }
  340. /**
  341. * This method returns the symbol which precedes or follows a
  342. * value in this particular currency in the default locale.
  343. * In cases where there is no such symbol for the currency,
  344. * the ISO 4217 currency code is returned.
  345. *
  346. * @return the currency symbol, or the ISO 4217 currency code if
  347. * one doesn't exist.
  348. */
  349. public String getSymbol()
  350. {
  351. return getSymbol(Locale.getDefault());
  352. }
  353. /**
  354. * <p>
  355. * This method returns the symbol which precedes or follows a
  356. * value in this particular currency. The returned value is
  357. * the symbol used to denote the currency in the specified locale.
  358. * </p>
  359. * <p>
  360. * For example, a supplied locale may specify a different symbol
  361. * for the currency, due to conflicts with its own currency.
  362. * This would be the case with the American currency, the dollar.
  363. * Locales that also use a dollar-based currency (e.g. Canada, Australia)
  364. * need to differentiate the American dollar using 'US$' rather than '$'.
  365. * So, supplying one of these locales to <code>getSymbol()</code> would
  366. * return this value, rather than the standard '$'.
  367. * </p>
  368. * <p>
  369. * In cases where there is no such symbol for a particular currency,
  370. * the ISO 4217 currency code is returned.
  371. * </p>
  372. *
  373. * @param locale the locale to express the symbol in.
  374. * @return the currency symbol, or the ISO 4217 currency code if
  375. * one doesn't exist.
  376. * @throws NullPointerException if the locale is null.
  377. */
  378. public String getSymbol(Locale locale)
  379. {
  380. String property = "currenciesSymbol." + currencyCode;
  381. try
  382. {
  383. return ResourceBundle.getBundle("gnu.java.locale.LocaleInformation",
  384. locale).getString(property);
  385. }
  386. catch (MissingResourceException exception)
  387. {
  388. /* This means runtime support for the locale
  389. * is not available, so we check providers. */
  390. }
  391. for (CurrencyNameProvider p :
  392. ServiceLoader.load(CurrencyNameProvider.class))
  393. {
  394. for (Locale loc : p.getAvailableLocales())
  395. {
  396. if (loc.equals(locale))
  397. {
  398. String localizedString = p.getSymbol(currencyCode,
  399. locale);
  400. if (localizedString != null)
  401. return localizedString;
  402. break;
  403. }
  404. }
  405. }
  406. if (locale.equals(Locale.ROOT)) // Base case
  407. return currencyCode;
  408. return getSymbol(LocaleHelper.getFallbackLocale(locale));
  409. }
  410. /**
  411. * Returns the international ISO4217 currency code of this currency.
  412. *
  413. * @return a <code>String</code> containing the ISO4217 currency code.
  414. */
  415. public String toString()
  416. {
  417. return getCurrencyCode();
  418. }
  419. /**
  420. * Resolves the deserialized object to the singleton instance for its
  421. * particular currency. The currency code of the deserialized instance
  422. * is used to return the correct instance.
  423. *
  424. * @return the singleton instance for the currency specified by the
  425. * currency code of the deserialized object. This replaces
  426. * the deserialized object as the returned object from
  427. * deserialization.
  428. * @throws ObjectStreamException if a problem occurs with deserializing
  429. * the object.
  430. */
  431. private Object readResolve()
  432. throws ObjectStreamException
  433. {
  434. return getInstance(currencyCode);
  435. }
  436. }