ResourceBundle.java 19.6 KB
Newer Older
1
/* ResourceBundle -- aids in loading resource bundles
2
   Copyright (C) 1998, 1999, 2001, 2002, 2003 Free Software Foundation, Inc.
Tom Tromey committed
3

Tom Tromey committed
4
This file is part of GNU Classpath.
Tom Tromey committed
5

Tom Tromey committed
6 7 8 9
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
Tom Tromey committed
10

Tom Tromey committed
11 12 13 14
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.
Tom Tromey committed
15

Tom Tromey committed
16 17 18 19
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
Tom Tromey committed
37 38


Tom Tromey committed
39
package java.util;
40

Tom Tromey committed
41 42
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
43 44
import java.io.InputStream;
import java.io.IOException;
45
import gnu.classpath.Configuration;
Tom Tromey committed
46 47

/**
48 49 50 51 52 53 54 55
 * A resource bundle contains locale-specific data. If you need localized
 * data, you can load a resource bundle that matches the locale with
 * <code>getBundle</code>. Now you can get your object by calling
 * <code>getObject</code> or <code>getString</code> on that bundle.
 *
 * <p>When a bundle is demanded for a specific locale, the ResourceBundle
 * is searched in following order (<i>def. language<i> stands for the
 * two letter ISO language code of the default locale (see
Tom Tromey committed
56 57
 * <code>Locale.getDefault()</code>).
 *
58 59 60 61 62 63 64 65
<pre>baseName_<i>language code</i>_<i>country code</i>_<i>variant</i>
baseName_<i>language code</i>_<i>country code</i>
baseName_<i>language code</i>
baseName_<i>def. language</i>_<i>def. country</i>_<i>def. variant</i>
baseName_<i>def. language</i>_<i>def. country</i>
baseName_<i>def. language</i>
baseName</pre>
 *
66
 * <p>A bundle is backed up by less specific bundles (omitting variant, country
67 68 69
 * or language). But it is not backed up by the default language locale.
 *
 * <p>If you provide a bundle for a given locale, say
Tom Tromey committed
70 71 72 73
 * <code>Bundle_en_UK_POSIX</code>, you must also provide a bundle for
 * all sub locales, ie. <code>Bundle_en_UK</code>, <code>Bundle_en</code>, and
 * <code>Bundle</code>.
 *
74 75 76 77 78 79 80 81 82 83 84
 * <p>When a bundle is searched, we look first for a class with the given
 * name, then for a file with <code>.properties</code> extension in the
 * classpath. The name must be a fully qualified classname (with dots as
 * path separators).
 *
 * <p>(Note: This implementation always backs up the class with a properties
 * file if that is existing, but you shouldn't rely on this, if you want to
 * be compatible to the standard JDK.)
 *
 * @author Jochen Hoenicke
 * @author Eric Blake (ebb9@email.byu.edu)
Tom Tromey committed
85
 * @see Locale
86
 * @see ListResourceBundle
Tom Tromey committed
87
 * @see PropertyResourceBundle
88 89 90
 * @since 1.1
 * @status updated to 1.4
 */
Tom Tromey committed
91 92
public abstract class ResourceBundle
{
Tom Tromey committed
93
  /**
94 95
   * The parent bundle. This is consulted when you call getObject and there
   * is no such resource in the current bundle. This field may be null.
Tom Tromey committed
96
   */
Tom Tromey committed
97 98
  protected ResourceBundle parent;

Tom Tromey committed
99
  /**
100
   * The locale of this resource bundle. You can read this with
Tom Tromey committed
101
   * <code>getLocale</code> and it is automatically set in
102
   * <code>getBundle</code>.
Tom Tromey committed
103 104 105
   */
  private Locale locale;

Tom Tromey committed
106
  private static native ClassLoader getCallingClassLoader();
107 108

  /**
109 110 111 112 113
   * The resource bundle cache. This is a two-level hash map: The key
   * is the class loader, the value is a new HashMap. The key of this
   * second hash map is the localized name, the value is a soft
   * references to the resource bundle.
   */
114 115 116 117 118 119 120
  private static Map resourceBundleCache;

  /**
   * The last default Locale we saw. If this ever changes then we have to
   * reset our caches.
   */
  private static Locale lastDefaultLocale;
121 122 123 124 125 126 127 128 129

