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