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