  /**
   * The `empty' locale is created once in order to optimize
   * tryBundle().
   */
  private static final Locale emptyLocale = new Locale("");

  /**
   * The constructor. It does nothing special.
Tom Tromey committed
130 131
   */
  public ResourceBundle()
Bryce McKinlay committed
132 133
  {
  }
Tom Tromey committed
134

Tom Tromey committed
135
  /**
136 137 138 139 140 141 142 143
   * Get a String from this resource bundle. Since most localized Objects
   * are Strings, this method provides a convenient way to get them without
   * casting.
   *
   * @param key the name of the resource
   * @throws MissingResourceException if the resource can't be found
   * @throws NullPointerException if key is null
   * @throws ClassCastException if resource is not a string
Tom Tromey committed
144
   */
145
  public final String getString(String key)
Tom Tromey committed
146 147 148
  {
    return (String) getObject(key);
  }
Tom Tromey committed
149

Tom Tromey committed
150
  /**
151
   * Get an array of Strings from this resource bundle. This method
Tom Tromey committed
152
   * provides a convenient way to get it without casting.
153 154 155 156 157
   *
   * @param key the name of the resource
   * @throws MissingResourceException if the resource can't be found
   * @throws NullPointerException if key is null
   * @throws ClassCastException if resource is not a string
Tom Tromey committed
158 159 160 161 162
   */
  public final String[] getStringArray(String key)
  {
    return (String[]) getObject(key);
  }
Tom Tromey committed
163

Tom Tromey committed
164
  /**
165 166 167 168 169 170 171
   * Get an object from this resource bundle. This will call
   * <code>handleGetObject</code> for this resource and all of its parents,
   * until it finds a non-null resource.
   *
   * @param key the name of the resource
   * @throws MissingResourceException if the resource can't be found
   * @throws NullPointerException if key is null
Tom Tromey committed
172
   */
173
  public final Object getObject(String key)
Tom Tromey committed
174 175
  {
    for (ResourceBundle bundle = this; bundle != null; bundle = bundle.parent)
176 177 178 179 180 181 182 183 184
      try
        {
          Object o = bundle.handleGetObject(key);
          if (o != null)
            return o;
        }
      catch (MissingResourceException ex)
        {
        }
185 186 187
 
    throw new MissingResourceException("Key not found", getClass().getName(),
				       key);
Tom Tromey committed
188
  }
Tom Tromey committed
189

Tom Tromey committed
190
  /**
191 192 193 194 195
   * Return the actual locale of this bundle. You can use it after calling
   * getBundle, to know if the bundle for the desired locale was loaded or
   * if the fall back was used.
   *
   * @return the bundle's locale
196
   */
197
  public Locale getLocale()
Tom Tromey committed
198
  {
199
    return locale;
Tom Tromey committed
200
  }
Tom Tromey committed
201

Tom Tromey committed
202
  /**
203 204 205 206
   * Set the parent of this bundle. The parent is consulted when you call
   * getObject and there is no such resource in the current bundle.
   *
   * @param parent the parent of this bundle
Tom Tromey committed
207
   */
208
  protected void setParent(ResourceBundle parent)
Tom Tromey committed
209
  {
210
    this.parent = parent;
Tom Tromey committed
211
  }
Tom Tromey committed
212

Tom Tromey committed
213
  /**
214 215 216 217 218 219 220 221 222
   * Get the appropriate ResourceBundle for the default locale. This is like
   * calling <code>getBundle(baseName, Locale.getDefault(),
   * getClass().getClassLoader()</code>, except that any security check of
   * getClassLoader won't fail.
   *
   * @param baseName the name of the ResourceBundle
   * @return the desired resource bundle
   * @throws MissingResourceException if the resource bundle can't be found
   * @throws NullPointerException if baseName is null
Tom Tromey committed
223
   */
224
  public static final ResourceBundle getBundle(String baseName)
Tom Tromey committed
225
  {
226
    return getBundle(baseName, Locale.getDefault(),
Tom Tromey committed
227
                     getCallingClassLoader());
Tom Tromey committed
228
  }
Tom Tromey committed
229

Tom Tromey committed
230
  /**
231 232 233 234
   * Get the appropriate ResourceBundle for the given locale. This is like
   * calling <code>getBundle(baseName, locale,
   * getClass().getClassLoader()</code>, except that any security check of
   * getClassLoader won't fail.
Tom Tromey committed
235
   *
236 237 238 239 240
   * @param baseName the name of the ResourceBundle
   * @param locale A locale
   * @return the desired resource bundle
   * @throws MissingResourceException if the resource bundle can't be found
   * @throws NullPointerException if baseName or locale is null
Tom Tromey committed
241
   */
242 243
  public static final ResourceBundle getBundle(String baseName,
                                               Locale locale)
244
  {
Tom Tromey committed
245
    return getBundle(baseName, locale, getCallingClassLoader());
246 247
  }

Tom Tromey committed
248
  /**
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
   * Get the appropriate ResourceBundle for the given locale. The following
   * strategy is used:
   *
   * <p>A sequence of candidate bundle names are generated, and tested in
   * this order, where the suffix 1 means the string from the specified
   * locale, and the suffix 2 means the string from the default locale:<ul>
   * <li>baseName + "_" + language1 + "_" + country1 + "_" + variant1</li>
   * <li>baseName + "_" + language1 + "_" + country1</li>
   * <li>baseName + "_" + language1</li>
   * <li>baseName + "_" + language2 + "_" + country2 + "_" + variant2</li>
   * <li>baseName + "_" + language2 + "_" + country2</li>
   * <li>baseName + "_" + language2<li>
   * <li>baseName</li>
   * </ul>
   *
   * <p>In the sequence, entries with an empty string are ignored. Next,
   * <code>getBundle</code> tries to instantiate the resource bundle:<ul>
   * <li>First, an attempt is made to load a class in the specified classloader
   * which is a subclass of ResourceBundle, and which has a public constructor
   * with no arguments, via reflection.</li>
   * <li>Next, a search is made for a property resource file, by replacing
   * '.' with '/' and appending ".properties", and using
   * ClassLoader.getResource(). If a file is found, then a
   * PropertyResourceBundle is created from the file's contents.</li>
   * </ul>
   * If no resource bundle was found, a MissingResourceException is thrown.
   *
   * <p>Next, the parent chain is implemented. The remaining candidate names
   * in the above sequence are tested in a similar manner, and if any results
   * in a resource bundle, it is assigned as the parent of the first bundle
   * using the <code>setParent</code> method (unless the first bundle already
   * has a parent).
   *
   * <p>For example, suppose the following class and property files are
   * provided: MyResources.class, MyResources_fr_CH.properties,
   * MyResources_fr_CH.class, MyResources_fr.properties,
   * MyResources_en.properties, and MyResources_es_ES.class. The contents of
   * all files are valid (that is, public non-abstract subclasses of
   * ResourceBundle with public nullary constructors for the ".class" files,
   * syntactically correct ".properties" files). The default locale is
   * Locale("en", "UK").
   *
   * <p>Calling getBundle with the shown locale argument values instantiates
   * resource bundles from the following sources:<ul>
   * <li>Locale("fr", "CH"): result MyResources_fr_CH.class, parent
   *   MyResources_fr.properties, parent MyResources.class</li>
   * <li>Locale("fr", "FR"): result MyResources_fr.properties, parent
   *   MyResources.class</li>
   * <li>Locale("de", "DE"): result MyResources_en.properties, parent
   *   MyResources.class</li>
   * <li>Locale("en", "US"): result MyResources_en.properties, parent
   *   MyResources.class</li>
   * <li>Locale("es", "ES"): result MyResources_es_ES.class, parent
   *   MyResources.class</li>
   * </ul>
   * The file MyResources_fr_CH.properties is never used because it is hidden
   * by MyResources_fr_CH.class.
   *
   * @param baseName the name of the ResourceBundle
   * @param locale A locale
   * @param classloader a ClassLoader
Tom Tromey committed
310
   * @return the desired resource bundle
311 312 313
   * @throws MissingResourceException if the resource bundle can't be found
   * @throws NullPointerException if any argument is null
   * @since 1.2
Tom Tromey committed
314 315 316
   */
  // This method is synchronized so that the cache is properly
  // handled.
317 318
  public static final synchronized ResourceBundle getBundle
    (String baseName, Locale locale, ClassLoader classLoader)
Tom Tromey committed
319 320 321
  {
    // This implementation searches the bundle in the reverse direction
    // and builds the parent chain on the fly.
322 323 324 325 326 327
    Locale defaultLocale = Locale.getDefault();
    if (defaultLocale != lastDefaultLocale)
      {
	resourceBundleCache = new HashMap();
	lastDefaultLocale = defaultLocale;
      }
Tom Tromey committed
328
    HashMap cache = (HashMap) resourceBundleCache.get(classLoader);
329 330 331 332
    StringBuffer sb = new StringBuffer(60);
    sb.append(baseName).append('_').append(locale);
    String name = sb.toString();

Tom Tromey committed
333 334
    if (cache == null)
      {
335 336
        cache = new HashMap();
        resourceBundleCache.put(classLoader, cache);
Tom Tromey committed
337
      }
338
    else if (cache.containsKey(name))
Tom Tromey committed
339
      {
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
	Reference ref = (Reference) cache.get(name);
	ResourceBundle result = null;
	// If REF is null, that means that we added a `null' value to
	// the hash map.  That means we failed to find the bundle
	// previously, and we cached that fact.  The JDK does this, so
	// it must be ok.
	if (ref == null)
	  throw new MissingResourceException("Bundle " + baseName
					     + " not found",
					     baseName, "");
	else
	  {
	    ResourceBundle rb = (ResourceBundle) ref.get();
	    if (rb != null)
	      {
		// RB should already have the right parent, except if
		// something very strange happened.
		return rb;
	      }
	    // If RB is null, then we previously found it but it was
	    // collected.  So we try again.
	  }
Tom Tromey committed
362 363
      }

364 365
    // It is ok if this returns null.  We aren't required to have the
    // base bundle.
Anthony Green committed
366
    ResourceBundle baseBundle = tryBundle(baseName, emptyLocale,
367
                                          classLoader, null, cache);
Tom Tromey committed
368

369 370 371 372
    // Now use our locale, followed by the default locale.  We only
    // need to try the default locale if our locale is different, and
    // if our locale failed to yield a result other than the base
    // bundle.
Tom Tromey committed
373
    ResourceBundle bundle = tryLocalBundle(baseName, locale,
374
                                           classLoader, baseBundle, cache);
375
    if (bundle == baseBundle && !locale.equals(defaultLocale))
376
      {
377
	bundle = tryLocalBundle(baseName, defaultLocale,
378 379 380 381 382 383 384 385 386
				classLoader, baseBundle, cache);
	// We need to record that the argument locale maps to the
	// bundle we just found.  If we didn't find a bundle, record
	// that instead.
	if (bundle == null)
	  cache.put(name, null);
	else
	  cache.put(name, new SoftReference(bundle));
      }
387

388 389 390
    if (bundle == null)
      throw new MissingResourceException("Bundle " + baseName + " not found",
					 baseName, "");
391

Tom Tromey committed
392 393
    return bundle;
  }
394

Tom Tromey committed
395
  /**
396 397 398 399 400 401 402 403 404
   * Override this method to provide the resource for a keys. This gets
   * called by <code>getObject</code>. If you don't have a resource
   * for the given key, you should return null instead throwing a
   * MissingResourceException. You don't have to ask the parent, getObject()
   * already does this; nor should you throw a MissingResourceException.
   *
   * @param key the key of the resource
   * @return the resource for the key, or null if not in bundle
   * @throws NullPointerException if key is null
Tom Tromey committed
405
   */
406
  protected abstract Object handleGetObject(String key);
Tom Tromey committed
407

Tom Tromey committed
408
  /**
409 410 411 412 413
   * This method should return all keys for which a resource exists; you
   * should include the enumeration of any parent's keys, after filtering out
   * duplicates.
   *
   * @return an enumeration of the keys
Tom Tromey committed
414
   */
415
  public abstract Enumeration getKeys();
Tom Tromey committed
416

Tom Tromey committed
417
  /**
418
   * Tries to load a class or a property file with the specified name.
Tom Tromey committed
419
   *
420 421 422 423 424
   * @param localizedName the name
   * @param locale the locale, that must be used exactly
   * @param classloader the classloader
   * @param bundle the backup (parent) bundle
   * @return the resource bundle if it was loaded, otherwise the backup
Tom Tromey committed
425
   */
426 427 428 429 430 431 432
  private static final ResourceBundle tryBundle(String localizedName,
                                                Locale locale,
                                                ClassLoader classloader,
                                                ResourceBundle bundle,
                                                HashMap cache)
  {
    // First look into the cache.
433
    if (cache.containsKey(localizedName))
434
      {
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
	Reference ref = (Reference) cache.get(localizedName);
	ResourceBundle result = null;
	// If REF is null, that means that we added a `null' value to
	// the hash map.  That means we failed to find the bundle
	// previously, and we cached that fact.  The JDK does this, so
	// it must be ok.
	if (ref == null)
	  return null;
	else
	  {
	    ResourceBundle rb = (ResourceBundle) ref.get();
	    if (rb != null)
	      {
		// RB should already have the right parent, except if
		// something very strange happened.
		return rb;
	      }
	    // If RB is null, then we previously found it but it was
	    // collected.  So we try again.
	  }
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
      }

    // foundBundle holds exact matches for the localizedName resource
    // bundle, which may later be cached.
    ResourceBundle foundBundle = null;
    try
      {
        Class rbClass;
        if (classloader == null)
          rbClass = Class.forName(localizedName);
        else
          rbClass = classloader.loadClass(localizedName);
        foundBundle = (ResourceBundle) rbClass.newInstance();
        foundBundle.parent = bundle;
        foundBundle.locale = locale;
      }
    catch (Exception ex)
      {
        // ignore them all
474
	foundBundle = null;
475 476
      }
    if (foundBundle == null)
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
      {
	try
	  {
	    InputStream is;
	    final String resourceName
	      = localizedName.replace('.', '/') + ".properties";
	    if (classloader == null)
	      is = ClassLoader.getSystemResourceAsStream(resourceName);
	    else
	      is = classloader.getResourceAsStream(resourceName);
	    if (is != null)
	      {
		foundBundle = new PropertyResourceBundle(is);
		foundBundle.parent = bundle;
		foundBundle.locale = locale;
	      }
	  }
	catch (IOException ex)
	  {
	  }
      }
498

499 500 501 502 503 504 505 506
    // Put the result into the hash table.  If we didn't find anything
    // here, we record our parent bundle.  If we record `null' that means
    // nothing, not even the base, was found.
    if (foundBundle == null)
      foundBundle = bundle;
    if (foundBundle == null)
      cache.put(localizedName, null);
    else
507
      cache.put(localizedName, new SoftReference(foundBundle));
508
    return foundBundle;
509
  }
Tom Tromey committed
510

Tom Tromey committed
511
  /**
512 513 514 515
   * Tries to load a the bundle for a given locale, also loads the backup
   * locales with the same language.
   *
   * @param name the name
516
   * @param locale the locale
517 518 519
   * @param classloader the classloader
   * @param bundle the backup (parent) bundle
   * @return the resource bundle if it was loaded, otherwise the backup
Tom Tromey committed
520
   */
521
  private static final ResourceBundle tryLocalBundle(String baseName,
522
						     Locale locale,
523 524 525 526 527
                                                     ClassLoader classloader,
                                                     ResourceBundle bundle,
                                                     HashMap cache)
  {
    final String language = locale.getLanguage();
528 529 530
    final String country = locale.getCountry();
    final String variant = locale.getVariant();

531
    StringBuffer sb = new StringBuffer(60);
532 533
    sb.append(baseName);
    sb.append('_');
534 535 536

    if (language.length() > 0)
      {
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
	sb.append(language);
	bundle = tryBundle(sb.toString(), new Locale(language),
			   classloader, bundle, cache);
      }
    // If LANGUAGE was empty, we still need to try the other
    // components, and the `_' is required.
    sb.append('_');

    if (country.length() > 0)
      {
	sb.append(country);
	bundle = tryBundle(sb.toString(), new Locale(language, country),
			   classloader, bundle, cache);
      }
    sb.append('_');

    if (variant.length() > 0)
      {
	sb.append(variant);
	bundle = tryBundle(sb.toString(), locale,
			   classloader, bundle, cache);
558
      }
559

560 561
    return bundle;
  }
562
}