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