ResourceBundle.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /* ResourceBundle -- aids in loading resource bundles
  2. Copyright (C) 1998, 1999, 2001, 2002, 2003, 2004, 2005, 2006
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.util;
  33. import gnu.classpath.VMStackWalker;
  34. import gnu.java.lang.CPStringBuilder;
  35. import java.io.IOException;
  36. import java.io.InputStream;
  37. /**
  38. * A resource bundle contains locale-specific data. If you need localized
  39. * data, you can load a resource bundle that matches the locale with
  40. * <code>getBundle</code>. Now you can get your object by calling
  41. * <code>getObject</code> or <code>getString</code> on that bundle.
  42. *
  43. * <p>When a bundle is demanded for a specific locale, the ResourceBundle
  44. * is searched in following order (<i>def. language</i> stands for the
  45. * two letter ISO language code of the default locale (see
  46. * <code>Locale.getDefault()</code>).
  47. *
  48. <pre>baseName_<i>language code</i>_<i>country code</i>_<i>variant</i>
  49. baseName_<i>language code</i>_<i>country code</i>
  50. baseName_<i>language code</i>
  51. baseName_<i>def. language</i>_<i>def. country</i>_<i>def. variant</i>
  52. baseName_<i>def. language</i>_<i>def. country</i>
  53. baseName_<i>def. language</i>
  54. baseName</pre>
  55. *
  56. * <p>A bundle is backed up by less specific bundles (omitting variant, country
  57. * or language). But it is not backed up by the default language locale.
  58. *
  59. * <p>If you provide a bundle for a given locale, say
  60. * <code>Bundle_en_UK_POSIX</code>, you must also provide a bundle for
  61. * all sub locales, ie. <code>Bundle_en_UK</code>, <code>Bundle_en</code>, and
  62. * <code>Bundle</code>.
  63. *
  64. * <p>When a bundle is searched, we look first for a class with the given
  65. * name, then for a file with <code>.properties</code> extension in the
  66. * classpath. The name must be a fully qualified classname (with dots as
  67. * path separators).
  68. *
  69. * <p>(Note: This implementation always backs up the class with a properties
  70. * file if that is existing, but you shouldn't rely on this, if you want to
  71. * be compatible to the standard JDK.)
  72. *
  73. * @author Jochen Hoenicke
  74. * @author Eric Blake (ebb9@email.byu.edu)
  75. * @see Locale
  76. * @see ListResourceBundle
  77. * @see PropertyResourceBundle
  78. * @since 1.1
  79. * @status updated to 1.4
  80. */
  81. public abstract class ResourceBundle
  82. {
  83. /**
  84. * Maximum size of our cache of <code>ResourceBundle</code>s keyed by
  85. * {@link BundleKey} instances.
  86. *
  87. * @see BundleKey
  88. */
  89. private static final int CACHE_SIZE = 100;
  90. /**
  91. * The parent bundle. This is consulted when you call getObject and there
  92. * is no such resource in the current bundle. This field may be null.
  93. */
  94. protected ResourceBundle parent;
  95. /**
  96. * The locale of this resource bundle. You can read this with
  97. * <code>getLocale</code> and it is automatically set in
  98. * <code>getBundle</code>.
  99. */
  100. private Locale locale;
  101. /**
  102. * A VM-wide cache of resource bundles already fetched.
  103. * <p>
  104. * This {@link Map} is a Least Recently Used (LRU) cache, of the last
  105. * {@link #CACHE_SIZE} accessed <code>ResourceBundle</code>s keyed by the
  106. * tuple: default locale, resource-bundle name, resource-bundle locale, and
  107. * classloader.
  108. *
  109. * @see BundleKey
  110. */
  111. private static Map<BundleKey,Object> bundleCache =
  112. new LinkedHashMap<BundleKey,Object>(CACHE_SIZE + 1, 0.75F, true)
  113. {
  114. public boolean removeEldestEntry(Map.Entry<BundleKey,Object> entry)
  115. {
  116. return size() > CACHE_SIZE;
  117. }
  118. };
  119. /**
  120. * The constructor. It does nothing special.
  121. */
  122. public ResourceBundle()
  123. {
  124. }
  125. /**
  126. * Get a String from this resource bundle. Since most localized Objects
  127. * are Strings, this method provides a convenient way to get them without
  128. * casting.
  129. *
  130. * @param key the name of the resource
  131. * @throws MissingResourceException if the resource can't be found
  132. * @throws NullPointerException if key is null
  133. * @throws ClassCastException if resource is not a string
  134. */
  135. public final String getString(String key)
  136. {
  137. return (String) getObject(key);
  138. }
  139. /**
  140. * Get an array of Strings from this resource bundle. This method
  141. * provides a convenient way to get it without casting.
  142. *
  143. * @param key the name of the resource
  144. * @throws MissingResourceException if the resource can't be found
  145. * @throws NullPointerException if key is null
  146. * @throws ClassCastException if resource is not a string
  147. */
  148. public final String[] getStringArray(String key)
  149. {
  150. return (String[]) getObject(key);
  151. }
  152. /**
  153. * Get an object from this resource bundle. This will call
  154. * <code>handleGetObject</code> for this resource and all of its parents,
  155. * until it finds a non-null resource.
  156. *
  157. * @param key the name of the resource
  158. * @throws MissingResourceException if the resource can't be found
  159. * @throws NullPointerException if key is null
  160. */
  161. public final Object getObject(String key)
  162. {
  163. for (ResourceBundle bundle = this; bundle != null; bundle = bundle.parent)
  164. {
  165. Object o = bundle.handleGetObject(key);
  166. if (o != null)
  167. return o;
  168. }
  169. String className = getClass().getName();
  170. throw new MissingResourceException("Key '" + key
  171. + "'not found in Bundle: "
  172. + className, className, key);
  173. }
  174. /**
  175. * Return the actual locale of this bundle. You can use it after calling
  176. * getBundle, to know if the bundle for the desired locale was loaded or
  177. * if the fall back was used.
  178. *
  179. * @return the bundle's locale
  180. */
  181. public Locale getLocale()
  182. {
  183. return locale;
  184. }
  185. /**
  186. * Set the parent of this bundle. The parent is consulted when you call
  187. * getObject and there is no such resource in the current bundle.
  188. *
  189. * @param parent the parent of this bundle
  190. */
  191. protected void setParent(ResourceBundle parent)
  192. {
  193. this.parent = parent;
  194. }
  195. /**
  196. * Get the appropriate ResourceBundle for the default locale. This is like
  197. * calling <code>getBundle(baseName, Locale.getDefault(),
  198. * getClass().getClassLoader()</code>, except that any security check of
  199. * getClassLoader won't fail.
  200. *
  201. * @param baseName the name of the ResourceBundle
  202. * @return the desired resource bundle
  203. * @throws MissingResourceException if the resource bundle can't be found
  204. * @throws NullPointerException if baseName is null
  205. */
  206. public static ResourceBundle getBundle(String baseName)
  207. {
  208. ClassLoader cl = VMStackWalker.getCallingClassLoader();
  209. if (cl == null)
  210. cl = ClassLoader.getSystemClassLoader();
  211. return getBundle(baseName, Locale.getDefault(), cl);
  212. }
  213. /**
  214. * Get the appropriate ResourceBundle for the given locale. This is like
  215. * calling <code>getBundle(baseName, locale,
  216. * getClass().getClassLoader()</code>, except that any security check of
  217. * getClassLoader won't fail.
  218. *
  219. * @param baseName the name of the ResourceBundle
  220. * @param locale A locale
  221. * @return the desired resource bundle
  222. * @throws MissingResourceException if the resource bundle can't be found
  223. * @throws NullPointerException if baseName or locale is null
  224. */
  225. public static ResourceBundle getBundle(String baseName, Locale locale)
  226. {
  227. ClassLoader cl = VMStackWalker.getCallingClassLoader();
  228. if (cl == null)
  229. cl = ClassLoader.getSystemClassLoader();
  230. return getBundle(baseName, locale, cl);
  231. }
  232. /** Cache key for the ResourceBundle cache. Resource bundles are keyed
  233. by the combination of bundle name, locale, and class loader. */
  234. private static class BundleKey
  235. {
  236. Locale defaultLocale;
  237. String baseName;
  238. Locale locale;
  239. ClassLoader classLoader;
  240. int hashcode;
  241. BundleKey() {}
  242. BundleKey(Locale dl, String s, Locale l, ClassLoader cl)
  243. {
  244. set(dl, s, l, cl);
  245. }
  246. void set(Locale dl, String s, Locale l, ClassLoader cl)
  247. {
  248. defaultLocale = dl;
  249. baseName = s;
  250. locale = l;
  251. classLoader = cl;
  252. hashcode = defaultLocale.hashCode() ^ baseName.hashCode()
  253. ^ locale.hashCode() ^ classLoader.hashCode();
  254. }
  255. public int hashCode()
  256. {
  257. return hashcode;
  258. }
  259. public boolean equals(Object o)
  260. {
  261. if (! (o instanceof BundleKey))
  262. return false;
  263. BundleKey key = (BundleKey) o;
  264. return hashcode == key.hashcode
  265. && defaultLocale.equals(key.defaultLocale)
  266. && baseName.equals(key.baseName)
  267. && locale.equals(key.locale)
  268. && classLoader.equals(key.classLoader);
  269. }
  270. public String toString()
  271. {
  272. CPStringBuilder builder = new CPStringBuilder(getClass().getName());
  273. builder.append("[defaultLocale=");
  274. builder.append(defaultLocale);
  275. builder.append(",baseName=");
  276. builder.append(baseName);
  277. builder.append(",locale=");
  278. builder.append(locale);
  279. builder.append(",classLoader=");
  280. builder.append(classLoader);
  281. builder.append("]");
  282. return builder.toString();
  283. }
  284. }
  285. /** A cache lookup key. This avoids having to a new one for every
  286. * getBundle() call. */
  287. private static final BundleKey lookupKey = new BundleKey();
  288. /** Singleton cache entry to represent previous failed lookups. */
  289. private static final Object nullEntry = new Object();
  290. /**
  291. * Get the appropriate ResourceBundle for the given locale. The following
  292. * strategy is used:
  293. *
  294. * <p>A sequence of candidate bundle names are generated, and tested in
  295. * this order, where the suffix 1 means the string from the specified
  296. * locale, and the suffix 2 means the string from the default locale:</p>
  297. *
  298. * <ul>
  299. * <li>baseName + "_" + language1 + "_" + country1 + "_" + variant1</li>
  300. * <li>baseName + "_" + language1 + "_" + country1</li>
  301. * <li>baseName + "_" + language1</li>
  302. * <li>baseName + "_" + language2 + "_" + country2 + "_" + variant2</li>
  303. * <li>baseName + "_" + language2 + "_" + country2</li>
  304. * <li>baseName + "_" + language2</li>
  305. * <li>baseName</li>
  306. * </ul>
  307. *
  308. * <p>In the sequence, entries with an empty string are ignored. Next,
  309. * <code>getBundle</code> tries to instantiate the resource bundle:</p>
  310. *
  311. * <ul>
  312. * <li>First, an attempt is made to load a class in the specified classloader
  313. * which is a subclass of ResourceBundle, and which has a public constructor
  314. * with no arguments, via reflection.</li>
  315. * <li>Next, a search is made for a property resource file, by replacing
  316. * '.' with '/' and appending ".properties", and using
  317. * ClassLoader.getResource(). If a file is found, then a
  318. * PropertyResourceBundle is created from the file's contents.</li>
  319. * </ul>
  320. * If no resource bundle was found, a MissingResourceException is thrown.
  321. *
  322. * <p>Next, the parent chain is implemented. The remaining candidate names
  323. * in the above sequence are tested in a similar manner, and if any results
  324. * in a resource bundle, it is assigned as the parent of the first bundle
  325. * using the <code>setParent</code> method (unless the first bundle already
  326. * has a parent).</p>
  327. *
  328. * <p>For example, suppose the following class and property files are
  329. * provided: MyResources.class, MyResources_fr_CH.properties,
  330. * MyResources_fr_CH.class, MyResources_fr.properties,
  331. * MyResources_en.properties, and MyResources_es_ES.class. The contents of
  332. * all files are valid (that is, public non-abstract subclasses of
  333. * ResourceBundle with public nullary constructors for the ".class" files,
  334. * syntactically correct ".properties" files). The default locale is
  335. * Locale("en", "UK").</p>
  336. *
  337. * <p>Calling getBundle with the shown locale argument values instantiates
  338. * resource bundles from the following sources:</p>
  339. *
  340. * <ul>
  341. * <li>Locale("fr", "CH"): result MyResources_fr_CH.class, parent
  342. * MyResources_fr.properties, parent MyResources.class</li>
  343. * <li>Locale("fr", "FR"): result MyResources_fr.properties, parent
  344. * MyResources.class</li>
  345. * <li>Locale("de", "DE"): result MyResources_en.properties, parent
  346. * MyResources.class</li>
  347. * <li>Locale("en", "US"): result MyResources_en.properties, parent
  348. * MyResources.class</li>
  349. * <li>Locale("es", "ES"): result MyResources_es_ES.class, parent
  350. * MyResources.class</li>
  351. * </ul>
  352. *
  353. * <p>The file MyResources_fr_CH.properties is never used because it is hidden
  354. * by MyResources_fr_CH.class.</p>
  355. *
  356. * @param baseName the name of the ResourceBundle
  357. * @param locale A locale
  358. * @param classLoader a ClassLoader
  359. * @return the desired resource bundle
  360. * @throws MissingResourceException if the resource bundle can't be found
  361. * @throws NullPointerException if any argument is null
  362. * @since 1.2
  363. */
  364. // This method is synchronized so that the cache is properly
  365. // handled.
  366. public static synchronized ResourceBundle getBundle
  367. (String baseName, Locale locale, ClassLoader classLoader)
  368. {
  369. Locale defaultLocale = Locale.getDefault();
  370. // This will throw NullPointerException if any arguments are null.
  371. lookupKey.set(defaultLocale, baseName, locale, classLoader);
  372. Object obj = bundleCache.get(lookupKey);
  373. if (obj instanceof ResourceBundle)
  374. return (ResourceBundle) obj;
  375. if (obj == nullEntry)
  376. throw new MissingResourceException("Bundle " + baseName
  377. + " not found for locale " + locale
  378. + " by classloader " + classLoader,
  379. baseName, "");
  380. // First, look for a bundle for the specified locale. We don't want
  381. // the base bundle this time.
  382. boolean wantBase = locale.equals(defaultLocale);
  383. ResourceBundle bundle = tryBundle(baseName, locale, classLoader, wantBase);
  384. // Try the default locale if neccessary.
  385. if (bundle == null && ! wantBase)
  386. bundle = tryBundle(baseName, defaultLocale, classLoader, true);
  387. BundleKey key = new BundleKey(defaultLocale, baseName, locale, classLoader);
  388. if (bundle == null)
  389. {
  390. // Cache the fact that this lookup has previously failed.
  391. bundleCache.put(key, nullEntry);
  392. throw new MissingResourceException("Bundle " + baseName
  393. + " not found for locale " + locale
  394. + " by classloader " + classLoader,
  395. baseName, "");
  396. }
  397. // Cache the result and return it.
  398. bundleCache.put(key, bundle);
  399. return bundle;
  400. }
  401. /**
  402. * Override this method to provide the resource for a keys. This gets
  403. * called by <code>getObject</code>. If you don't have a resource
  404. * for the given key, you should return null instead throwing a
  405. * MissingResourceException. You don't have to ask the parent, getObject()
  406. * already does this; nor should you throw a MissingResourceException.
  407. *
  408. * @param key the key of the resource
  409. * @return the resource for the key, or null if not in bundle
  410. * @throws NullPointerException if key is null
  411. */
  412. protected abstract Object handleGetObject(String key);
  413. /**
  414. * This method should return all keys for which a resource exists; you
  415. * should include the enumeration of any parent's keys, after filtering out
  416. * duplicates.
  417. *
  418. * @return an enumeration of the keys
  419. */
  420. public abstract Enumeration<String> getKeys();
  421. /**
  422. * Tries to load a class or a property file with the specified name.
  423. *
  424. * @param localizedName the name
  425. * @param classloader the classloader
  426. * @return the resource bundle if it was loaded, otherwise the backup
  427. */
  428. private static ResourceBundle tryBundle(String localizedName,
  429. ClassLoader classloader)
  430. {
  431. ResourceBundle bundle = null;
  432. try
  433. {
  434. Class<?> rbClass;
  435. if (classloader == null)
  436. rbClass = Class.forName(localizedName);
  437. else
  438. rbClass = classloader.loadClass(localizedName);
  439. // Note that we do the check up front instead of catching
  440. // ClassCastException. The reason for this is that some crazy
  441. // programs (Eclipse) have classes that do not extend
  442. // ResourceBundle but that have the same name as a property
  443. // bundle; in fact Eclipse relies on ResourceBundle not
  444. // instantiating these classes.
  445. if (ResourceBundle.class.isAssignableFrom(rbClass))
  446. bundle = (ResourceBundle) rbClass.newInstance();
  447. }
  448. catch (Exception ex) {}
  449. if (bundle == null)
  450. {
  451. try
  452. {
  453. InputStream is;
  454. String resourceName
  455. = localizedName.replace('.', '/') + ".properties";
  456. if (classloader == null)
  457. is = ClassLoader.getSystemResourceAsStream(resourceName);
  458. else
  459. is = classloader.getResourceAsStream(resourceName);
  460. if (is != null)
  461. bundle = new PropertyResourceBundle(is);
  462. }
  463. catch (IOException ex)
  464. {
  465. MissingResourceException mre = new MissingResourceException
  466. ("Failed to load bundle: " + localizedName, localizedName, "");
  467. mre.initCause(ex);
  468. throw mre;
  469. }
  470. }
  471. return bundle;
  472. }
  473. /**
  474. * Tries to load the bundle for a given locale, also loads the backup
  475. * locales with the same language.
  476. *
  477. * @param baseName the raw bundle name, without locale qualifiers
  478. * @param locale the locale
  479. * @param classLoader the classloader
  480. * @param wantBase whether a resource bundle made only from the base name
  481. * (with no locale information attached) should be returned.
  482. * @return the resource bundle if it was loaded, otherwise the backup
  483. */
  484. private static ResourceBundle tryBundle(String baseName, Locale locale,
  485. ClassLoader classLoader,
  486. boolean wantBase)
  487. {
  488. String language = locale.getLanguage();
  489. String country = locale.getCountry();
  490. String variant = locale.getVariant();
  491. int baseLen = baseName.length();
  492. // Build up a CPStringBuilder containing the complete bundle name, fully
  493. // qualified by locale.
  494. CPStringBuilder sb = new CPStringBuilder(baseLen + variant.length() + 7);
  495. sb.append(baseName);
  496. if (language.length() > 0)
  497. {
  498. sb.append('_');
  499. sb.append(language);
  500. if (country.length() > 0)
  501. {
  502. sb.append('_');
  503. sb.append(country);
  504. if (variant.length() > 0)
  505. {
  506. sb.append('_');
  507. sb.append(variant);
  508. }
  509. }
  510. }
  511. // Now try to load bundles, starting with the most specialized name.
  512. // Build up the parent chain as we go.
  513. String bundleName = sb.toString();
  514. ResourceBundle first = null; // The most specialized bundle.
  515. ResourceBundle last = null; // The least specialized bundle.
  516. while (true)
  517. {
  518. ResourceBundle foundBundle = tryBundle(bundleName, classLoader);
  519. if (foundBundle != null)
  520. {
  521. if (first == null)
  522. first = foundBundle;
  523. if (last != null)
  524. last.parent = foundBundle;
  525. foundBundle.locale = locale;
  526. last = foundBundle;
  527. }
  528. int idx = bundleName.lastIndexOf('_');
  529. // Try the non-localized base name only if we already have a
  530. // localized child bundle, or wantBase is true.
  531. if (idx > baseLen || (idx == baseLen && (first != null || wantBase)))
  532. bundleName = bundleName.substring(0, idx);
  533. else
  534. break;
  535. }
  536. return first;
  537. }
  538. /**
  539. * Remove all resources from the cache that were loaded
  540. * using the class loader of the calling class.
  541. *
  542. * @since 1.6
  543. */
  544. public static final void clearCache()
  545. {
  546. clearCache(VMStackWalker.getCallingClassLoader());
  547. }
  548. /**
  549. * Remove all resources from the cache that were loaded
  550. * using the specified class loader.
  551. *
  552. * @param loader the loader used for the bundles that will be removed.
  553. * @throws NullPointerException if {@code loader} is {@code null}.
  554. * @since 1.6
  555. */
  556. public static final void clearCache(ClassLoader loader)
  557. {
  558. if (loader == null)
  559. throw new NullPointerException("The loader can not be null.");
  560. synchronized (ResourceBundle.class)
  561. {
  562. Iterator<BundleKey> iter = bundleCache.keySet().iterator();
  563. while (iter.hasNext())
  564. {
  565. BundleKey key = iter.next();
  566. if (key.classLoader == loader)
  567. iter.remove();
  568. }
  569. }
  570. }
  571. }