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