1 /*
2 * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
3 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
4 *
5 *
6 *
7 *
8 *
9 *
10 *
11 *
12 *
13 *
14 *
15 *
16 *
17 *
18 *
19 *
20 *
21 *
22 *
23 *
24 */
25
26 /*
27 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
28 * (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved
29 *
30 * The original version of this source code and documentation
31 * is copyrighted and owned by Taligent, Inc., a wholly-owned
32 * subsidiary of IBM. These materials are provided under terms
33 * of a License Agreement between Taligent and Sun. This technology
34 * is protected by multiple US and International patents.
35 *
36 * This notice and attribution to Taligent may not be removed.
37 * Taligent is a registered trademark of Taligent, Inc.
38 *
39 */
40
41 package java.util;
42
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.lang.ref.ReferenceQueue;
46 import java.lang.ref.SoftReference;
47 import java.lang.ref.WeakReference;
48 import java.net.JarURLConnection;
49 import java.net.URL;
50 import java.net.URLConnection;
51 import java.security.AccessController;
52 import java.security.PrivilegedAction;
53 import java.security.PrivilegedActionException;
54 import java.security.PrivilegedExceptionAction;
55 import java.util.concurrent.ConcurrentHashMap;
56 import java.util.concurrent.ConcurrentMap;
57 import java.util.jar.JarEntry;
58 import java.util.spi.ResourceBundleControlProvider;
59
60 import sun.reflect.CallerSensitive;
61 import sun.reflect.Reflection;
62 import sun.util.locale.BaseLocale;
63 import sun.util.locale.LocaleObjectCache;
64
65
66 /**
67 *
68 * Resource bundles contain locale-specific objects. When your program needs a
69 * locale-specific resource, a <code>String</code> for example, your program can
70 * load it from the resource bundle that is appropriate for the current user's
71 * locale. In this way, you can write program code that is largely independent
72 * of the user's locale isolating most, if not all, of the locale-specific
73 * information in resource bundles.
74 *
75 * <p>
76 * This allows you to write programs that can:
77 * <UL>
78 * <LI> be easily localized, or translated, into different languages
79 * <LI> handle multiple locales at once
80 * <LI> be easily modified later to support even more locales
81 * </UL>
82 *
83 * <P>
84 * Resource bundles belong to families whose members share a common base
85 * name, but whose names also have additional components that identify
86 * their locales. For example, the base name of a family of resource
87 * bundles might be "MyResources". The family should have a default
88 * resource bundle which simply has the same name as its family -
89 * "MyResources" - and will be used as the bundle of last resort if a
90 * specific locale is not supported. The family can then provide as
91 * many locale-specific members as needed, for example a German one
92 * named "MyResources_de".
93 *
94 * <P>
95 * Each resource bundle in a family contains the same items, but the items have
96 * been translated for the locale represented by that resource bundle.
97 * For example, both "MyResources" and "MyResources_de" may have a
98 * <code>String</code> that's used on a button for canceling operations.
99 * In "MyResources" the <code>String</code> may contain "Cancel" and in
100 * "MyResources_de" it may contain "Abbrechen".
101 *
102 * <P>
103 * If there are different resources for different countries, you
104 * can make specializations: for example, "MyResources_de_CH" contains objects for
105 * the German language (de) in Switzerland (CH). If you want to only
106 * modify some of the resources
107 * in the specialization, you can do so.
108 *
109 * <P>
110 * When your program needs a locale-specific object, it loads
111 * the <code>ResourceBundle</code> class using the
112 * {@link #getBundle(java.lang.String, java.util.Locale) getBundle}
113 * method:
114 * <blockquote>
115 * <pre>
116 * ResourceBundle myResources =
117 * ResourceBundle.getBundle("MyResources", currentLocale);
118 * </pre>
119 * </blockquote>
120 *
121 * <P>
122 * Resource bundles contain key/value pairs. The keys uniquely
123 * identify a locale-specific object in the bundle. Here's an
124 * example of a <code>ListResourceBundle</code> that contains
125 * two key/value pairs:
126 * <blockquote>
127 * <pre>
128 * public class MyResources extends ListResourceBundle {
129 * protected Object[][] getContents() {
130 * return new Object[][] {
131 * // LOCALIZE THE SECOND STRING OF EACH ARRAY (e.g., "OK")
132 * {"OkKey", "OK"},
133 * {"CancelKey", "Cancel"},
134 * // END OF MATERIAL TO LOCALIZE
135 * };
136 * }
137 * }
138 * </pre>
139 * </blockquote>
140 * Keys are always <code>String</code>s.
141 * In this example, the keys are "OkKey" and "CancelKey".
142 * In the above example, the values
143 * are also <code>String</code>s--"OK" and "Cancel"--but
144 * they don't have to be. The values can be any type of object.
145 *
146 * <P>
147 * You retrieve an object from resource bundle using the appropriate
148 * getter method. Because "OkKey" and "CancelKey"
149 * are both strings, you would use <code>getString</code> to retrieve them:
150 * <blockquote>
151 * <pre>
152 * button1 = new Button(myResources.getString("OkKey"));
153 * button2 = new Button(myResources.getString("CancelKey"));
154 * </pre>
155 * </blockquote>
156 * The getter methods all require the key as an argument and return
157 * the object if found. If the object is not found, the getter method
158 * throws a <code>MissingResourceException</code>.
159 *
160 * <P>
161 * Besides <code>getString</code>, <code>ResourceBundle</code> also provides
162 * a method for getting string arrays, <code>getStringArray</code>,
163 * as well as a generic <code>getObject</code> method for any other
164 * type of object. When using <code>getObject</code>, you'll
165 * have to cast the result to the appropriate type. For example:
166 * <blockquote>
167 * <pre>
168 * int[] myIntegers = (int[]) myResources.getObject("intList");
169 * </pre>
170 * </blockquote>
171 *
172 * <P>
173 * The Java Platform provides two subclasses of <code>ResourceBundle</code>,
174 * <code>ListResourceBundle</code> and <code>PropertyResourceBundle</code>,
175 * that provide a fairly simple way to create resources.
176 * As you saw briefly in a previous example, <code>ListResourceBundle</code>
177 * manages its resource as a list of key/value pairs.
178 * <code>PropertyResourceBundle</code> uses a properties file to manage
179 * its resources.
180 *
181 * <p>
182 * If <code>ListResourceBundle</code> or <code>PropertyResourceBundle</code>
183 * do not suit your needs, you can write your own <code>ResourceBundle</code>
184 * subclass. Your subclasses must override two methods: <code>handleGetObject</code>
185 * and <code>getKeys()</code>.
186 *
187 * <p>
188 * The implementation of a {@code ResourceBundle} subclass must be thread-safe
189 * if it's simultaneously used by multiple threads. The default implementations
190 * of the non-abstract methods in this class, and the methods in the direct
191 * known concrete subclasses {@code ListResourceBundle} and
192 * {@code PropertyResourceBundle} are thread-safe.
193 *
194 * <h3>ResourceBundle.Control</h3>
195 *
196 * The {@link ResourceBundle.Control} class provides information necessary
197 * to perform the bundle loading process by the <code>getBundle</code>
198 * factory methods that take a <code>ResourceBundle.Control</code>
199 * instance. You can implement your own subclass in order to enable
200 * non-standard resource bundle formats, change the search strategy, or
201 * define caching parameters. Refer to the descriptions of the class and the
202 * {@link #getBundle(String, Locale, ClassLoader, Control) getBundle}
203 * factory method for details.
204 *
205 * <p><a name="modify_default_behavior">For the {@code getBundle} factory</a>
206 * methods that take no {@link Control} instance, their <a
207 * href="#default_behavior"> default behavior</a> of resource bundle loading
208 * can be modified with <em>installed</em> {@link
209 * ResourceBundleControlProvider} implementations. Any installed providers are
210 * detected at the {@code ResourceBundle} class loading time. If any of the
211 * providers provides a {@link Control} for the given base name, that {@link
212 * Control} will be used instead of the default {@link Control}. If there is
213 * more than one service provider installed for supporting the same base name,
214 * the first one returned from {@link ServiceLoader} will be used.
215 *
216 * <h3>Cache Management</h3>
217 *
218 * Resource bundle instances created by the <code>getBundle</code> factory
219 * methods are cached by default, and the factory methods return the same
220 * resource bundle instance multiple times if it has been
221 * cached. <code>getBundle</code> clients may clear the cache, manage the
222 * lifetime of cached resource bundle instances using time-to-live values,
223 * or specify not to cache resource bundle instances. Refer to the
224 * descriptions of the {@linkplain #getBundle(String, Locale, ClassLoader,
225 * Control) <code>getBundle</code> factory method}, {@link
226 * #clearCache(ClassLoader) clearCache}, {@link
227 * Control#getTimeToLive(String, Locale)
228 * ResourceBundle.Control.getTimeToLive}, and {@link
229 * Control#needsReload(String, Locale, String, ClassLoader, ResourceBundle,
230 * long) ResourceBundle.Control.needsReload} for details.
231 *
232 * <h3>Example</h3>
233 *
234 * The following is a very simple example of a <code>ResourceBundle</code>
235 * subclass, <code>MyResources</code>, that manages two resources (for a larger number of
236 * resources you would probably use a <code>Map</code>).
237 * Notice that you don't need to supply a value if
238 * a "parent-level" <code>ResourceBundle</code> handles the same
239 * key with the same value (as for the okKey below).
240 * <blockquote>
241 * <pre>
242 * // default (English language, United States)
243 * public class MyResources extends ResourceBundle {
244 * public Object handleGetObject(String key) {
245 * if (key.equals("okKey")) return "Ok";
246 * if (key.equals("cancelKey")) return "Cancel";
247 * return null;
248 * }
249 *
250 * public Enumeration<String> getKeys() {
251 * return Collections.enumeration(keySet());
252 * }
253 *
254 * // Overrides handleKeySet() so that the getKeys() implementation
255 * // can rely on the keySet() value.
256 * protected Set<String> handleKeySet() {
257 * return new HashSet<String>(Arrays.asList("okKey", "cancelKey"));
258 * }
259 * }
260 *
261 * // German language
262 * public class MyResources_de extends MyResources {
263 * public Object handleGetObject(String key) {
264 * // don't need okKey, since parent level handles it.
265 * if (key.equals("cancelKey")) return "Abbrechen";
266 * return null;
267 * }
268 *
269 * protected Set<String> handleKeySet() {
270 * return new HashSet<String>(Arrays.asList("cancelKey"));
271 * }
272 * }
273 * </pre>
274 * </blockquote>
275 * You do not have to restrict yourself to using a single family of
276 * <code>ResourceBundle</code>s. For example, you could have a set of bundles for
277 * exception messages, <code>ExceptionResources</code>
278 * (<code>ExceptionResources_fr</code>, <code>ExceptionResources_de</code>, ...),
279 * and one for widgets, <code>WidgetResource</code> (<code>WidgetResources_fr</code>,
280 * <code>WidgetResources_de</code>, ...); breaking up the resources however you like.
281 *
282 * @see ListResourceBundle
283 * @see PropertyResourceBundle
284 * @see MissingResourceException
285 * @since JDK1.1
286 */
287 public abstract class ResourceBundle {
288
289 /** initial size of the bundle cache */
290 private static final int INITIAL_CACHE_SIZE = 32;
291
292 /** constant indicating that no resource bundle exists */
293 private static final ResourceBundle NONEXISTENT_BUNDLE = new ResourceBundle() {
294 public Enumeration<String> getKeys() { return null; }
295 protected Object handleGetObject(String key) { return null; }
296 public String toString() { return "NONEXISTENT_BUNDLE"; }
297 };
298
299
300 /**
301 * The cache is a map from cache keys (with bundle base name, locale, and
302 * class loader) to either a resource bundle or NONEXISTENT_BUNDLE wrapped by a
303 * BundleReference.
304 *
305 * The cache is a ConcurrentMap, allowing the cache to be searched
306 * concurrently by multiple threads. This will also allow the cache keys
307 * to be reclaimed along with the ClassLoaders they reference.
308 *
309 * This variable would be better named "cache", but we keep the old
310 * name for compatibility with some workarounds for bug 4212439.
311 */
312 private static final ConcurrentMap<CacheKey, BundleReference> cacheList
313 = new ConcurrentHashMap<>(INITIAL_CACHE_SIZE);
314
315 /**
316 * Queue for reference objects referring to class loaders or bundles.
317 */
318 private static final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
319
320 /**
321 * Returns the base name of this bundle, if known, or {@code null} if unknown.
322 *
323 * If not null, then this is the value of the {@code baseName} parameter
324 * that was passed to the {@code ResourceBundle.getBundle(...)} method
325 * when the resource bundle was loaded.
326 *
327 * @return The base name of the resource bundle, as provided to and expected
328 * by the {@code ResourceBundle.getBundle(...)} methods.
329 *
330 * @see #getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader)
331 *
332 * @since 1.8
333 */
334 public String getBaseBundleName() {
335 return name;
336 }
337
338 /**
339 * The parent bundle of this bundle.
340 * The parent bundle is searched by {@link #getObject getObject}
341 * when this bundle does not contain a particular resource.
342 */
343 protected ResourceBundle parent = null;
344
345 /**
346 * The locale for this bundle.
347 */
348 private Locale locale = null;
349
350 /**
351 * The base bundle name for this bundle.
352 */
353 private String name;
354
355 /**
356 * The flag indicating this bundle has expired in the cache.
357 */
358 private volatile boolean expired;
359
360 /**
361 * The back link to the cache key. null if this bundle isn't in
362 * the cache (yet) or has expired.
363 */
364 private volatile CacheKey cacheKey;
365
366 /**
367 * A Set of the keys contained only in this ResourceBundle.
368 */
369 private volatile Set<String> keySet;
370
371 private static final List<ResourceBundleControlProvider> providers;
372
373 static {
374 List<ResourceBundleControlProvider> list = null;
375 ServiceLoader<ResourceBundleControlProvider> serviceLoaders
376 = ServiceLoader.loadInstalled(ResourceBundleControlProvider.class);
377 for (ResourceBundleControlProvider provider : serviceLoaders) {
378 if (list == null) {
379 list = new ArrayList<>();
380 }
381 list.add(provider);
382 }
383 providers = list;
384 }
385
386 /**
387 * Sole constructor. (For invocation by subclass constructors, typically
388 * implicit.)
389 */
390 public ResourceBundle() {
391 }
392
393 /**
394 * Gets a string for the given key from this resource bundle or one of its parents.
395 * Calling this method is equivalent to calling
396 * <blockquote>
397 * <code>(String) {@link #getObject(java.lang.String) getObject}(key)</code>.
398 * </blockquote>
399 *
400 * @param key the key for the desired string
401 * @exception NullPointerException if <code>key</code> is <code>null</code>
402 * @exception MissingResourceException if no object for the given key can be found
403 * @exception ClassCastException if the object found for the given key is not a string
404 * @return the string for the given key
405 */
406 public final String getString(String key) {
407 return (String) getObject(key);
408 }
409
410 /**
411 * Gets a string array for the given key from this resource bundle or one of its parents.
412 * Calling this method is equivalent to calling
413 * <blockquote>
414 * <code>(String[]) {@link #getObject(java.lang.String) getObject}(key)</code>.
415 * </blockquote>
416 *
417 * @param key the key for the desired string array
418 * @exception NullPointerException if <code>key</code> is <code>null</code>
419 * @exception MissingResourceException if no object for the given key can be found
420 * @exception ClassCastException if the object found for the given key is not a string array
421 * @return the string array for the given key
422 */
423 public final String[] getStringArray(String key) {
424 return (String[]) getObject(key);
425 }
426
427 /**
428 * Gets an object for the given key from this resource bundle or one of its parents.
429 * This method first tries to obtain the object from this resource bundle using
430 * {@link #handleGetObject(java.lang.String) handleGetObject}.
431 * If not successful, and the parent resource bundle is not null,
432 * it calls the parent's <code>getObject</code> method.
433 * If still not successful, it throws a MissingResourceException.
434 *
435 * @param key the key for the desired object
436 * @exception NullPointerException if <code>key</code> is <code>null</code>
437 * @exception MissingResourceException if no object for the given key can be found
438 * @return the object for the given key
439 */
440 public final Object getObject(String key) {
441 Object obj = handleGetObject(key);
442 if (obj == null) {
443 if (parent != null) {
444 obj = parent.getObject(key);
445 }
446 if (obj == null) {
447 throw new MissingResourceException("Can't find resource for bundle "
448 +this.getClass().getName()
449 +", key "+key,
450 this.getClass().getName(),
451 key);
452 }
453 }
454 return obj;
455 }
456
457 /**
458 * Returns the locale of this resource bundle. This method can be used after a
459 * call to getBundle() to determine whether the resource bundle returned really
460 * corresponds to the requested locale or is a fallback.
461 *
462 * @return the locale of this resource bundle
463 */
464 public Locale getLocale() {
465 return locale;
466 }
467
468 /*
469 * Automatic determination of the ClassLoader to be used to load
470 * resources on behalf of the client.
471 */
472 private static ClassLoader getLoader(Class<?> caller) {
473 ClassLoader cl = caller == null ? null : caller.getClassLoader();
474 if (cl == null) {
475 // When the caller's loader is the boot class loader, cl is null
476 // here. In that case, ClassLoader.getSystemClassLoader() may
477 // return the same class loader that the application is
478 // using. We therefore use a wrapper ClassLoader to create a
479 // separate scope for bundles loaded on behalf of the Java
480 // runtime so that these bundles cannot be returned from the
481 // cache to the application (5048280).
482 cl = RBClassLoader.INSTANCE;
483 }
484 return cl;
485 }
486
487 /**
488 * A wrapper of Extension Class Loader
489 */
490 private static class RBClassLoader extends ClassLoader {
491 private static final RBClassLoader INSTANCE = AccessController.doPrivileged(
492 new PrivilegedAction<RBClassLoader>() {
493 public RBClassLoader run() {
494 return new RBClassLoader();
495 }
496 });
497 private static final ClassLoader loader;
498 static {
499 // Find the extension class loader.
500 ClassLoader ld = ClassLoader.getSystemClassLoader();
501 ClassLoader parent;
502 while ((parent = ld.getParent()) != null) {
503 ld = parent;
504 }
505 loader = ld;
506 }
507
508 private RBClassLoader() {
509 }
510 public Class<?> loadClass(String name) throws ClassNotFoundException {
511 if (loader != null) {
512 return loader.loadClass(name);
513 }
514 return Class.forName(name);
515 }
516 public URL getResource(String name) {
517 if (loader != null) {
518 return loader.getResource(name);
519 }
520 return ClassLoader.getSystemResource(name);
521 }
522 public InputStream getResourceAsStream(String name) {
523 if (loader != null) {
524 return loader.getResourceAsStream(name);
525 }
526 return ClassLoader.getSystemResourceAsStream(name);
527 }
528 }
529
530 /**
531 * Sets the parent bundle of this bundle.
532 * The parent bundle is searched by {@link #getObject getObject}
533 * when this bundle does not contain a particular resource.
534 *
535 * @param parent this bundle's parent bundle.
536 */
537 protected void setParent(ResourceBundle parent) {
538 assert parent != NONEXISTENT_BUNDLE;
539 this.parent = parent;
540 }
541
542 /**
543 * Key used for cached resource bundles. The key checks the base
544 * name, the locale, and the class loader to determine if the
545 * resource is a match to the requested one. The loader may be
546 * null, but the base name and the locale must have a non-null
547 * value.
548 */
549 private static class CacheKey implements Cloneable {
550 // These three are the actual keys for lookup in Map.
551 private String name;
552 private Locale locale;
553 private LoaderReference loaderRef;
554
555 // bundle format which is necessary for calling
556 // Control.needsReload().
557 private String format;
558
559 // These time values are in CacheKey so that NONEXISTENT_BUNDLE
560 // doesn't need to be cloned for caching.
561
562 // The time when the bundle has been loaded
563 private volatile long loadTime;
564
565 // The time when the bundle expires in the cache, or either
566 // Control.TTL_DONT_CACHE or Control.TTL_NO_EXPIRATION_CONTROL.
567 private volatile long expirationTime;
568
569 // Placeholder for an error report by a Throwable
570 private Throwable cause;
571
572 // Hash code value cache to avoid recalculating the hash code
573 // of this instance.
574 private int hashCodeCache;
575
576 CacheKey(String baseName, Locale locale, ClassLoader loader) {
577 this.name = baseName;
578 this.locale = locale;
579 if (loader == null) {
580 this.loaderRef = null;
581 } else {
582 loaderRef = new LoaderReference(loader, referenceQueue, this);
583 }
584 calculateHashCode();
585 }
586
587 String getName() {
588 return name;
589 }
590
591 CacheKey setName(String baseName) {
592 if (!this.name.equals(baseName)) {
593 this.name = baseName;
594 calculateHashCode();
595 }
596 return this;
597 }
598
599 Locale getLocale() {
600 return locale;
601 }
602
603 CacheKey setLocale(Locale locale) {
604 if (!this.locale.equals(locale)) {
605 this.locale = locale;
606 calculateHashCode();
607 }
608 return this;
609 }
610
611 ClassLoader getLoader() {
612 return (loaderRef != null) ? loaderRef.get() : null;
613 }
614
615 public boolean equals(Object other) {
616 if (this == other) {
617 return true;
618 }
619 try {
620 final CacheKey otherEntry = (CacheKey)other;
621 //quick check to see if they are not equal
622 if (hashCodeCache != otherEntry.hashCodeCache) {
623 return false;
624 }
625 //are the names the same?
626 if (!name.equals(otherEntry.name)) {
627 return false;
628 }
629 // are the locales the same?
630 if (!locale.equals(otherEntry.locale)) {
631 return false;
632 }
633 //are refs (both non-null) or (both null)?
634 if (loaderRef == null) {
635 return otherEntry.loaderRef == null;
636 }
637 ClassLoader loader = loaderRef.get();
638 return (otherEntry.loaderRef != null)
639 // with a null reference we can no longer find
640 // out which class loader was referenced; so
641 // treat it as unequal
642 && (loader != null)
643 && (loader == otherEntry.loaderRef.get());
644 } catch ( NullPointerException | ClassCastException e) {
645 }
646 return false;
647 }
648
649 public int hashCode() {
650 return hashCodeCache;
651 }
652
653 private void calculateHashCode() {
654 hashCodeCache = name.hashCode() << 3;
655 hashCodeCache ^= locale.hashCode();
656 ClassLoader loader = getLoader();
657 if (loader != null) {
658 hashCodeCache ^= loader.hashCode();
659 }
660 }
661
662 public Object clone() {
663 try {
664 CacheKey clone = (CacheKey) super.clone();
665 if (loaderRef != null) {
666 clone.loaderRef = new LoaderReference(loaderRef.get(),
667 referenceQueue, clone);
668 }
669 // Clear the reference to a Throwable
670 clone.cause = null;
671 return clone;
672 } catch (CloneNotSupportedException e) {
673 //this should never happen
674 throw new InternalError(e);
675 }
676 }
677
678 String getFormat() {
679 return format;
680 }
681
682 void setFormat(String format) {
683 this.format = format;
684 }
685
686 private void setCause(Throwable cause) {
687 if (this.cause == null) {
688 this.cause = cause;
689 } else {
690 // Override the cause if the previous one is
691 // ClassNotFoundException.
692 if (this.cause instanceof ClassNotFoundException) {
693 this.cause = cause;
694 }
695 }
696 }
697
698 private Throwable getCause() {
699 return cause;
700 }
701
702 public String toString() {
703 String l = locale.toString();
704 if (l.length() == 0) {
705 if (locale.getVariant().length() != 0) {
706 l = "__" + locale.getVariant();
707 } else {
708 l = "\"\"";
709 }
710 }
711 return "CacheKey[" + name + ", lc=" + l + ", ldr=" + getLoader()
712 + "(format=" + format + ")]";
713 }
714 }
715
716 /**
717 * The common interface to get a CacheKey in LoaderReference and
718 * BundleReference.
719 */
720 private static interface CacheKeyReference {
721 public CacheKey getCacheKey();
722 }
723
724 /**
725 * References to class loaders are weak references, so that they can be
726 * garbage collected when nobody else is using them. The ResourceBundle
727 * class has no reason to keep class loaders alive.
728 */
729 private static class LoaderReference extends WeakReference<ClassLoader>
730 implements CacheKeyReference {
731 private CacheKey cacheKey;
732
733 LoaderReference(ClassLoader referent, ReferenceQueue<Object> q, CacheKey key) {
734 super(referent, q);
735 cacheKey = key;
736 }
737
738 public CacheKey getCacheKey() {
739 return cacheKey;
740 }
741 }
742
743 /**
744 * References to bundles are soft references so that they can be garbage
745 * collected when they have no hard references.
746 */
747 private static class BundleReference extends SoftReference<ResourceBundle>
748 implements CacheKeyReference {
749 private CacheKey cacheKey;
750
751 BundleReference(ResourceBundle referent, ReferenceQueue<Object> q, CacheKey key) {
752 super(referent, q);
753 cacheKey = key;
754 }
755
756 public CacheKey getCacheKey() {
757 return cacheKey;
758 }
759 }
760
761 /**
762 * Gets a resource bundle using the specified base name, the default locale,
763 * and the caller's class loader. Calling this method is equivalent to calling
764 * <blockquote>
765 * <code>getBundle(baseName, Locale.getDefault(), this.getClass().getClassLoader())</code>,
766 * </blockquote>
767 * except that <code>getClassLoader()</code> is run with the security
768 * privileges of <code>ResourceBundle</code>.
769 * See {@link #getBundle(String, Locale, ClassLoader) getBundle}
770 * for a complete description of the search and instantiation strategy.
771 *
772 * @param baseName the base name of the resource bundle, a fully qualified class name
773 * @exception java.lang.NullPointerException
774 * if <code>baseName</code> is <code>null</code>
775 * @exception MissingResourceException
776 * if no resource bundle for the specified base name can be found
777 * @return a resource bundle for the given base name and the default locale
778 */
779 @CallerSensitive
780 public static final ResourceBundle getBundle(String baseName)
781 {
782 return getBundleImpl(baseName, Locale.getDefault(),
783 getLoader(Reflection.getCallerClass()),
784 getDefaultControl(baseName));
785 }
786
787 /**
788 * Returns a resource bundle using the specified base name, the
789 * default locale and the specified control. Calling this method
790 * is equivalent to calling
791 * <pre>
792 * getBundle(baseName, Locale.getDefault(),
793 * this.getClass().getClassLoader(), control),
794 * </pre>
795 * except that <code>getClassLoader()</code> is run with the security
796 * privileges of <code>ResourceBundle</code>. See {@link
797 * #getBundle(String, Locale, ClassLoader, Control) getBundle} for the
798 * complete description of the resource bundle loading process with a
799 * <code>ResourceBundle.Control</code>.
800 *
801 * @param baseName
802 * the base name of the resource bundle, a fully qualified class
803 * name
804 * @param control
805 * the control which gives information for the resource bundle
806 * loading process
807 * @return a resource bundle for the given base name and the default
808 * locale
809 * @exception NullPointerException
810 * if <code>baseName</code> or <code>control</code> is
811 * <code>null</code>
812 * @exception MissingResourceException
813 * if no resource bundle for the specified base name can be found
814 * @exception IllegalArgumentException
815 * if the given <code>control</code> doesn't perform properly
816 * (e.g., <code>control.getCandidateLocales</code> returns null.)
817 * Note that validation of <code>control</code> is performed as
818 * needed.
819 * @since 1.6
820 */
821 @CallerSensitive
822 public static final ResourceBundle getBundle(String baseName,
823 Control control) {
824 return getBundleImpl(baseName, Locale.getDefault(),
825 getLoader(Reflection.getCallerClass()),
826 control);
827 }
828
829 /**
830 * Gets a resource bundle using the specified base name and locale,
831 * and the caller's class loader. Calling this method is equivalent to calling
832 * <blockquote>
833 * <code>getBundle(baseName, locale, this.getClass().getClassLoader())</code>,
834 * </blockquote>
835 * except that <code>getClassLoader()</code> is run with the security
836 * privileges of <code>ResourceBundle</code>.
837 * See {@link #getBundle(String, Locale, ClassLoader) getBundle}
838 * for a complete description of the search and instantiation strategy.
839 *
840 * @param baseName
841 * the base name of the resource bundle, a fully qualified class name
842 * @param locale
843 * the locale for which a resource bundle is desired
844 * @exception NullPointerException
845 * if <code>baseName</code> or <code>locale</code> is <code>null</code>
846 * @exception MissingResourceException
847 * if no resource bundle for the specified base name can be found
848 * @return a resource bundle for the given base name and locale
849 */
850 @CallerSensitive
851 public static final ResourceBundle getBundle(String baseName,
852 Locale locale)
853 {
854 return getBundleImpl(baseName, locale,
855 getLoader(Reflection.getCallerClass()),
856 getDefaultControl(baseName));
857 }
858
859 /**
860 * Returns a resource bundle using the specified base name, target
861 * locale and control, and the caller's class loader. Calling this
862 * method is equivalent to calling
863 * <pre>
864 * getBundle(baseName, targetLocale, this.getClass().getClassLoader(),
865 * control),
866 * </pre>
867 * except that <code>getClassLoader()</code> is run with the security
868 * privileges of <code>ResourceBundle</code>. See {@link
869 * #getBundle(String, Locale, ClassLoader, Control) getBundle} for the
870 * complete description of the resource bundle loading process with a
871 * <code>ResourceBundle.Control</code>.
872 *
873 * @param baseName
874 * the base name of the resource bundle, a fully qualified
875 * class name
876 * @param targetLocale
877 * the locale for which a resource bundle is desired
878 * @param control
879 * the control which gives information for the resource
880 * bundle loading process
881 * @return a resource bundle for the given base name and a
882 * <code>Locale</code> in <code>locales</code>
883 * @exception NullPointerException
884 * if <code>baseName</code>, <code>locales</code> or
885 * <code>control</code> is <code>null</code>
886 * @exception MissingResourceException
887 * if no resource bundle for the specified base name in any
888 * of the <code>locales</code> can be found.
889 * @exception IllegalArgumentException
890 * if the given <code>control</code> doesn't perform properly
891 * (e.g., <code>control.getCandidateLocales</code> returns null.)
892 * Note that validation of <code>control</code> is performed as
893 * needed.
894 * @since 1.6
895 */
896 @CallerSensitive
897 public static final ResourceBundle getBundle(String baseName, Locale targetLocale,
898 Control control) {
899 return getBundleImpl(baseName, targetLocale,
900 getLoader(Reflection.getCallerClass()),
901 control);
902 }
903
904 /**
905 * Gets a resource bundle using the specified base name, locale, and class
906 * loader.
907 *
908 * <p>This method behaves the same as calling
909 * {@link #getBundle(String, Locale, ClassLoader, Control)} passing a
910 * default instance of {@link Control} unless another {@link Control} is
911 * provided with the {@link ResourceBundleControlProvider} SPI. Refer to the
912 * description of <a href="#modify_default_behavior">modifying the default
913 * behavior</a>.
914 *
915 * <p><a name="default_behavior">The following describes the default
916 * behavior</a>.
917 *
918 * <p><code>getBundle</code> uses the base name, the specified locale, and
919 * the default locale (obtained from {@link java.util.Locale#getDefault()
920 * Locale.getDefault}) to generate a sequence of <a
921 * name="candidates"><em>candidate bundle names</em></a>. If the specified
922 * locale's language, script, country, and variant are all empty strings,
923 * then the base name is the only candidate bundle name. Otherwise, a list
924 * of candidate locales is generated from the attribute values of the
925 * specified locale (language, script, country and variant) and appended to
926 * the base name. Typically, this will look like the following:
927 *
928 * <pre>
929 * baseName + "_" + language + "_" + script + "_" + country + "_" + variant
930 * baseName + "_" + language + "_" + script + "_" + country
931 * baseName + "_" + language + "_" + script
932 * baseName + "_" + language + "_" + country + "_" + variant
933 * baseName + "_" + language + "_" + country
934 * baseName + "_" + language
935 * </pre>
936 *
937 * <p>Candidate bundle names where the final component is an empty string
938 * are omitted, along with the underscore. For example, if country is an
939 * empty string, the second and the fifth candidate bundle names above
940 * would be omitted. Also, if script is an empty string, the candidate names
941 * including script are omitted. For example, a locale with language "de"
942 * and variant "JAVA" will produce candidate names with base name
943 * "MyResource" below.
944 *
945 * <pre>
946 * MyResource_de__JAVA
947 * MyResource_de
948 * </pre>
949 *
950 * In the case that the variant contains one or more underscores ('_'), a
951 * sequence of bundle names generated by truncating the last underscore and
952 * the part following it is inserted after a candidate bundle name with the
953 * original variant. For example, for a locale with language "en", script
954 * "Latn, country "US" and variant "WINDOWS_VISTA", and bundle base name
955 * "MyResource", the list of candidate bundle names below is generated:
956 *
957 * <pre>
958 * MyResource_en_Latn_US_WINDOWS_VISTA
959 * MyResource_en_Latn_US_WINDOWS
960 * MyResource_en_Latn_US
961 * MyResource_en_Latn
962 * MyResource_en_US_WINDOWS_VISTA
963 * MyResource_en_US_WINDOWS
964 * MyResource_en_US
965 * MyResource_en
966 * </pre>
967 *
968 * <blockquote><b>Note:</b> For some <code>Locale</code>s, the list of
969 * candidate bundle names contains extra names, or the order of bundle names
970 * is slightly modified. See the description of the default implementation
971 * of {@link Control#getCandidateLocales(String, Locale)
972 * getCandidateLocales} for details.</blockquote>
973 *
974 * <p><code>getBundle</code> then iterates over the candidate bundle names
975 * to find the first one for which it can <em>instantiate</em> an actual
976 * resource bundle. It uses the default controls' {@link Control#getFormats
977 * getFormats} method, which generates two bundle names for each generated
978 * name, the first a class name and the second a properties file name. For
979 * each candidate bundle name, it attempts to create a resource bundle:
980 *
981 * <ul><li>First, it attempts to load a class using the generated class name.
982 * If such a class can be found and loaded using the specified class
983 * loader, is assignment compatible with ResourceBundle, is accessible from
984 * ResourceBundle, and can be instantiated, <code>getBundle</code> creates a
985 * new instance of this class and uses it as the <em>result resource
986 * bundle</em>.
987 *
988 * <li>Otherwise, <code>getBundle</code> attempts to locate a property
989 * resource file using the generated properties file name. It generates a
990 * path name from the candidate bundle name by replacing all "." characters
991 * with "/" and appending the string ".properties". It attempts to find a
992 * "resource" with this name using {@link
993 * java.lang.ClassLoader#getResource(java.lang.String)
994 * ClassLoader.getResource}. (Note that a "resource" in the sense of
995 * <code>getResource</code> has nothing to do with the contents of a
996 * resource bundle, it is just a container of data, such as a file.) If it
997 * finds a "resource", it attempts to create a new {@link
998 * PropertyResourceBundle} instance from its contents. If successful, this
999 * instance becomes the <em>result resource bundle</em>. </ul>
1000 *
1001 * <p>This continues until a result resource bundle is instantiated or the
1002 * list of candidate bundle names is exhausted. If no matching resource
1003 * bundle is found, the default control's {@link Control#getFallbackLocale
1004 * getFallbackLocale} method is called, which returns the current default
1005 * locale. A new sequence of candidate locale names is generated using this
1006 * locale and and searched again, as above.
1007 *
1008 * <p>If still no result bundle is found, the base name alone is looked up. If
1009 * this still fails, a <code>MissingResourceException</code> is thrown.
1010 *
1011 * <p><a name="parent_chain"> Once a result resource bundle has been found,
1012 * its <em>parent chain</em> is instantiated</a>. If the result bundle already
1013 * has a parent (perhaps because it was returned from a cache) the chain is
1014 * complete.
1015 *
1016 * <p>Otherwise, <code>getBundle</code> examines the remainder of the
1017 * candidate locale list that was used during the pass that generated the
1018 * result resource bundle. (As before, candidate bundle names where the
1019 * final component is an empty string are omitted.) When it comes to the
1020 * end of the candidate list, it tries the plain bundle name. With each of the
1021 * candidate bundle names it attempts to instantiate a resource bundle (first
1022 * looking for a class and then a properties file, as described above).
1023 *
1024 * <p>Whenever it succeeds, it calls the previously instantiated resource
1025 * bundle's {@link #setParent(java.util.ResourceBundle) setParent} method
1026 * with the new resource bundle. This continues until the list of names
1027 * is exhausted or the current bundle already has a non-null parent.
1028 *
1029 * <p>Once the parent chain is complete, the bundle is returned.
1030 *
1031 * <p><b>Note:</b> <code>getBundle</code> caches instantiated resource
1032 * bundles and might return the same resource bundle instance multiple times.
1033 *
1034 * <p><b>Note:</b>The <code>baseName</code> argument should be a fully
1035 * qualified class name. However, for compatibility with earlier versions,
1036 * Sun's Java SE Runtime Environments do not verify this, and so it is
1037 * possible to access <code>PropertyResourceBundle</code>s by specifying a
1038 * path name (using "/") instead of a fully qualified class name (using
1039 * ".").
1040 *
1041 * <p><a name="default_behavior_example">
1042 * <strong>Example:</strong></a>
1043 * <p>
1044 * The following class and property files are provided:
1045 * <pre>
1046 * MyResources.class
1047 * MyResources.properties
1048 * MyResources_fr.properties
1049 * MyResources_fr_CH.class
1050 * MyResources_fr_CH.properties
1051 * MyResources_en.properties
1052 * MyResources_es_ES.class
1053 * </pre>
1054 *
1055 * The contents of all files are valid (that is, public non-abstract
1056 * subclasses of <code>ResourceBundle</code> for the ".class" files,
1057 * syntactically correct ".properties" files). The default locale is
1058 * <code>Locale("en", "GB")</code>.
1059 *
1060 * <p>Calling <code>getBundle</code> with the locale arguments below will
1061 * instantiate resource bundles as follows:
1062 *
1063 * <table summary="getBundle() locale to resource bundle mapping">
1064 * <tr><td>Locale("fr", "CH")</td><td>MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class</td></tr>
1065 * <tr><td>Locale("fr", "FR")</td><td>MyResources_fr.properties, parent MyResources.class</td></tr>
1066 * <tr><td>Locale("de", "DE")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
1067 * <tr><td>Locale("en", "US")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
1068 * <tr><td>Locale("es", "ES")</td><td>MyResources_es_ES.class, parent MyResources.class</td></tr>
1069 * </table>
1070 *
1071 * <p>The file MyResources_fr_CH.properties is never used because it is
1072 * hidden by the MyResources_fr_CH.class. Likewise, MyResources.properties
1073 * is also hidden by MyResources.class.
1074 *
1075 * @param baseName the base name of the resource bundle, a fully qualified class name
1076 * @param locale the locale for which a resource bundle is desired
1077 * @param loader the class loader from which to load the resource bundle
1078 * @return a resource bundle for the given base name and locale
1079 * @exception java.lang.NullPointerException
1080 * if <code>baseName</code>, <code>locale</code>, or <code>loader</code> is <code>null</code>
1081 * @exception MissingResourceException
1082 * if no resource bundle for the specified base name can be found
1083 * @since 1.2
1084 */
1085 public static ResourceBundle getBundle(String baseName, Locale locale,
1086 ClassLoader loader)
1087 {
1088 if (loader == null) {
1089 throw new NullPointerException();
1090 }
1091 return getBundleImpl(baseName, locale, loader, getDefaultControl(baseName));
1092 }
1093
1094 /**
1095 * Returns a resource bundle using the specified base name, target
1096 * locale, class loader and control. Unlike the {@linkplain
1097 * #getBundle(String, Locale, ClassLoader) <code>getBundle</code>
1098 * factory methods with no <code>control</code> argument}, the given
1099 * <code>control</code> specifies how to locate and instantiate resource
1100 * bundles. Conceptually, the bundle loading process with the given
1101 * <code>control</code> is performed in the following steps.
1102 *
1103 * <ol>
1104 * <li>This factory method looks up the resource bundle in the cache for
1105 * the specified <code>baseName</code>, <code>targetLocale</code> and
1106 * <code>loader</code>. If the requested resource bundle instance is
1107 * found in the cache and the time-to-live periods of the instance and
1108 * all of its parent instances have not expired, the instance is returned
1109 * to the caller. Otherwise, this factory method proceeds with the
1110 * loading process below.</li>
1111 *
1112 * <li>The {@link ResourceBundle.Control#getFormats(String)
1113 * control.getFormats} method is called to get resource bundle formats
1114 * to produce bundle or resource names. The strings
1115 * <code>"java.class"</code> and <code>"java.properties"</code>
1116 * designate class-based and {@linkplain PropertyResourceBundle
1117 * property}-based resource bundles, respectively. Other strings
1118 * starting with <code>"java."</code> are reserved for future extensions
1119 * and must not be used for application-defined formats. Other strings
1120 * designate application-defined formats.</li>
1121 *
1122 * <li>The {@link ResourceBundle.Control#getCandidateLocales(String,
1123 * Locale) control.getCandidateLocales} method is called with the target
1124 * locale to get a list of <em>candidate <code>Locale</code>s</em> for
1125 * which resource bundles are searched.</li>
1126 *
1127 * <li>The {@link ResourceBundle.Control#newBundle(String, Locale,
1128 * String, ClassLoader, boolean) control.newBundle} method is called to
1129 * instantiate a <code>ResourceBundle</code> for the base bundle name, a
1130 * candidate locale, and a format. (Refer to the note on the cache
1131 * lookup below.) This step is iterated over all combinations of the
1132 * candidate locales and formats until the <code>newBundle</code> method
1133 * returns a <code>ResourceBundle</code> instance or the iteration has
1134 * used up all the combinations. For example, if the candidate locales
1135 * are <code>Locale("de", "DE")</code>, <code>Locale("de")</code> and
1136 * <code>Locale("")</code> and the formats are <code>"java.class"</code>
1137 * and <code>"java.properties"</code>, then the following is the
1138 * sequence of locale-format combinations to be used to call
1139 * <code>control.newBundle</code>.
1140 *
1141 * <table style="width: 50%; text-align: left; margin-left: 40px;"
1142 * border="0" cellpadding="2" cellspacing="2" summary="locale-format combinations for newBundle">
1143 * <tbody>
1144 * <tr>
1145 * <td
1146 * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;"><code>Locale</code><br>
1147 * </td>
1148 * <td
1149 * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;"><code>format</code><br>
1150 * </td>
1151 * </tr>
1152 * <tr>
1153 * <td style="vertical-align: top; width: 50%;"><code>Locale("de", "DE")</code><br>
1154 * </td>
1155 * <td style="vertical-align: top; width: 50%;"><code>java.class</code><br>
1156 * </td>
1157 * </tr>
1158 * <tr>
1159 * <td style="vertical-align: top; width: 50%;"><code>Locale("de", "DE")</code></td>
1160 * <td style="vertical-align: top; width: 50%;"><code>java.properties</code><br>
1161 * </td>
1162 * </tr>
1163 * <tr>
1164 * <td style="vertical-align: top; width: 50%;"><code>Locale("de")</code></td>
1165 * <td style="vertical-align: top; width: 50%;"><code>java.class</code></td>
1166 * </tr>
1167 * <tr>
1168 * <td style="vertical-align: top; width: 50%;"><code>Locale("de")</code></td>
1169 * <td style="vertical-align: top; width: 50%;"><code>java.properties</code></td>
1170 * </tr>
1171 * <tr>
1172 * <td style="vertical-align: top; width: 50%;"><code>Locale("")</code><br>
1173 * </td>
1174 * <td style="vertical-align: top; width: 50%;"><code>java.class</code></td>
1175 * </tr>
1176 * <tr>
1177 * <td style="vertical-align: top; width: 50%;"><code>Locale("")</code></td>
1178 * <td style="vertical-align: top; width: 50%;"><code>java.properties</code></td>
1179 * </tr>
1180 * </tbody>
1181 * </table>
1182 * </li>
1183 *
1184 * <li>If the previous step has found no resource bundle, proceed to
1185 * Step 6. If a bundle has been found that is a base bundle (a bundle
1186 * for <code>Locale("")</code>), and the candidate locale list only contained
1187 * <code>Locale("")</code>, return the bundle to the caller. If a bundle
1188 * has been found that is a base bundle, but the candidate locale list
1189 * contained locales other than Locale(""), put the bundle on hold and
1190 * proceed to Step 6. If a bundle has been found that is not a base
1191 * bundle, proceed to Step 7.</li>
1192 *
1193 * <li>The {@link ResourceBundle.Control#getFallbackLocale(String,
1194 * Locale) control.getFallbackLocale} method is called to get a fallback
1195 * locale (alternative to the current target locale) to try further
1196 * finding a resource bundle. If the method returns a non-null locale,
1197 * it becomes the next target locale and the loading process starts over
1198 * from Step 3. Otherwise, if a base bundle was found and put on hold in
1199 * a previous Step 5, it is returned to the caller now. Otherwise, a
1200 * MissingResourceException is thrown.</li>
1201 *
1202 * <li>At this point, we have found a resource bundle that's not the
1203 * base bundle. If this bundle set its parent during its instantiation,
1204 * it is returned to the caller. Otherwise, its <a
1205 * href="./ResourceBundle.html#parent_chain">parent chain</a> is
1206 * instantiated based on the list of candidate locales from which it was
1207 * found. Finally, the bundle is returned to the caller.</li>
1208 * </ol>
1209 *
1210 * <p>During the resource bundle loading process above, this factory
1211 * method looks up the cache before calling the {@link
1212 * Control#newBundle(String, Locale, String, ClassLoader, boolean)
1213 * control.newBundle} method. If the time-to-live period of the
1214 * resource bundle found in the cache has expired, the factory method
1215 * calls the {@link ResourceBundle.Control#needsReload(String, Locale,
1216 * String, ClassLoader, ResourceBundle, long) control.needsReload}
1217 * method to determine whether the resource bundle needs to be reloaded.
1218 * If reloading is required, the factory method calls
1219 * <code>control.newBundle</code> to reload the resource bundle. If
1220 * <code>control.newBundle</code> returns <code>null</code>, the factory
1221 * method puts a dummy resource bundle in the cache as a mark of
1222 * nonexistent resource bundles in order to avoid lookup overhead for
1223 * subsequent requests. Such dummy resource bundles are under the same
1224 * expiration control as specified by <code>control</code>.
1225 *
1226 * <p>All resource bundles loaded are cached by default. Refer to
1227 * {@link Control#getTimeToLive(String,Locale)
1228 * control.getTimeToLive} for details.
1229 *
1230 * <p>The following is an example of the bundle loading process with the
1231 * default <code>ResourceBundle.Control</code> implementation.
1232 *
1233 * <p>Conditions:
1234 * <ul>
1235 * <li>Base bundle name: <code>foo.bar.Messages</code>
1236 * <li>Requested <code>Locale</code>: {@link Locale#ITALY}</li>
1237 * <li>Default <code>Locale</code>: {@link Locale#FRENCH}</li>
1238 * <li>Available resource bundles:
1239 * <code>foo/bar/Messages_fr.properties</code> and
1240 * <code>foo/bar/Messages.properties</code></li>
1241 * </ul>
1242 *
1243 * <p>First, <code>getBundle</code> tries loading a resource bundle in
1244 * the following sequence.
1245 *
1246 * <ul>
1247 * <li>class <code>foo.bar.Messages_it_IT</code>
1248 * <li>file <code>foo/bar/Messages_it_IT.properties</code>
1249 * <li>class <code>foo.bar.Messages_it</code></li>
1250 * <li>file <code>foo/bar/Messages_it.properties</code></li>
1251 * <li>class <code>foo.bar.Messages</code></li>
1252 * <li>file <code>foo/bar/Messages.properties</code></li>
1253 * </ul>
1254 *
1255 * <p>At this point, <code>getBundle</code> finds
1256 * <code>foo/bar/Messages.properties</code>, which is put on hold
1257 * because it's the base bundle. <code>getBundle</code> calls {@link
1258 * Control#getFallbackLocale(String, Locale)
1259 * control.getFallbackLocale("foo.bar.Messages", Locale.ITALY)} which
1260 * returns <code>Locale.FRENCH</code>. Next, <code>getBundle</code>
1261 * tries loading a bundle in the following sequence.
1262 *
1263 * <ul>
1264 * <li>class <code>foo.bar.Messages_fr</code></li>
1265 * <li>file <code>foo/bar/Messages_fr.properties</code></li>
1266 * <li>class <code>foo.bar.Messages</code></li>
1267 * <li>file <code>foo/bar/Messages.properties</code></li>
1268 * </ul>
1269 *
1270 * <p><code>getBundle</code> finds
1271 * <code>foo/bar/Messages_fr.properties</code> and creates a
1272 * <code>ResourceBundle</code> instance. Then, <code>getBundle</code>
1273 * sets up its parent chain from the list of the candidate locales. Only
1274 * <code>foo/bar/Messages.properties</code> is found in the list and
1275 * <code>getBundle</code> creates a <code>ResourceBundle</code> instance
1276 * that becomes the parent of the instance for
1277 * <code>foo/bar/Messages_fr.properties</code>.
1278 *
1279 * @param baseName
1280 * the base name of the resource bundle, a fully qualified
1281 * class name
1282 * @param targetLocale
1283 * the locale for which a resource bundle is desired
1284 * @param loader
1285 * the class loader from which to load the resource bundle
1286 * @param control
1287 * the control which gives information for the resource
1288 * bundle loading process
1289 * @return a resource bundle for the given base name and locale
1290 * @exception NullPointerException
1291 * if <code>baseName</code>, <code>targetLocale</code>,
1292 * <code>loader</code>, or <code>control</code> is
1293 * <code>null</code>
1294 * @exception MissingResourceException
1295 * if no resource bundle for the specified base name can be found
1296 * @exception IllegalArgumentException
1297 * if the given <code>control</code> doesn't perform properly
1298 * (e.g., <code>control.getCandidateLocales</code> returns null.)
1299 * Note that validation of <code>control</code> is performed as
1300 * needed.
1301 * @since 1.6
1302 */
1303 public static ResourceBundle getBundle(String baseName, Locale targetLocale,
1304 ClassLoader loader, Control control) {
1305 if (loader == null || control == null) {
1306 throw new NullPointerException();
1307 }
1308 return getBundleImpl(baseName, targetLocale, loader, control);
1309 }
1310
1311 private static Control getDefaultControl(String baseName) {
1312 if (providers != null) {
1313 for (ResourceBundleControlProvider provider : providers) {
1314 Control control = provider.getControl(baseName);
1315 if (control != null) {
1316 return control;
1317 }
1318 }
1319 }
1320 return Control.INSTANCE;
1321 }
1322
1323 private static ResourceBundle getBundleImpl(String baseName, Locale locale,
1324 ClassLoader loader, Control control) {
1325 if (locale == null || control == null) {
1326 throw new NullPointerException();
1327 }
1328
1329 // We create a CacheKey here for use by this call. The base
1330 // name and loader will never change during the bundle loading
1331 // process. We have to make sure that the locale is set before
1332 // using it as a cache key.
1333 CacheKey cacheKey = new CacheKey(baseName, locale, loader);
1334 ResourceBundle bundle = null;
1335
1336 // Quick lookup of the cache.
1337 BundleReference bundleRef = cacheList.get(cacheKey);
1338 if (bundleRef != null) {
1339 bundle = bundleRef.get();
1340 bundleRef = null;
1341 }
1342
1343 // If this bundle and all of its parents are valid (not expired),
1344 // then return this bundle. If any of the bundles is expired, we
1345 // don't call control.needsReload here but instead drop into the
1346 // complete loading process below.
1347 if (isValidBundle(bundle) && hasValidParentChain(bundle)) {
1348 return bundle;
1349 }
1350
1351 // No valid bundle was found in the cache, so we need to load the
1352 // resource bundle and its parents.
1353
1354 boolean isKnownControl = (control == Control.INSTANCE) ||
1355 (control instanceof SingleFormatControl);
1356 List<String> formats = control.getFormats(baseName);
1357 if (!isKnownControl && !checkList(formats)) {
1358 throw new IllegalArgumentException("Invalid Control: getFormats");
1359 }
1360
1361 ResourceBundle baseBundle = null;
1362 for (Locale targetLocale = locale;
1363 targetLocale != null;
1364 targetLocale = control.getFallbackLocale(baseName, targetLocale)) {
1365 List<Locale> candidateLocales = control.getCandidateLocales(baseName, targetLocale);
1366 if (!isKnownControl && !checkList(candidateLocales)) {
1367 throw new IllegalArgumentException("Invalid Control: getCandidateLocales");
1368 }
1369
1370 bundle = findBundle(cacheKey, candidateLocales, formats, 0, control, baseBundle);
1371
1372 // If the loaded bundle is the base bundle and exactly for the
1373 // requested locale or the only candidate locale, then take the
1374 // bundle as the resulting one. If the loaded bundle is the base
1375 // bundle, it's put on hold until we finish processing all
1376 // fallback locales.
1377 if (isValidBundle(bundle)) {
1378 boolean isBaseBundle = Locale.ROOT.equals(bundle.locale);
1379 if (!isBaseBundle || bundle.locale.equals(locale)
1380 || (candidateLocales.size() == 1
1381 && bundle.locale.equals(candidateLocales.get(0)))) {
1382 break;
1383 }
1384
1385 // If the base bundle has been loaded, keep the reference in
1386 // baseBundle so that we can avoid any redundant loading in case
1387 // the control specify not to cache bundles.
1388 if (isBaseBundle && baseBundle == null) {
1389 baseBundle = bundle;
1390 }
1391 }
1392 }
1393
1394 if (bundle == null) {
1395 if (baseBundle == null) {
1396 throwMissingResourceException(baseName, locale, cacheKey.getCause());
1397 }
1398 bundle = baseBundle;
1399 }
1400
1401 return bundle;
1402 }
1403
1404 /**
1405 * Checks if the given <code>List</code> is not null, not empty,
1406 * not having null in its elements.
1407 */
1408 private static boolean checkList(List<?> a) {
1409 boolean valid = (a != null && !a.isEmpty());
1410 if (valid) {
1411 int size = a.size();
1412 for (int i = 0; valid && i < size; i++) {
1413 valid = (a.get(i) != null);
1414 }
1415 }
1416 return valid;
1417 }
1418
1419 private static ResourceBundle findBundle(CacheKey cacheKey,
1420 List<Locale> candidateLocales,
1421 List<String> formats,
1422 int index,
1423 Control control,
1424 ResourceBundle baseBundle) {
1425 Locale targetLocale = candidateLocales.get(index);
1426 ResourceBundle parent = null;
1427 if (index != candidateLocales.size() - 1) {
1428 parent = findBundle(cacheKey, candidateLocales, formats, index + 1,
1429 control, baseBundle);
1430 } else if (baseBundle != null && Locale.ROOT.equals(targetLocale)) {
1431 return baseBundle;
1432 }
1433
1434 // Before we do the real loading work, see whether we need to
1435 // do some housekeeping: If references to class loaders or
1436 // resource bundles have been nulled out, remove all related
1437 // information from the cache.
1438 Object ref;
1439 while ((ref = referenceQueue.poll()) != null) {
1440 cacheList.remove(((CacheKeyReference)ref).getCacheKey());
1441 }
1442
1443 // flag indicating the resource bundle has expired in the cache
1444 boolean expiredBundle = false;
1445
1446 // First, look up the cache to see if it's in the cache, without
1447 // attempting to load bundle.
1448 cacheKey.setLocale(targetLocale);
1449 ResourceBundle bundle = findBundleInCache(cacheKey, control);
1450 if (isValidBundle(bundle)) {
1451 expiredBundle = bundle.expired;
1452 if (!expiredBundle) {
1453 // If its parent is the one asked for by the candidate
1454 // locales (the runtime lookup path), we can take the cached
1455 // one. (If it's not identical, then we'd have to check the
1456 // parent's parents to be consistent with what's been
1457 // requested.)
1458 if (bundle.parent == parent) {
1459 return bundle;
1460 }
1461 // Otherwise, remove the cached one since we can't keep
1462 // the same bundles having different parents.
1463 BundleReference bundleRef = cacheList.get(cacheKey);
1464 if (bundleRef != null && bundleRef.get() == bundle) {
1465 cacheList.remove(cacheKey, bundleRef);
1466 }
1467 }
1468 }
1469
1470 if (bundle != NONEXISTENT_BUNDLE) {
1471 CacheKey constKey = (CacheKey) cacheKey.clone();
1472
1473 try {
1474 bundle = loadBundle(cacheKey, formats, control, expiredBundle);
1475 if (bundle != null) {
1476 if (bundle.parent == null) {
1477 bundle.setParent(parent);
1478 }
1479 bundle.locale = targetLocale;
1480 bundle = putBundleInCache(cacheKey, bundle, control);
1481 return bundle;
1482 }
1483
1484 // Put NONEXISTENT_BUNDLE in the cache as a mark that there's no bundle
1485 // instance for the locale.
1486 putBundleInCache(cacheKey, NONEXISTENT_BUNDLE, control);
1487 } finally {
1488 if (constKey.getCause() instanceof InterruptedException) {
1489 Thread.currentThread().interrupt();
1490 }
1491 }
1492 }
1493 return parent;
1494 }
1495
1496 private static ResourceBundle loadBundle(CacheKey cacheKey,
1497 List<String> formats,
1498 Control control,
1499 boolean reload) {
1500
1501 // Here we actually load the bundle in the order of formats
1502 // specified by the getFormats() value.
1503 Locale targetLocale = cacheKey.getLocale();
1504
1505 ResourceBundle bundle = null;
1506 int size = formats.size();
1507 for (int i = 0; i < size; i++) {
1508 String format = formats.get(i);
1509 try {
1510 bundle = control.newBundle(cacheKey.getName(), targetLocale, format,
1511 cacheKey.getLoader(), reload);
1512 } catch (LinkageError error) {
1513 // We need to handle the LinkageError case due to
1514 // inconsistent case-sensitivity in ClassLoader.
1515 // See 6572242 for details.
1516 cacheKey.setCause(error);
1517 } catch (Exception cause) {
1518 cacheKey.setCause(cause);
1519 }
1520 if (bundle != null) {
1521 // Set the format in the cache key so that it can be
1522 // used when calling needsReload later.
1523 cacheKey.setFormat(format);
1524 bundle.name = cacheKey.getName();
1525 bundle.locale = targetLocale;
1526 // Bundle provider might reuse instances. So we should make
1527 // sure to clear the expired flag here.
1528 bundle.expired = false;
1529 break;
1530 }
1531 }
1532
1533 return bundle;
1534 }
1535
1536 private static boolean isValidBundle(ResourceBundle bundle) {
1537 return bundle != null && bundle != NONEXISTENT_BUNDLE;
1538 }
1539
1540 /**
1541 * Determines whether any of resource bundles in the parent chain,
1542 * including the leaf, have expired.
1543 */
1544 private static boolean hasValidParentChain(ResourceBundle bundle) {
1545 long now = System.currentTimeMillis();
1546 while (bundle != null) {
1547 if (bundle.expired) {
1548 return false;
1549 }
1550 CacheKey key = bundle.cacheKey;
1551 if (key != null) {
1552 long expirationTime = key.expirationTime;
1553 if (expirationTime >= 0 && expirationTime <= now) {
1554 return false;
1555 }
1556 }
1557 bundle = bundle.parent;
1558 }
1559 return true;
1560 }
1561
1562 /**
1563 * Throw a MissingResourceException with proper message
1564 */
1565 private static void throwMissingResourceException(String baseName,
1566 Locale locale,
1567 Throwable cause) {
1568 // If the cause is a MissingResourceException, avoid creating
1569 // a long chain. (6355009)
1570 if (cause instanceof MissingResourceException) {
1571 cause = null;
1572 }
1573 throw new MissingResourceException("Can't find bundle for base name "
1574 + baseName + ", locale " + locale,
1575 baseName + "_" + locale, // className
1576 "", // key
1577 cause);
1578 }
1579
1580 /**
1581 * Finds a bundle in the cache. Any expired bundles are marked as
1582 * `expired' and removed from the cache upon return.
1583 *
1584 * @param cacheKey the key to look up the cache
1585 * @param control the Control to be used for the expiration control
1586 * @return the cached bundle, or null if the bundle is not found in the
1587 * cache or its parent has expired. <code>bundle.expire</code> is true
1588 * upon return if the bundle in the cache has expired.
1589 */
1590 private static ResourceBundle findBundleInCache(CacheKey cacheKey,
1591 Control control) {
1592 BundleReference bundleRef = cacheList.get(cacheKey);
1593 if (bundleRef == null) {
1594 return null;
1595 }
1596 ResourceBundle bundle = bundleRef.get();
1597 if (bundle == null) {
1598 return null;
1599 }
1600 ResourceBundle p = bundle.parent;
1601 assert p != NONEXISTENT_BUNDLE;
1602 // If the parent has expired, then this one must also expire. We
1603 // check only the immediate parent because the actual loading is
1604 // done from the root (base) to leaf (child) and the purpose of
1605 // checking is to propagate expiration towards the leaf. For
1606 // example, if the requested locale is ja_JP_JP and there are
1607 // bundles for all of the candidates in the cache, we have a list,
1608 //
1609 // base <- ja <- ja_JP <- ja_JP_JP
1610 //
1611 // If ja has expired, then it will reload ja and the list becomes a
1612 // tree.
1613 //
1614 // base <- ja (new)
1615 // " <- ja (expired) <- ja_JP <- ja_JP_JP
1616 //
1617 // When looking up ja_JP in the cache, it finds ja_JP in the cache
1618 // which references to the expired ja. Then, ja_JP is marked as
1619 // expired and removed from the cache. This will be propagated to
1620 // ja_JP_JP.
1621 //
1622 // Now, it's possible, for example, that while loading new ja_JP,
1623 // someone else has started loading the same bundle and finds the
1624 // base bundle has expired. Then, what we get from the first
1625 // getBundle call includes the expired base bundle. However, if
1626 // someone else didn't start its loading, we wouldn't know if the
1627 // base bundle has expired at the end of the loading process. The
1628 // expiration control doesn't guarantee that the returned bundle and
1629 // its parents haven't expired.
1630 //
1631 // We could check the entire parent chain to see if there's any in
1632 // the chain that has expired. But this process may never end. An
1633 // extreme case would be that getTimeToLive returns 0 and
1634 // needsReload always returns true.
1635 if (p != null && p.expired) {
1636 assert bundle != NONEXISTENT_BUNDLE;
1637 bundle.expired = true;
1638 bundle.cacheKey = null;
1639 cacheList.remove(cacheKey, bundleRef);
1640 bundle = null;
1641 } else {
1642 CacheKey key = bundleRef.getCacheKey();
1643 long expirationTime = key.expirationTime;
1644 if (!bundle.expired && expirationTime >= 0 &&
1645 expirationTime <= System.currentTimeMillis()) {
1646 // its TTL period has expired.
1647 if (bundle != NONEXISTENT_BUNDLE) {
1648 // Synchronize here to call needsReload to avoid
1649 // redundant concurrent calls for the same bundle.
1650 synchronized (bundle) {
1651 expirationTime = key.expirationTime;
1652 if (!bundle.expired && expirationTime >= 0 &&
1653 expirationTime <= System.currentTimeMillis()) {
1654 try {
1655 bundle.expired = control.needsReload(key.getName(),
1656 key.getLocale(),
1657 key.getFormat(),
1658 key.getLoader(),
1659 bundle,
1660 key.loadTime);
1661 } catch (Exception e) {
1662 cacheKey.setCause(e);
1663 }
1664 if (bundle.expired) {
1665 // If the bundle needs to be reloaded, then
1666 // remove the bundle from the cache, but
1667 // return the bundle with the expired flag
1668 // on.
1669 bundle.cacheKey = null;
1670 cacheList.remove(cacheKey, bundleRef);
1671 } else {
1672 // Update the expiration control info. and reuse
1673 // the same bundle instance
1674 setExpirationTime(key, control);
1675 }
1676 }
1677 }
1678 } else {
1679 // We just remove NONEXISTENT_BUNDLE from the cache.
1680 cacheList.remove(cacheKey, bundleRef);
1681 bundle = null;
1682 }
1683 }
1684 }
1685 return bundle;
1686 }
1687
1688 /**
1689 * Put a new bundle in the cache.
1690 *
1691 * @param cacheKey the key for the resource bundle
1692 * @param bundle the resource bundle to be put in the cache
1693 * @return the ResourceBundle for the cacheKey; if someone has put
1694 * the bundle before this call, the one found in the cache is
1695 * returned.
1696 */
1697 private static ResourceBundle putBundleInCache(CacheKey cacheKey,
1698 ResourceBundle bundle,
1699 Control control) {
1700 setExpirationTime(cacheKey, control);
1701 if (cacheKey.expirationTime != Control.TTL_DONT_CACHE) {
1702 CacheKey key = (CacheKey) cacheKey.clone();
1703 BundleReference bundleRef = new BundleReference(bundle, referenceQueue, key);
1704 bundle.cacheKey = key;
1705
1706 // Put the bundle in the cache if it's not been in the cache.
1707 BundleReference result = cacheList.putIfAbsent(key, bundleRef);
1708
1709 // If someone else has put the same bundle in the cache before
1710 // us and it has not expired, we should use the one in the cache.
1711 if (result != null) {
1712 ResourceBundle rb = result.get();
1713 if (rb != null && !rb.expired) {
1714 // Clear the back link to the cache key
1715 bundle.cacheKey = null;
1716 bundle = rb;
1717 // Clear the reference in the BundleReference so that
1718 // it won't be enqueued.
1719 bundleRef.clear();
1720 } else {
1721 // Replace the invalid (garbage collected or expired)
1722 // instance with the valid one.
1723 cacheList.put(key, bundleRef);
1724 }
1725 }
1726 }
1727 return bundle;
1728 }
1729
1730 private static void setExpirationTime(CacheKey cacheKey, Control control) {
1731 long ttl = control.getTimeToLive(cacheKey.getName(),
1732 cacheKey.getLocale());
1733 if (ttl >= 0) {
1734 // If any expiration time is specified, set the time to be
1735 // expired in the cache.
1736 long now = System.currentTimeMillis();
1737 cacheKey.loadTime = now;
1738 cacheKey.expirationTime = now + ttl;
1739 } else if (ttl >= Control.TTL_NO_EXPIRATION_CONTROL) {
1740 cacheKey.expirationTime = ttl;
1741 } else {
1742 throw new IllegalArgumentException("Invalid Control: TTL=" + ttl);
1743 }
1744 }
1745
1746 /**
1747 * Removes all resource bundles from the cache that have been loaded
1748 * using the caller's class loader.
1749 *
1750 * @since 1.6
1751 * @see ResourceBundle.Control#getTimeToLive(String,Locale)
1752 */
1753 @CallerSensitive
1754 public static final void clearCache() {
1755 clearCache(getLoader(Reflection.getCallerClass()));
1756 }
1757
1758 /**
1759 * Removes all resource bundles from the cache that have been loaded
1760 * using the given class loader.
1761 *
1762 * @param loader the class loader
1763 * @exception NullPointerException if <code>loader</code> is null
1764 * @since 1.6
1765 * @see ResourceBundle.Control#getTimeToLive(String,Locale)
1766 */
1767 public static final void clearCache(ClassLoader loader) {
1768 if (loader == null) {
1769 throw new NullPointerException();
1770 }
1771 Set<CacheKey> set = cacheList.keySet();
1772 for (CacheKey key : set) {
1773 if (key.getLoader() == loader) {
1774 set.remove(key);
1775 }
1776 }
1777 }
1778
1779 /**
1780 * Gets an object for the given key from this resource bundle.
1781 * Returns null if this resource bundle does not contain an
1782 * object for the given key.
1783 *
1784 * @param key the key for the desired object
1785 * @exception NullPointerException if <code>key</code> is <code>null</code>
1786 * @return the object for the given key, or null
1787 */
1788 protected abstract Object handleGetObject(String key);
1789
1790 /**
1791 * Returns an enumeration of the keys.
1792 *
1793 * @return an <code>Enumeration</code> of the keys contained in
1794 * this <code>ResourceBundle</code> and its parent bundles.
1795 */
1796 public abstract Enumeration<String> getKeys();
1797
1798 /**
1799 * Determines whether the given <code>key</code> is contained in
1800 * this <code>ResourceBundle</code> or its parent bundles.
1801 *
1802 * @param key
1803 * the resource <code>key</code>
1804 * @return <code>true</code> if the given <code>key</code> is
1805 * contained in this <code>ResourceBundle</code> or its
1806 * parent bundles; <code>false</code> otherwise.
1807 * @exception NullPointerException
1808 * if <code>key</code> is <code>null</code>
1809 * @since 1.6
1810 */
1811 public boolean containsKey(String key) {
1812 if (key == null) {
1813 throw new NullPointerException();
1814 }
1815 for (ResourceBundle rb = this; rb != null; rb = rb.parent) {
1816 if (rb.handleKeySet().contains(key)) {
1817 return true;
1818 }
1819 }
1820 return false;
1821 }
1822
1823 /**
1824 * Returns a <code>Set</code> of all keys contained in this
1825 * <code>ResourceBundle</code> and its parent bundles.
1826 *
1827 * @return a <code>Set</code> of all keys contained in this
1828 * <code>ResourceBundle</code> and its parent bundles.
1829 * @since 1.6
1830 */
1831 public Set<String> keySet() {
1832 Set<String> keys = new HashSet<>();
1833 for (ResourceBundle rb = this; rb != null; rb = rb.parent) {
1834 keys.addAll(rb.handleKeySet());
1835 }
1836 return keys;
1837 }
1838
1839 /**
1840 * Returns a <code>Set</code> of the keys contained <em>only</em>
1841 * in this <code>ResourceBundle</code>.
1842 *
1843 * <p>The default implementation returns a <code>Set</code> of the
1844 * keys returned by the {@link #getKeys() getKeys} method except
1845 * for the ones for which the {@link #handleGetObject(String)
1846 * handleGetObject} method returns <code>null</code>. Once the
1847 * <code>Set</code> has been created, the value is kept in this
1848 * <code>ResourceBundle</code> in order to avoid producing the
1849 * same <code>Set</code> in subsequent calls. Subclasses can
1850 * override this method for faster handling.
1851 *
1852 * @return a <code>Set</code> of the keys contained only in this
1853 * <code>ResourceBundle</code>
1854 * @since 1.6
1855 */
1856 protected Set<String> handleKeySet() {
1857 if (keySet == null) {
1858 synchronized (this) {
1859 if (keySet == null) {
1860 Set<String> keys = new HashSet<>();
1861 Enumeration<String> enumKeys = getKeys();
1862 while (enumKeys.hasMoreElements()) {
1863 String key = enumKeys.nextElement();
1864 if (handleGetObject(key) != null) {
1865 keys.add(key);
1866 }
1867 }
1868 keySet = keys;
1869 }
1870 }
1871 }
1872 return keySet;
1873 }
1874
1875
1876
1877 /**
1878 * <code>ResourceBundle.Control</code> defines a set of callback methods
1879 * that are invoked by the {@link ResourceBundle#getBundle(String,
1880 * Locale, ClassLoader, Control) ResourceBundle.getBundle} factory
1881 * methods during the bundle loading process. In other words, a
1882 * <code>ResourceBundle.Control</code> collaborates with the factory
1883 * methods for loading resource bundles. The default implementation of
1884 * the callback methods provides the information necessary for the
1885 * factory methods to perform the <a
1886 * href="./ResourceBundle.html#default_behavior">default behavior</a>.
1887 *
1888 * <p>In addition to the callback methods, the {@link
1889 * #toBundleName(String, Locale) toBundleName} and {@link
1890 * #toResourceName(String, String) toResourceName} methods are defined
1891 * primarily for convenience in implementing the callback
1892 * methods. However, the <code>toBundleName</code> method could be
1893 * overridden to provide different conventions in the organization and
1894 * packaging of localized resources. The <code>toResourceName</code>
1895 * method is <code>final</code> to avoid use of wrong resource and class
1896 * name separators.
1897 *
1898 * <p>Two factory methods, {@link #getControl(List)} and {@link
1899 * #getNoFallbackControl(List)}, provide
1900 * <code>ResourceBundle.Control</code> instances that implement common
1901 * variations of the default bundle loading process.
1902 *
1903 * <p>The formats returned by the {@link Control#getFormats(String)
1904 * getFormats} method and candidate locales returned by the {@link
1905 * ResourceBundle.Control#getCandidateLocales(String, Locale)
1906 * getCandidateLocales} method must be consistent in all
1907 * <code>ResourceBundle.getBundle</code> invocations for the same base
1908 * bundle. Otherwise, the <code>ResourceBundle.getBundle</code> methods
1909 * may return unintended bundles. For example, if only
1910 * <code>"java.class"</code> is returned by the <code>getFormats</code>
1911 * method for the first call to <code>ResourceBundle.getBundle</code>
1912 * and only <code>"java.properties"</code> for the second call, then the
1913 * second call will return the class-based one that has been cached
1914 * during the first call.
1915 *
1916 * <p>A <code>ResourceBundle.Control</code> instance must be thread-safe
1917 * if it's simultaneously used by multiple threads.
1918 * <code>ResourceBundle.getBundle</code> does not synchronize to call
1919 * the <code>ResourceBundle.Control</code> methods. The default
1920 * implementations of the methods are thread-safe.
1921 *
1922 * <p>Applications can specify <code>ResourceBundle.Control</code>
1923 * instances returned by the <code>getControl</code> factory methods or
1924 * created from a subclass of <code>ResourceBundle.Control</code> to
1925 * customize the bundle loading process. The following are examples of
1926 * changing the default bundle loading process.
1927 *
1928 * <p><b>Example 1</b>
1929 *
1930 * <p>The following code lets <code>ResourceBundle.getBundle</code> look
1931 * up only properties-based resources.
1932 *
1933 * <pre>
1934 * import java.util.*;
1935 * import static java.util.ResourceBundle.Control.*;
1936 * ...
1937 * ResourceBundle bundle =
1938 * ResourceBundle.getBundle("MyResources", new Locale("fr", "CH"),
1939 * ResourceBundle.Control.getControl(FORMAT_PROPERTIES));
1940 * </pre>
1941 *
1942 * Given the resource bundles in the <a
1943 * href="./ResourceBundle.html#default_behavior_example">example</a> in
1944 * the <code>ResourceBundle.getBundle</code> description, this
1945 * <code>ResourceBundle.getBundle</code> call loads
1946 * <code>MyResources_fr_CH.properties</code> whose parent is
1947 * <code>MyResources_fr.properties</code> whose parent is
1948 * <code>MyResources.properties</code>. (<code>MyResources_fr_CH.properties</code>
1949 * is not hidden, but <code>MyResources_fr_CH.class</code> is.)
1950 *
1951 * <p><b>Example 2</b>
1952 *
1953 * <p>The following is an example of loading XML-based bundles
1954 * using {@link Properties#loadFromXML(java.io.InputStream)
1955 * Properties.loadFromXML}.
1956 *
1957 * <pre>
1958 * ResourceBundle rb = ResourceBundle.getBundle("Messages",
1959 * new ResourceBundle.Control() {
1960 * public List<String> getFormats(String baseName) {
1961 * if (baseName == null)
1962 * throw new NullPointerException();
1963 * return Arrays.asList("xml");
1964 * }
1965 * public ResourceBundle newBundle(String baseName,
1966 * Locale locale,
1967 * String format,
1968 * ClassLoader loader,
1969 * boolean reload)
1970 * throws IllegalAccessException,
1971 * InstantiationException,
1972 * IOException {
1973 * if (baseName == null || locale == null
1974 * || format == null || loader == null)
1975 * throw new NullPointerException();
1976 * ResourceBundle bundle = null;
1977 * if (format.equals("xml")) {
1978 * String bundleName = toBundleName(baseName, locale);
1979 * String resourceName = toResourceName(bundleName, format);
1980 * InputStream stream = null;
1981 * if (reload) {
1982 * URL url = loader.getResource(resourceName);
1983 * if (url != null) {
1984 * URLConnection connection = url.openConnection();
1985 * if (connection != null) {
1986 * // Disable caches to get fresh data for
1987 * // reloading.
1988 * connection.setUseCaches(false);
1989 * stream = connection.getInputStream();
1990 * }
1991 * }
1992 * } else {
1993 * stream = loader.getResourceAsStream(resourceName);
1994 * }
1995 * if (stream != null) {
1996 * BufferedInputStream bis = new BufferedInputStream(stream);
1997 * bundle = new XMLResourceBundle(bis);
1998 * bis.close();
1999 * }
2000 * }
2001 * return bundle;
2002 * }
2003 * });
2004 *
2005 * ...
2006 *
2007 * private static class XMLResourceBundle extends ResourceBundle {
2008 * private Properties props;
2009 * XMLResourceBundle(InputStream stream) throws IOException {
2010 * props = new Properties();
2011 * props.loadFromXML(stream);
2012 * }
2013 * protected Object handleGetObject(String key) {
2014 * return props.getProperty(key);
2015 * }
2016 * public Enumeration<String> getKeys() {
2017 * ...
2018 * }
2019 * }
2020 * </pre>
2021 *
2022 * @since 1.6
2023 */
2024 public static class Control {
2025 /**
2026 * The default format <code>List</code>, which contains the strings
2027 * <code>"java.class"</code> and <code>"java.properties"</code>, in
2028 * this order. This <code>List</code> is {@linkplain
2029 * Collections#unmodifiableList(List) unmodifiable}.
2030 *
2031 * @see #getFormats(String)
2032 */
2033 public static final List<String> FORMAT_DEFAULT
2034 = Collections.unmodifiableList(Arrays.asList("java.class",
2035 "java.properties"));
2036
2037 /**
2038 * The class-only format <code>List</code> containing
2039 * <code>"java.class"</code>. This <code>List</code> is {@linkplain
2040 * Collections#unmodifiableList(List) unmodifiable}.
2041 *
2042 * @see #getFormats(String)
2043 */
2044 public static final List<String> FORMAT_CLASS
2045 = Collections.unmodifiableList(Arrays.asList("java.class"));
2046
2047 /**
2048 * The properties-only format <code>List</code> containing
2049 * <code>"java.properties"</code>. This <code>List</code> is
2050 * {@linkplain Collections#unmodifiableList(List) unmodifiable}.
2051 *
2052 * @see #getFormats(String)
2053 */
2054 public static final List<String> FORMAT_PROPERTIES
2055 = Collections.unmodifiableList(Arrays.asList("java.properties"));
2056
2057 /**
2058 * The time-to-live constant for not caching loaded resource bundle
2059 * instances.
2060 *
2061 * @see #getTimeToLive(String, Locale)
2062 */
2063 public static final long TTL_DONT_CACHE = -1;
2064
2065 /**
2066 * The time-to-live constant for disabling the expiration control
2067 * for loaded resource bundle instances in the cache.
2068 *
2069 * @see #getTimeToLive(String, Locale)
2070 */
2071 public static final long TTL_NO_EXPIRATION_CONTROL = -2;
2072
2073 private static final Control INSTANCE = new Control();
2074
2075 /**
2076 * Sole constructor. (For invocation by subclass constructors,
2077 * typically implicit.)
2078 */
2079 protected Control() {
2080 }
2081
2082 /**
2083 * Returns a <code>ResourceBundle.Control</code> in which the {@link
2084 * #getFormats(String) getFormats} method returns the specified
2085 * <code>formats</code>. The <code>formats</code> must be equal to
2086 * one of {@link Control#FORMAT_PROPERTIES}, {@link
2087 * Control#FORMAT_CLASS} or {@link
2088 * Control#FORMAT_DEFAULT}. <code>ResourceBundle.Control</code>
2089 * instances returned by this method are singletons and thread-safe.
2090 *
2091 * <p>Specifying {@link Control#FORMAT_DEFAULT} is equivalent to
2092 * instantiating the <code>ResourceBundle.Control</code> class,
2093 * except that this method returns a singleton.
2094 *
2095 * @param formats
2096 * the formats to be returned by the
2097 * <code>ResourceBundle.Control.getFormats</code> method
2098 * @return a <code>ResourceBundle.Control</code> supporting the
2099 * specified <code>formats</code>
2100 * @exception NullPointerException
2101 * if <code>formats</code> is <code>null</code>
2102 * @exception IllegalArgumentException
2103 * if <code>formats</code> is unknown
2104 */
2105 public static final Control getControl(List<String> formats) {
2106 if (formats.equals(Control.FORMAT_PROPERTIES)) {
2107 return SingleFormatControl.PROPERTIES_ONLY;
2108 }
2109 if (formats.equals(Control.FORMAT_CLASS)) {
2110 return SingleFormatControl.CLASS_ONLY;
2111 }
2112 if (formats.equals(Control.FORMAT_DEFAULT)) {
2113 return Control.INSTANCE;
2114 }
2115 throw new IllegalArgumentException();
2116 }
2117
2118 /**
2119 * Returns a <code>ResourceBundle.Control</code> in which the {@link
2120 * #getFormats(String) getFormats} method returns the specified
2121 * <code>formats</code> and the {@link
2122 * Control#getFallbackLocale(String, Locale) getFallbackLocale}
2123 * method returns <code>null</code>. The <code>formats</code> must
2124 * be equal to one of {@link Control#FORMAT_PROPERTIES}, {@link
2125 * Control#FORMAT_CLASS} or {@link Control#FORMAT_DEFAULT}.
2126 * <code>ResourceBundle.Control</code> instances returned by this
2127 * method are singletons and thread-safe.
2128 *
2129 * @param formats
2130 * the formats to be returned by the
2131 * <code>ResourceBundle.Control.getFormats</code> method
2132 * @return a <code>ResourceBundle.Control</code> supporting the
2133 * specified <code>formats</code> with no fallback
2134 * <code>Locale</code> support
2135 * @exception NullPointerException
2136 * if <code>formats</code> is <code>null</code>
2137 * @exception IllegalArgumentException
2138 * if <code>formats</code> is unknown
2139 */
2140 public static final Control getNoFallbackControl(List<String> formats) {
2141 if (formats.equals(Control.FORMAT_DEFAULT)) {
2142 return NoFallbackControl.NO_FALLBACK;
2143 }
2144 if (formats.equals(Control.FORMAT_PROPERTIES)) {
2145 return NoFallbackControl.PROPERTIES_ONLY_NO_FALLBACK;
2146 }
2147 if (formats.equals(Control.FORMAT_CLASS)) {
2148 return NoFallbackControl.CLASS_ONLY_NO_FALLBACK;
2149 }
2150 throw new IllegalArgumentException();
2151 }
2152
2153 /**
2154 * Returns a <code>List</code> of <code>String</code>s containing
2155 * formats to be used to load resource bundles for the given
2156 * <code>baseName</code>. The <code>ResourceBundle.getBundle</code>
2157 * factory method tries to load resource bundles with formats in the
2158 * order specified by the list. The list returned by this method
2159 * must have at least one <code>String</code>. The predefined
2160 * formats are <code>"java.class"</code> for class-based resource
2161 * bundles and <code>"java.properties"</code> for {@linkplain
2162 * PropertyResourceBundle properties-based} ones. Strings starting
2163 * with <code>"java."</code> are reserved for future extensions and
2164 * must not be used by application-defined formats.
2165 *
2166 * <p>It is not a requirement to return an immutable (unmodifiable)
2167 * <code>List</code>. However, the returned <code>List</code> must
2168 * not be mutated after it has been returned by
2169 * <code>getFormats</code>.
2170 *
2171 * <p>The default implementation returns {@link #FORMAT_DEFAULT} so
2172 * that the <code>ResourceBundle.getBundle</code> factory method
2173 * looks up first class-based resource bundles, then
2174 * properties-based ones.
2175 *
2176 * @param baseName
2177 * the base name of the resource bundle, a fully qualified class
2178 * name
2179 * @return a <code>List</code> of <code>String</code>s containing
2180 * formats for loading resource bundles.
2181 * @exception NullPointerException
2182 * if <code>baseName</code> is null
2183 * @see #FORMAT_DEFAULT
2184 * @see #FORMAT_CLASS
2185 * @see #FORMAT_PROPERTIES
2186 */
2187 public List<String> getFormats(String baseName) {
2188 if (baseName == null) {
2189 throw new NullPointerException();
2190 }
2191 return FORMAT_DEFAULT;
2192 }
2193
2194 /**
2195 * Returns a <code>List</code> of <code>Locale</code>s as candidate
2196 * locales for <code>baseName</code> and <code>locale</code>. This
2197 * method is called by the <code>ResourceBundle.getBundle</code>
2198 * factory method each time the factory method tries finding a
2199 * resource bundle for a target <code>Locale</code>.
2200 *
2201 * <p>The sequence of the candidate locales also corresponds to the
2202 * runtime resource lookup path (also known as the <I>parent
2203 * chain</I>), if the corresponding resource bundles for the
2204 * candidate locales exist and their parents are not defined by
2205 * loaded resource bundles themselves. The last element of the list
2206 * must be a {@linkplain Locale#ROOT root locale} if it is desired to
2207 * have the base bundle as the terminal of the parent chain.
2208 *
2209 * <p>If the given locale is equal to <code>Locale.ROOT</code> (the
2210 * root locale), a <code>List</code> containing only the root
2211 * <code>Locale</code> must be returned. In this case, the
2212 * <code>ResourceBundle.getBundle</code> factory method loads only
2213 * the base bundle as the resulting resource bundle.
2214 *
2215 * <p>It is not a requirement to return an immutable (unmodifiable)
2216 * <code>List</code>. However, the returned <code>List</code> must not
2217 * be mutated after it has been returned by
2218 * <code>getCandidateLocales</code>.
2219 *
2220 * <p>The default implementation returns a <code>List</code> containing
2221 * <code>Locale</code>s using the rules described below. In the
2222 * description below, <em>L</em>, <em>S</em>, <em>C</em> and <em>V</em>
2223 * respectively represent non-empty language, script, country, and
2224 * variant. For example, [<em>L</em>, <em>C</em>] represents a
2225 * <code>Locale</code> that has non-empty values only for language and
2226 * country. The form <em>L</em>("xx") represents the (non-empty)
2227 * language value is "xx". For all cases, <code>Locale</code>s whose
2228 * final component values are empty strings are omitted.
2229 *
2230 * <ol><li>For an input <code>Locale</code> with an empty script value,
2231 * append candidate <code>Locale</code>s by omitting the final component
2232 * one by one as below:
2233 *
2234 * <ul>
2235 * <li> [<em>L</em>, <em>C</em>, <em>V</em>] </li>
2236 * <li> [<em>L</em>, <em>C</em>] </li>
2237 * <li> [<em>L</em>] </li>
2238 * <li> <code>Locale.ROOT</code> </li>
2239 * </ul></li>
2240 *
2241 * <li>For an input <code>Locale</code> with a non-empty script value,
2242 * append candidate <code>Locale</code>s by omitting the final component
2243 * up to language, then append candidates generated from the
2244 * <code>Locale</code> with country and variant restored:
2245 *
2246 * <ul>
2247 * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V</em>]</li>
2248 * <li> [<em>L</em>, <em>S</em>, <em>C</em>]</li>
2249 * <li> [<em>L</em>, <em>S</em>]</li>
2250 * <li> [<em>L</em>, <em>C</em>, <em>V</em>]</li>
2251 * <li> [<em>L</em>, <em>C</em>]</li>
2252 * <li> [<em>L</em>]</li>
2253 * <li> <code>Locale.ROOT</code></li>
2254 * </ul></li>
2255 *
2256 * <li>For an input <code>Locale</code> with a variant value consisting
2257 * of multiple subtags separated by underscore, generate candidate
2258 * <code>Locale</code>s by omitting the variant subtags one by one, then
2259 * insert them after every occurrence of <code> Locale</code>s with the
2260 * full variant value in the original list. For example, if the
2261 * the variant consists of two subtags <em>V1</em> and <em>V2</em>:
2262 *
2263 * <ul>
2264 * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]</li>
2265 * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>]</li>
2266 * <li> [<em>L</em>, <em>S</em>, <em>C</em>]</li>
2267 * <li> [<em>L</em>, <em>S</em>]</li>
2268 * <li> [<em>L</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]</li>
2269 * <li> [<em>L</em>, <em>C</em>, <em>V1</em>]</li>
2270 * <li> [<em>L</em>, <em>C</em>]</li>
2271 * <li> [<em>L</em>]</li>
2272 * <li> <code>Locale.ROOT</code></li>
2273 * </ul></li>
2274 *
2275 * <li>Special cases for Chinese. When an input <code>Locale</code> has the
2276 * language "zh" (Chinese) and an empty script value, either "Hans" (Simplified) or
2277 * "Hant" (Traditional) might be supplied, depending on the country.
2278 * When the country is "CN" (China) or "SG" (Singapore), "Hans" is supplied.
2279 * When the country is "HK" (Hong Kong SAR China), "MO" (Macau SAR China),
2280 * or "TW" (Taiwan), "Hant" is supplied. For all other countries or when the country
2281 * is empty, no script is supplied. For example, for <code>Locale("zh", "CN")
2282 * </code>, the candidate list will be:
2283 * <ul>
2284 * <li> [<em>L</em>("zh"), <em>S</em>("Hans"), <em>C</em>("CN")]</li>
2285 * <li> [<em>L</em>("zh"), <em>S</em>("Hans")]</li>
2286 * <li> [<em>L</em>("zh"), <em>C</em>("CN")]</li>
2287 * <li> [<em>L</em>("zh")]</li>
2288 * <li> <code>Locale.ROOT</code></li>
2289 * </ul>
2290 *
2291 * For <code>Locale("zh", "TW")</code>, the candidate list will be:
2292 * <ul>
2293 * <li> [<em>L</em>("zh"), <em>S</em>("Hant"), <em>C</em>("TW")]</li>
2294 * <li> [<em>L</em>("zh"), <em>S</em>("Hant")]</li>
2295 * <li> [<em>L</em>("zh"), <em>C</em>("TW")]</li>
2296 * <li> [<em>L</em>("zh")]</li>
2297 * <li> <code>Locale.ROOT</code></li>
2298 * </ul></li>
2299 *
2300 * <li>Special cases for Norwegian. Both <code>Locale("no", "NO",
2301 * "NY")</code> and <code>Locale("nn", "NO")</code> represent Norwegian
2302 * Nynorsk. When a locale's language is "nn", the standard candidate
2303 * list is generated up to [<em>L</em>("nn")], and then the following
2304 * candidates are added:
2305 *
2306 * <ul><li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("NY")]</li>
2307 * <li> [<em>L</em>("no"), <em>C</em>("NO")]</li>
2308 * <li> [<em>L</em>("no")]</li>
2309 * <li> <code>Locale.ROOT</code></li>
2310 * </ul>
2311 *
2312 * If the locale is exactly <code>Locale("no", "NO", "NY")</code>, it is first
2313 * converted to <code>Locale("nn", "NO")</code> and then the above procedure is
2314 * followed.
2315 *
2316 * <p>Also, Java treats the language "no" as a synonym of Norwegian
2317 * Bokmål "nb". Except for the single case <code>Locale("no",
2318 * "NO", "NY")</code> (handled above), when an input <code>Locale</code>
2319 * has language "no" or "nb", candidate <code>Locale</code>s with
2320 * language code "no" and "nb" are interleaved, first using the
2321 * requested language, then using its synonym. For example,
2322 * <code>Locale("nb", "NO", "POSIX")</code> generates the following
2323 * candidate list:
2324 *
2325 * <ul>
2326 * <li> [<em>L</em>("nb"), <em>C</em>("NO"), <em>V</em>("POSIX")]</li>
2327 * <li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("POSIX")]</li>
2328 * <li> [<em>L</em>("nb"), <em>C</em>("NO")]</li>
2329 * <li> [<em>L</em>("no"), <em>C</em>("NO")]</li>
2330 * <li> [<em>L</em>("nb")]</li>
2331 * <li> [<em>L</em>("no")]</li>
2332 * <li> <code>Locale.ROOT</code></li>
2333 * </ul>
2334 *
2335 * <code>Locale("no", "NO", "POSIX")</code> would generate the same list
2336 * except that locales with "no" would appear before the corresponding
2337 * locales with "nb".</li>
2338 * </ol>
2339 *
2340 * <p>The default implementation uses an {@link ArrayList} that
2341 * overriding implementations may modify before returning it to the
2342 * caller. However, a subclass must not modify it after it has
2343 * been returned by <code>getCandidateLocales</code>.
2344 *
2345 * <p>For example, if the given <code>baseName</code> is "Messages"
2346 * and the given <code>locale</code> is
2347 * <code>Locale("ja", "", "XX")</code>, then a
2348 * <code>List</code> of <code>Locale</code>s:
2349 * <pre>
2350 * Locale("ja", "", "XX")
2351 * Locale("ja")
2352 * Locale.ROOT
2353 * </pre>
2354 * is returned. And if the resource bundles for the "ja" and
2355 * "" <code>Locale</code>s are found, then the runtime resource
2356 * lookup path (parent chain) is:
2357 * <pre>{@code
2358 * Messages_ja -> Messages
2359 * }</pre>
2360 *
2361 * @param baseName
2362 * the base name of the resource bundle, a fully
2363 * qualified class name
2364 * @param locale
2365 * the locale for which a resource bundle is desired
2366 * @return a <code>List</code> of candidate
2367 * <code>Locale</code>s for the given <code>locale</code>
2368 * @exception NullPointerException
2369 * if <code>baseName</code> or <code>locale</code> is
2370 * <code>null</code>
2371 */
2372 public List<Locale> getCandidateLocales(String baseName, Locale locale) {
2373 if (baseName == null) {
2374 throw new NullPointerException();
2375 }
2376 return new ArrayList<>(CANDIDATES_CACHE.get(locale.getBaseLocale()));
2377 }
2378
2379 private static final CandidateListCache CANDIDATES_CACHE = new CandidateListCache();
2380
2381 private static class CandidateListCache extends LocaleObjectCache<BaseLocale, List<Locale>> {
2382 protected List<Locale> createObject(BaseLocale base) {
2383 String language = base.getLanguage();
2384 String script = base.getScript();
2385 String region = base.getRegion();
2386 String variant = base.getVariant();
2387
2388 // Special handling for Norwegian
2389 boolean isNorwegianBokmal = false;
2390 boolean isNorwegianNynorsk = false;
2391 if (language.equals("no")) {
2392 if (region.equals("NO") && variant.equals("NY")) {
2393 variant = "";
2394 isNorwegianNynorsk = true;
2395 } else {
2396 isNorwegianBokmal = true;
2397 }
2398 }
2399 if (language.equals("nb") || isNorwegianBokmal) {
2400 List<Locale> tmpList = getDefaultList("nb", script, region, variant);
2401 // Insert a locale replacing "nb" with "no" for every list entry
2402 List<Locale> bokmalList = new LinkedList<>();
2403 for (Locale l : tmpList) {
2404 bokmalList.add(l);
2405 if (l.getLanguage().length() == 0) {
2406 break;
2407 }
2408 bokmalList.add(Locale.getInstance("no", l.getScript(), l.getCountry(),
2409 l.getVariant(), null));
2410 }
2411 return bokmalList;
2412 } else if (language.equals("nn") || isNorwegianNynorsk) {
2413 // Insert no_NO_NY, no_NO, no after nn
2414 List<Locale> nynorskList = getDefaultList("nn", script, region, variant);
2415 int idx = nynorskList.size() - 1;
2416 nynorskList.add(idx++, Locale.getInstance("no", "NO", "NY"));
2417 nynorskList.add(idx++, Locale.getInstance("no", "NO", ""));
2418 nynorskList.add(idx++, Locale.getInstance("no", "", ""));
2419 return nynorskList;
2420 }
2421 // Special handling for Chinese
2422 else if (language.equals("zh")) {
2423 if (script.length() == 0 && region.length() > 0) {
2424 // Supply script for users who want to use zh_Hans/zh_Hant
2425 // as bundle names (recommended for Java7+)
2426 switch (region) {
2427 case "TW":
2428 case "HK":
2429 case "MO":
2430 script = "Hant";
2431 break;
2432 case "CN":
2433 case "SG":
2434 script = "Hans";
2435 break;
2436 }
2437 } else if (script.length() > 0 && region.length() == 0) {
2438 // Supply region(country) for users who still package Chinese
2439 // bundles using old convension.
2440 switch (script) {
2441 case "Hans":
2442 region = "CN";
2443 break;
2444 case "Hant":
2445 region = "TW";
2446 break;
2447 }
2448 }
2449 }
2450
2451 return getDefaultList(language, script, region, variant);
2452 }
2453
2454 private static List<Locale> getDefaultList(String language, String script, String region, String variant) {
2455 List<String> variants = null;
2456
2457 if (variant.length() > 0) {
2458 variants = new LinkedList<>();
2459 int idx = variant.length();
2460 while (idx != -1) {
2461 variants.add(variant.substring(0, idx));
2462 idx = variant.lastIndexOf('_', --idx);
2463 }
2464 }
2465
2466 List<Locale> list = new LinkedList<>();
2467
2468 if (variants != null) {
2469 for (String v : variants) {
2470 list.add(Locale.getInstance(language, script, region, v, null));
2471 }
2472 }
2473 if (region.length() > 0) {
2474 list.add(Locale.getInstance(language, script, region, "", null));
2475 }
2476 if (script.length() > 0) {
2477 list.add(Locale.getInstance(language, script, "", "", null));
2478
2479 // With script, after truncating variant, region and script,
2480 // start over without script.
2481 if (variants != null) {
2482 for (String v : variants) {
2483 list.add(Locale.getInstance(language, "", region, v, null));
2484 }
2485 }
2486 if (region.length() > 0) {
2487 list.add(Locale.getInstance(language, "", region, "", null));
2488 }
2489 }
2490 if (language.length() > 0) {
2491 list.add(Locale.getInstance(language, "", "", "", null));
2492 }
2493 // Add root locale at the end
2494 list.add(Locale.ROOT);
2495
2496 return list;
2497 }
2498 }
2499
2500 /**
2501 * Returns a <code>Locale</code> to be used as a fallback locale for
2502 * further resource bundle searches by the
2503 * <code>ResourceBundle.getBundle</code> factory method. This method
2504 * is called from the factory method every time when no resulting
2505 * resource bundle has been found for <code>baseName</code> and
2506 * <code>locale</code>, where locale is either the parameter for
2507 * <code>ResourceBundle.getBundle</code> or the previous fallback
2508 * locale returned by this method.
2509 *
2510 * <p>The method returns <code>null</code> if no further fallback
2511 * search is desired.
2512 *
2513 * <p>The default implementation returns the {@linkplain
2514 * Locale#getDefault() default <code>Locale</code>} if the given
2515 * <code>locale</code> isn't the default one. Otherwise,
2516 * <code>null</code> is returned.
2517 *
2518 * @param baseName
2519 * the base name of the resource bundle, a fully
2520 * qualified class name for which
2521 * <code>ResourceBundle.getBundle</code> has been
2522 * unable to find any resource bundles (except for the
2523 * base bundle)
2524 * @param locale
2525 * the <code>Locale</code> for which
2526 * <code>ResourceBundle.getBundle</code> has been
2527 * unable to find any resource bundles (except for the
2528 * base bundle)
2529 * @return a <code>Locale</code> for the fallback search,
2530 * or <code>null</code> if no further fallback search
2531 * is desired.
2532 * @exception NullPointerException
2533 * if <code>baseName</code> or <code>locale</code>
2534 * is <code>null</code>
2535 */
2536 public Locale getFallbackLocale(String baseName, Locale locale) {
2537 if (baseName == null) {
2538 throw new NullPointerException();
2539 }
2540 Locale defaultLocale = Locale.getDefault();
2541 return locale.equals(defaultLocale) ? null : defaultLocale;
2542 }
2543
2544 /**
2545 * Instantiates a resource bundle for the given bundle name of the
2546 * given format and locale, using the given class loader if
2547 * necessary. This method returns <code>null</code> if there is no
2548 * resource bundle available for the given parameters. If a resource
2549 * bundle can't be instantiated due to an unexpected error, the
2550 * error must be reported by throwing an <code>Error</code> or
2551 * <code>Exception</code> rather than simply returning
2552 * <code>null</code>.
2553 *
2554 * <p>If the <code>reload</code> flag is <code>true</code>, it
2555 * indicates that this method is being called because the previously
2556 * loaded resource bundle has expired.
2557 *
2558 * <p>The default implementation instantiates a
2559 * <code>ResourceBundle</code> as follows.
2560 *
2561 * <ul>
2562 *
2563 * <li>The bundle name is obtained by calling {@link
2564 * #toBundleName(String, Locale) toBundleName(baseName,
2565 * locale)}.</li>
2566 *
2567 * <li>If <code>format</code> is <code>"java.class"</code>, the
2568 * {@link Class} specified by the bundle name is loaded by calling
2569 * {@link ClassLoader#loadClass(String)}. Then, a
2570 * <code>ResourceBundle</code> is instantiated by calling {@link
2571 * Class#newInstance()}. Note that the <code>reload</code> flag is
2572 * ignored for loading class-based resource bundles in this default
2573 * implementation.</li>
2574 *
2575 * <li>If <code>format</code> is <code>"java.properties"</code>,
2576 * {@link #toResourceName(String, String) toResourceName(bundlename,
2577 * "properties")} is called to get the resource name.
2578 * If <code>reload</code> is <code>true</code>, {@link
2579 * ClassLoader#getResource(String) load.getResource} is called
2580 * to get a {@link URL} for creating a {@link
2581 * URLConnection}. This <code>URLConnection</code> is used to
2582 * {@linkplain URLConnection#setUseCaches(boolean) disable the
2583 * caches} of the underlying resource loading layers,
2584 * and to {@linkplain URLConnection#getInputStream() get an
2585 * <code>InputStream</code>}.
2586 * Otherwise, {@link ClassLoader#getResourceAsStream(String)
2587 * loader.getResourceAsStream} is called to get an {@link
2588 * InputStream}. Then, a {@link
2589 * PropertyResourceBundle} is constructed with the
2590 * <code>InputStream</code>.</li>
2591 *
2592 * <li>If <code>format</code> is neither <code>"java.class"</code>
2593 * nor <code>"java.properties"</code>, an
2594 * <code>IllegalArgumentException</code> is thrown.</li>
2595 *
2596 * </ul>
2597 *
2598 * @param baseName
2599 * the base bundle name of the resource bundle, a fully
2600 * qualified class name
2601 * @param locale
2602 * the locale for which the resource bundle should be
2603 * instantiated
2604 * @param format
2605 * the resource bundle format to be loaded
2606 * @param loader
2607 * the <code>ClassLoader</code> to use to load the bundle
2608 * @param reload
2609 * the flag to indicate bundle reloading; <code>true</code>
2610 * if reloading an expired resource bundle,
2611 * <code>false</code> otherwise
2612 * @return the resource bundle instance,
2613 * or <code>null</code> if none could be found.
2614 * @exception NullPointerException
2615 * if <code>bundleName</code>, <code>locale</code>,
2616 * <code>format</code>, or <code>loader</code> is
2617 * <code>null</code>, or if <code>null</code> is returned by
2618 * {@link #toBundleName(String, Locale) toBundleName}
2619 * @exception IllegalArgumentException
2620 * if <code>format</code> is unknown, or if the resource
2621 * found for the given parameters contains malformed data.
2622 * @exception ClassCastException
2623 * if the loaded class cannot be cast to <code>ResourceBundle</code>
2624 * @exception IllegalAccessException
2625 * if the class or its nullary constructor is not
2626 * accessible.
2627 * @exception InstantiationException
2628 * if the instantiation of a class fails for some other
2629 * reason.
2630 * @exception ExceptionInInitializerError
2631 * if the initialization provoked by this method fails.
2632 * @exception SecurityException
2633 * If a security manager is present and creation of new
2634 * instances is denied. See {@link Class#newInstance()}
2635 * for details.
2636 * @exception IOException
2637 * if an error occurred when reading resources using
2638 * any I/O operations
2639 */
2640 public ResourceBundle newBundle(String baseName, Locale locale, String format,
2641 ClassLoader loader, boolean reload)
2642 throws IllegalAccessException, InstantiationException, IOException {
2643 String bundleName = toBundleName(baseName, locale);
2644 ResourceBundle bundle = null;
2645 if (format.equals("java.class")) {
2646 try {
2647 @SuppressWarnings("unchecked")
2648 Class<? extends ResourceBundle> bundleClass
2649 = (Class<? extends ResourceBundle>)loader.loadClass(bundleName);
2650
2651 // If the class isn't a ResourceBundle subclass, throw a
2652 // ClassCastException.
2653 if (ResourceBundle.class.isAssignableFrom(bundleClass)) {
2654 bundle = bundleClass.newInstance();
2655 } else {
2656 throw new ClassCastException(bundleClass.getName()
2657 + " cannot be cast to ResourceBundle");
2658 }
2659 } catch (ClassNotFoundException e) {
2660 }
2661 } else if (format.equals("java.properties")) {
2662 final String resourceName = toResourceName0(bundleName, "properties");
2663 if (resourceName == null) {
2664 return bundle;
2665 }
2666 final ClassLoader classLoader = loader;
2667 final boolean reloadFlag = reload;
2668 InputStream stream = null;
2669 try {
2670 stream = AccessController.doPrivileged(
2671 new PrivilegedExceptionAction<InputStream>() {
2672 public InputStream run() throws IOException {
2673 InputStream is = null;
2674 if (reloadFlag) {
2675 URL url = classLoader.getResource(resourceName);
2676 if (url != null) {
2677 URLConnection connection = url.openConnection();
2678 if (connection != null) {
2679 // Disable caches to get fresh data for
2680 // reloading.
2681 connection.setUseCaches(false);
2682 is = connection.getInputStream();
2683 }
2684 }
2685 } else {
2686 is = classLoader.getResourceAsStream(resourceName);
2687 }
2688 return is;
2689 }
2690 });
2691 } catch (PrivilegedActionException e) {
2692 throw (IOException) e.getException();
2693 }
2694 if (stream != null) {
2695 try {
2696 bundle = new PropertyResourceBundle(stream);
2697 } finally {
2698 stream.close();
2699 }
2700 }
2701 } else {
2702 throw new IllegalArgumentException("unknown format: " + format);
2703 }
2704 return bundle;
2705 }
2706
2707 /**
2708 * Returns the time-to-live (TTL) value for resource bundles that
2709 * are loaded under this
2710 * <code>ResourceBundle.Control</code>. Positive time-to-live values
2711 * specify the number of milliseconds a bundle can remain in the
2712 * cache without being validated against the source data from which
2713 * it was constructed. The value 0 indicates that a bundle must be
2714 * validated each time it is retrieved from the cache. {@link
2715 * #TTL_DONT_CACHE} specifies that loaded resource bundles are not
2716 * put in the cache. {@link #TTL_NO_EXPIRATION_CONTROL} specifies
2717 * that loaded resource bundles are put in the cache with no
2718 * expiration control.
2719 *
2720 * <p>The expiration affects only the bundle loading process by the
2721 * <code>ResourceBundle.getBundle</code> factory method. That is,
2722 * if the factory method finds a resource bundle in the cache that
2723 * has expired, the factory method calls the {@link
2724 * #needsReload(String, Locale, String, ClassLoader, ResourceBundle,
2725 * long) needsReload} method to determine whether the resource
2726 * bundle needs to be reloaded. If <code>needsReload</code> returns
2727 * <code>true</code>, the cached resource bundle instance is removed
2728 * from the cache. Otherwise, the instance stays in the cache,
2729 * updated with the new TTL value returned by this method.
2730 *
2731 * <p>All cached resource bundles are subject to removal from the
2732 * cache due to memory constraints of the runtime environment.
2733 * Returning a large positive value doesn't mean to lock loaded
2734 * resource bundles in the cache.
2735 *
2736 * <p>The default implementation returns {@link #TTL_NO_EXPIRATION_CONTROL}.
2737 *
2738 * @param baseName
2739 * the base name of the resource bundle for which the
2740 * expiration value is specified.
2741 * @param locale
2742 * the locale of the resource bundle for which the
2743 * expiration value is specified.
2744 * @return the time (0 or a positive millisecond offset from the
2745 * cached time) to get loaded bundles expired in the cache,
2746 * {@link #TTL_NO_EXPIRATION_CONTROL} to disable the
2747 * expiration control, or {@link #TTL_DONT_CACHE} to disable
2748 * caching.
2749 * @exception NullPointerException
2750 * if <code>baseName</code> or <code>locale</code> is
2751 * <code>null</code>
2752 */
2753 public long getTimeToLive(String baseName, Locale locale) {
2754 if (baseName == null || locale == null) {
2755 throw new NullPointerException();
2756 }
2757 return TTL_NO_EXPIRATION_CONTROL;
2758 }
2759
2760 /**
2761 * Determines if the expired <code>bundle</code> in the cache needs
2762 * to be reloaded based on the loading time given by
2763 * <code>loadTime</code> or some other criteria. The method returns
2764 * <code>true</code> if reloading is required; <code>false</code>
2765 * otherwise. <code>loadTime</code> is a millisecond offset since
2766 * the <a href="Calendar.html#Epoch"> <code>Calendar</code>
2767 * Epoch</a>.
2768 *
2769 * The calling <code>ResourceBundle.getBundle</code> factory method
2770 * calls this method on the <code>ResourceBundle.Control</code>
2771 * instance used for its current invocation, not on the instance
2772 * used in the invocation that originally loaded the resource
2773 * bundle.
2774 *
2775 * <p>The default implementation compares <code>loadTime</code> and
2776 * the last modified time of the source data of the resource
2777 * bundle. If it's determined that the source data has been modified
2778 * since <code>loadTime</code>, <code>true</code> is
2779 * returned. Otherwise, <code>false</code> is returned. This
2780 * implementation assumes that the given <code>format</code> is the
2781 * same string as its file suffix if it's not one of the default
2782 * formats, <code>"java.class"</code> or
2783 * <code>"java.properties"</code>.
2784 *
2785 * @param baseName
2786 * the base bundle name of the resource bundle, a
2787 * fully qualified class name
2788 * @param locale
2789 * the locale for which the resource bundle
2790 * should be instantiated
2791 * @param format
2792 * the resource bundle format to be loaded
2793 * @param loader
2794 * the <code>ClassLoader</code> to use to load the bundle
2795 * @param bundle
2796 * the resource bundle instance that has been expired
2797 * in the cache
2798 * @param loadTime
2799 * the time when <code>bundle</code> was loaded and put
2800 * in the cache
2801 * @return <code>true</code> if the expired bundle needs to be
2802 * reloaded; <code>false</code> otherwise.
2803 * @exception NullPointerException
2804 * if <code>baseName</code>, <code>locale</code>,
2805 * <code>format</code>, <code>loader</code>, or
2806 * <code>bundle</code> is <code>null</code>
2807 */
2808 public boolean needsReload(String baseName, Locale locale,
2809 String format, ClassLoader loader,
2810 ResourceBundle bundle, long loadTime) {
2811 if (bundle == null) {
2812 throw new NullPointerException();
2813 }
2814 if (format.equals("java.class") || format.equals("java.properties")) {
2815 format = format.substring(5);
2816 }
2817 boolean result = false;
2818 try {
2819 String resourceName = toResourceName0(toBundleName(baseName, locale), format);
2820 if (resourceName == null) {
2821 return result;
2822 }
2823 URL url = loader.getResource(resourceName);
2824 if (url != null) {
2825 long lastModified = 0;
2826 URLConnection connection = url.openConnection();
2827 if (connection != null) {
2828 // disable caches to get the correct data
2829 connection.setUseCaches(false);
2830 if (connection instanceof JarURLConnection) {
2831 JarEntry ent = ((JarURLConnection)connection).getJarEntry();
2832 if (ent != null) {
2833 lastModified = ent.getTime();
2834 if (lastModified == -1) {
2835 lastModified = 0;
2836 }
2837 }
2838 } else {
2839 lastModified = connection.getLastModified();
2840 }
2841 }
2842 result = lastModified >= loadTime;
2843 }
2844 } catch (NullPointerException npe) {
2845 throw npe;
2846 } catch (Exception e) {
2847 // ignore other exceptions
2848 }
2849 return result;
2850 }
2851
2852 /**
2853 * Converts the given <code>baseName</code> and <code>locale</code>
2854 * to the bundle name. This method is called from the default
2855 * implementation of the {@link #newBundle(String, Locale, String,
2856 * ClassLoader, boolean) newBundle} and {@link #needsReload(String,
2857 * Locale, String, ClassLoader, ResourceBundle, long) needsReload}
2858 * methods.
2859 *
2860 * <p>This implementation returns the following value:
2861 * <pre>
2862 * baseName + "_" + language + "_" + script + "_" + country + "_" + variant
2863 * </pre>
2864 * where <code>language</code>, <code>script</code>, <code>country</code>,
2865 * and <code>variant</code> are the language, script, country, and variant
2866 * values of <code>locale</code>, respectively. Final component values that
2867 * are empty Strings are omitted along with the preceding '_'. When the
2868 * script is empty, the script value is omitted along with the preceding '_'.
2869 * If all of the values are empty strings, then <code>baseName</code>
2870 * is returned.
2871 *
2872 * <p>For example, if <code>baseName</code> is
2873 * <code>"baseName"</code> and <code>locale</code> is
2874 * <code>Locale("ja", "", "XX")</code>, then
2875 * <code>"baseName_ja_ _XX"</code> is returned. If the given
2876 * locale is <code>Locale("en")</code>, then
2877 * <code>"baseName_en"</code> is returned.
2878 *
2879 * <p>Overriding this method allows applications to use different
2880 * conventions in the organization and packaging of localized
2881 * resources.
2882 *
2883 * @param baseName
2884 * the base name of the resource bundle, a fully
2885 * qualified class name
2886 * @param locale
2887 * the locale for which a resource bundle should be
2888 * loaded
2889 * @return the bundle name for the resource bundle
2890 * @exception NullPointerException
2891 * if <code>baseName</code> or <code>locale</code>
2892 * is <code>null</code>
2893 */
2894 public String toBundleName(String baseName, Locale locale) {
2895 if (locale == Locale.ROOT) {
2896 return baseName;
2897 }
2898
2899 String language = locale.getLanguage();
2900 String script = locale.getScript();
2901 String country = locale.getCountry();
2902 String variant = locale.getVariant();
2903
2904 if (language == "" && country == "" && variant == "") {
2905 return baseName;
2906 }
2907
2908 StringBuilder sb = new StringBuilder(baseName);
2909 sb.append('_');
2910 if (script != "") {
2911 if (variant != "") {
2912 sb.append(language).append('_').append(script).append('_').append(country).append('_').append(variant);
2913 } else if (country != "") {
2914 sb.append(language).append('_').append(script).append('_').append(country);
2915 } else {
2916 sb.append(language).append('_').append(script);
2917 }
2918 } else {
2919 if (variant != "") {
2920 sb.append(language).append('_').append(country).append('_').append(variant);
2921 } else if (country != "") {
2922 sb.append(language).append('_').append(country);
2923 } else {
2924 sb.append(language);
2925 }
2926 }
2927 return sb.toString();
2928
2929 }
2930
2931 /**
2932 * Converts the given <code>bundleName</code> to the form required
2933 * by the {@link ClassLoader#getResource ClassLoader.getResource}
2934 * method by replacing all occurrences of <code>'.'</code> in
2935 * <code>bundleName</code> with <code>'/'</code> and appending a
2936 * <code>'.'</code> and the given file <code>suffix</code>. For
2937 * example, if <code>bundleName</code> is
2938 * <code>"foo.bar.MyResources_ja_JP"</code> and <code>suffix</code>
2939 * is <code>"properties"</code>, then
2940 * <code>"foo/bar/MyResources_ja_JP.properties"</code> is returned.
2941 *
2942 * @param bundleName
2943 * the bundle name
2944 * @param suffix
2945 * the file type suffix
2946 * @return the converted resource name
2947 * @exception NullPointerException
2948 * if <code>bundleName</code> or <code>suffix</code>
2949 * is <code>null</code>
2950 */
2951 public final String toResourceName(String bundleName, String suffix) {
2952 StringBuilder sb = new StringBuilder(bundleName.length() + 1 + suffix.length());
2953 sb.append(bundleName.replace('.', '/')).append('.').append(suffix);
2954 return sb.toString();
2955 }
2956
2957 private String toResourceName0(String bundleName, String suffix) {
2958 // application protocol check
2959 if (bundleName.contains("://")) {
2960 return null;
2961 } else {
2962 return toResourceName(bundleName, suffix);
2963 }
2964 }
2965 }
2966
2967 private static class SingleFormatControl extends Control {
2968 private static final Control PROPERTIES_ONLY
2969 = new SingleFormatControl(FORMAT_PROPERTIES);
2970
2971 private static final Control CLASS_ONLY
2972 = new SingleFormatControl(FORMAT_CLASS);
2973
2974 private final List<String> formats;
2975
2976 protected SingleFormatControl(List<String> formats) {
2977 this.formats = formats;
2978 }
2979
2980 public List<String> getFormats(String baseName) {
2981 if (baseName == null) {
2982 throw new NullPointerException();
2983 }
2984 return formats;
2985 }
2986 }
2987
2988 private static final class NoFallbackControl extends SingleFormatControl {
2989 private static final Control NO_FALLBACK
2990 = new NoFallbackControl(FORMAT_DEFAULT);
2991
2992 private static final Control PROPERTIES_ONLY_NO_FALLBACK
2993 = new NoFallbackControl(FORMAT_PROPERTIES);
2994
2995 private static final Control CLASS_ONLY_NO_FALLBACK
2996 = new NoFallbackControl(FORMAT_CLASS);
2997
2998 protected NoFallbackControl(List<String> formats) {
2999 super(formats);
3000 }
3001
3002 public Locale getFallbackLocale(String baseName, Locale locale) {
3003 if (baseName == null || locale == null) {
3004 throw new NullPointerException();
3005 }
3006 return null;
3007 }
3008 }
3009 }
3010