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