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