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