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