Source for java.util.Currency

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