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