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.
 976      *
 977      * @param baseName the base name of the resource bundle,
 978      *                 a fully qualified class name
 979      * @param targetLocale the locale for which a resource bundle is desired
 980      * @param module   the module for which the resource bundle is searched
 981      * @throws NullPointerException
 982      *         if {@code baseName}, {@code targetLocale}, or {@code module} is
 983      *         {@code null}
 984      * @throws SecurityException
 985      *         if a security manager exists and the caller is not the specified
 986      *         module and doesn't have {@code RuntimePermission("getClassLoader")}
 987      * @throws MissingResourceException
 988      *         if no resource bundle for the specified base name and locale can
 989      *         be found in the specified {@code module}
 990      * @return a resource bundle for the given base name and locale in the module
 991      * @since 9
 992      */
 993     @CallerSensitive
 994     public static ResourceBundle getBundle(String baseName, Locale targetLocale, Module module) {
 995         return getBundleFromModule(Reflection.getCallerClass(), module, baseName, targetLocale,
 996                                    getDefaultControl(module, baseName));
 997     }
 998 
 999     /**
1000      * Returns a resource bundle using the specified base name, target
1001      * locale and control, and the caller's class loader. Calling this
1002      * method is equivalent to calling
1003      * <pre>
1004      * getBundle(baseName, targetLocale, this.getClass().getClassLoader(),
1005      *           control),
1006      * </pre>
1007      * except that <code>getClassLoader()</code> is run with the security
1008      * privileges of <code>ResourceBundle</code>.  See {@link
1009      * #getBundle(String, Locale, ClassLoader, Control) getBundle} for the
1010      * complete description of the resource bundle loading process with a
1011      * <code>ResourceBundle.Control</code>.
1012      *
1013      * @param baseName
1014      *        the base name of the resource bundle, a fully qualified
1015      *        class name
1016      * @param targetLocale
1017      *        the locale for which a resource bundle is desired
1018      * @param control
1019      *        the control which gives information for the resource
1020      *        bundle loading process
1021      * @return a resource bundle for the given base name and a
1022      *         <code>Locale</code> in <code>locales</code>
1023      * @throws NullPointerException
1024      *         if <code>baseName</code>, <code>locales</code> or
1025      *         <code>control</code> is <code>null</code>
1026      * @throws MissingResourceException
1027      *         if no resource bundle for the specified base name in any
1028      *         of the <code>locales</code> can be found.
1029      * @throws IllegalArgumentException
1030      *         if the given <code>control</code> doesn't perform properly
1031      *         (e.g., <code>control.getCandidateLocales</code> returns null.)
1032      *         Note that validation of <code>control</code> is performed as
1033      *         needed.
1034      * @throws UnsupportedOperationException
1035      *         if this method is called in a named module
1036      * @since 1.6
1037      */
1038     @CallerSensitive
1039     public static final ResourceBundle getBundle(String baseName, Locale targetLocale,
1040                                                  Control control) {
1041         Class<?> caller = Reflection.getCallerClass();
1042         checkNamedModule(caller);
1043         return getBundleImpl(baseName, targetLocale, caller, control);
1044     }
1045 
1046     /**
1047      * Gets a resource bundle using the specified base name, locale, and class
1048      * loader.
1049      *
1050      * <p>This method behaves the same as calling
1051      * {@link #getBundle(String, Locale, ClassLoader, Control)} passing a
1052      * default instance of {@link Control} unless another {@link Control} is
1053      * provided with the {@link ResourceBundleControlProvider} SPI. Refer to the
1054      * description of <a href="#modify_default_behavior">modifying the default
1055      * behavior</a>.
1056      *
1057      * <p><a name="default_behavior">The following describes the default
1058      * behavior</a>.
1059      *
1060      * <p>
1061      * Resource bundles in a named module are private to that module.  If
1062      * the caller is in a named module, this method will find resource bundles
1063      * from the service providers of {@link java.util.spi.ResourceBundleProvider}
1064      * and also find resource bundles that are in the caller's module or
1065      * that are visible to the given class loader.
1066      * If the caller is in a named module and the given {@code loader} is
1067      * different than the caller's class loader, or if the caller is not in
1068      * a named module, this method will not find resource bundles from named
1069      * modules.
1070      *
1071      * <p><code>getBundle</code> uses the base name, the specified locale, and
1072      * the default locale (obtained from {@link java.util.Locale#getDefault()
1073      * Locale.getDefault}) to generate a sequence of <a
1074      * name="candidates"><em>candidate bundle names</em></a>.  If the specified
1075      * locale's language, script, country, and variant are all empty strings,
1076      * then the base name is the only candidate bundle name.  Otherwise, a list
1077      * of candidate locales is generated from the attribute values of the
1078      * specified locale (language, script, country and variant) and appended to
1079      * the base name.  Typically, this will look like the following:
1080      *
1081      * <pre>
1082      *     baseName + "_" + language + "_" + script + "_" + country + "_" + variant
1083      *     baseName + "_" + language + "_" + script + "_" + country
1084      *     baseName + "_" + language + "_" + script
1085      *     baseName + "_" + language + "_" + country + "_" + variant
1086      *     baseName + "_" + language + "_" + country
1087      *     baseName + "_" + language
1088      * </pre>
1089      *
1090      * <p>Candidate bundle names where the final component is an empty string
1091      * are omitted, along with the underscore.  For example, if country is an
1092      * empty string, the second and the fifth candidate bundle names above
1093      * would be omitted.  Also, if script is an empty string, the candidate names
1094      * including script are omitted.  For example, a locale with language "de"
1095      * and variant "JAVA" will produce candidate names with base name
1096      * "MyResource" below.
1097      *
1098      * <pre>
1099      *     MyResource_de__JAVA
1100      *     MyResource_de
1101      * </pre>
1102      *
1103      * In the case that the variant contains one or more underscores ('_'), a
1104      * sequence of bundle names generated by truncating the last underscore and
1105      * the part following it is inserted after a candidate bundle name with the
1106      * original variant.  For example, for a locale with language "en", script
1107      * "Latn, country "US" and variant "WINDOWS_VISTA", and bundle base name
1108      * "MyResource", the list of candidate bundle names below is generated:
1109      *
1110      * <pre>
1111      * MyResource_en_Latn_US_WINDOWS_VISTA
1112      * MyResource_en_Latn_US_WINDOWS
1113      * MyResource_en_Latn_US
1114      * MyResource_en_Latn
1115      * MyResource_en_US_WINDOWS_VISTA
1116      * MyResource_en_US_WINDOWS
1117      * MyResource_en_US
1118      * MyResource_en
1119      * </pre>
1120      *
1121      * <blockquote><b>Note:</b> For some <code>Locale</code>s, the list of
1122      * candidate bundle names contains extra names, or the order of bundle names
1123      * is slightly modified.  See the description of the default implementation
1124      * of {@link Control#getCandidateLocales(String, Locale)
1125      * getCandidateLocales} for details.</blockquote>
1126      *
1127      * <p><code>getBundle</code> then iterates over the candidate bundle names
1128      * to find the first one for which it can <em>instantiate</em> an actual
1129      * resource bundle. It uses the default controls' {@link Control#getFormats
1130      * getFormats} method, which generates two bundle names for each generated
1131      * name, the first a class name and the second a properties file name. For
1132      * each candidate bundle name, it attempts to create a resource bundle:
1133      *
1134      * <ul><li>First, it attempts to load a class using the generated class name.
1135      * If such a class can be found and loaded using the specified class
1136      * loader, is assignment compatible with ResourceBundle, is accessible from
1137      * ResourceBundle, and can be instantiated, <code>getBundle</code> creates a
1138      * new instance of this class and uses it as the <em>result resource
1139      * bundle</em>.
1140      *
1141      * <li>Otherwise, <code>getBundle</code> attempts to locate a property
1142      * resource file using the generated properties file name.  It generates a
1143      * path name from the candidate bundle name by replacing all "." characters
1144      * with "/" and appending the string ".properties".  It attempts to find a
1145      * "resource" with this name using {@link
1146      * java.lang.ClassLoader#getResource(java.lang.String)
1147      * ClassLoader.getResource}.  (Note that a "resource" in the sense of
1148      * <code>getResource</code> has nothing to do with the contents of a
1149      * resource bundle, it is just a container of data, such as a file.)  If it
1150      * finds a "resource", it attempts to create a new {@link
1151      * PropertyResourceBundle} instance from its contents.  If successful, this
1152      * instance becomes the <em>result resource bundle</em>.  </ul>
1153      *
1154      * <p>This continues until a result resource bundle is instantiated or the
1155      * list of candidate bundle names is exhausted.  If no matching resource
1156      * bundle is found, the default control's {@link Control#getFallbackLocale
1157      * getFallbackLocale} method is called, which returns the current default
1158      * locale.  A new sequence of candidate locale names is generated using this
1159      * locale and searched again, as above.
1160      *
1161      * <p>If still no result bundle is found, the base name alone is looked up. If
1162      * this still fails, a <code>MissingResourceException</code> is thrown.
1163      *
1164      * <p><a name="parent_chain"> Once a result resource bundle has been found,
1165      * its <em>parent chain</em> is instantiated</a>.  If the result bundle already
1166      * has a parent (perhaps because it was returned from a cache) the chain is
1167      * complete.
1168      *
1169      * <p>Otherwise, <code>getBundle</code> examines the remainder of the
1170      * candidate locale list that was used during the pass that generated the
1171      * result resource bundle.  (As before, candidate bundle names where the
1172      * final component is an empty string are omitted.)  When it comes to the
1173      * end of the candidate list, it tries the plain bundle name.  With each of the
1174      * candidate bundle names it attempts to instantiate a resource bundle (first
1175      * looking for a class and then a properties file, as described above).
1176      *
1177      * <p>Whenever it succeeds, it calls the previously instantiated resource
1178      * bundle's {@link #setParent(java.util.ResourceBundle) setParent} method
1179      * with the new resource bundle.  This continues until the list of names
1180      * is exhausted or the current bundle already has a non-null parent.
1181      *
1182      * <p>Once the parent chain is complete, the bundle is returned.
1183      *
1184      * <p><b>Note:</b> <code>getBundle</code> caches instantiated resource
1185      * bundles and might return the same resource bundle instance multiple times.
1186      *
1187      * <p><b>Note:</b>The <code>baseName</code> argument should be a fully
1188      * qualified class name. However, for compatibility with earlier versions,
1189      * Sun's Java SE Runtime Environments do not verify this, and so it is
1190      * possible to access <code>PropertyResourceBundle</code>s by specifying a
1191      * path name (using "/") instead of a fully qualified class name (using
1192      * ".").
1193      *
1194      * <p><a name="default_behavior_example">
1195      * <strong>Example:</strong></a>
1196      * <p>
1197      * The following class and property files are provided:
1198      * <pre>
1199      *     MyResources.class
1200      *     MyResources.properties
1201      *     MyResources_fr.properties
1202      *     MyResources_fr_CH.class
1203      *     MyResources_fr_CH.properties
1204      *     MyResources_en.properties
1205      *     MyResources_es_ES.class
1206      * </pre>
1207      *
1208      * The contents of all files are valid (that is, public non-abstract
1209      * subclasses of <code>ResourceBundle</code> for the ".class" files,
1210      * syntactically correct ".properties" files).  The default locale is
1211      * <code>Locale("en", "GB")</code>.
1212      *
1213      * <p>Calling <code>getBundle</code> with the locale arguments below will
1214      * instantiate resource bundles as follows:
1215      *
1216      * <table summary="getBundle() locale to resource bundle mapping">
1217      * <tr><td>Locale("fr", "CH")</td><td>MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class</td></tr>
1218      * <tr><td>Locale("fr", "FR")</td><td>MyResources_fr.properties, parent MyResources.class</td></tr>
1219      * <tr><td>Locale("de", "DE")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
1220      * <tr><td>Locale("en", "US")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
1221      * <tr><td>Locale("es", "ES")</td><td>MyResources_es_ES.class, parent MyResources.class</td></tr>
1222      * </table>
1223      *
1224      * <p>The file MyResources_fr_CH.properties is never used because it is
1225      * hidden by the MyResources_fr_CH.class. Likewise, MyResources.properties
1226      * is also hidden by MyResources.class.
1227      *
1228      * @apiNote If the caller module is a named module and the given
1229      * {@code loader} is the caller module's class loader, this method is
1230      * equivalent to {@code getBundle(baseName, locale)}; otherwise, it will not
1231      * find resource bundles from named modules.
1232      * Use {@link #getBundle(String, Locale, Module)} to load resource bundles
1233      * on behalf on a specific module instead.
1234      *
1235      * @param baseName the base name of the resource bundle, a fully qualified class name
1236      * @param locale the locale for which a resource bundle is desired
1237      * @param loader the class loader from which to load the resource bundle
1238      * @return a resource bundle for the given base name and locale
1239      * @exception java.lang.NullPointerException
1240      *        if <code>baseName</code>, <code>locale</code>, or <code>loader</code> is <code>null</code>
1241      * @exception MissingResourceException
1242      *        if no resource bundle for the specified base name can be found
1243      * @since 1.2
1244      */
1245     @CallerSensitive
1246     public static ResourceBundle getBundle(String baseName, Locale locale,
1247                                            ClassLoader loader)
1248     {
1249         if (loader == null) {
1250             throw new NullPointerException();
1251         }
1252         Class<?> caller = Reflection.getCallerClass();
1253         return getBundleImpl(baseName, locale, caller, loader, getDefaultControl(caller, baseName));
1254     }
1255 
1256     /**
1257      * Returns a resource bundle using the specified base name, target
1258      * locale, class loader and control. Unlike the {@linkplain
1259      * #getBundle(String, Locale, ClassLoader) <code>getBundle</code>
1260      * factory methods with no <code>control</code> argument}, the given
1261      * <code>control</code> specifies how to locate and instantiate resource
1262      * bundles. Conceptually, the bundle loading process with the given
1263      * <code>control</code> is performed in the following steps.
1264      *
1265      * <ol>
1266      * <li>This factory method looks up the resource bundle in the cache for
1267      * the specified <code>baseName</code>, <code>targetLocale</code> and
1268      * <code>loader</code>.  If the requested resource bundle instance is
1269      * found in the cache and the time-to-live periods of the instance and
1270      * all of its parent instances have not expired, the instance is returned
1271      * to the caller. Otherwise, this factory method proceeds with the
1272      * loading process below.</li>
1273      *
1274      * <li>The {@link ResourceBundle.Control#getFormats(String)
1275      * control.getFormats} method is called to get resource bundle formats
1276      * to produce bundle or resource names. The strings
1277      * <code>"java.class"</code> and <code>"java.properties"</code>
1278      * designate class-based and {@linkplain PropertyResourceBundle
1279      * property}-based resource bundles, respectively. Other strings
1280      * starting with <code>"java."</code> are reserved for future extensions
1281      * and must not be used for application-defined formats. Other strings
1282      * designate application-defined formats.</li>
1283      *
1284      * <li>The {@link ResourceBundle.Control#getCandidateLocales(String,
1285      * Locale) control.getCandidateLocales} method is called with the target
1286      * locale to get a list of <em>candidate <code>Locale</code>s</em> for
1287      * which resource bundles are searched.</li>
1288      *
1289      * <li>The {@link ResourceBundle.Control#newBundle(String, Locale,
1290      * String, ClassLoader, boolean) control.newBundle} method is called to
1291      * instantiate a <code>ResourceBundle</code> for the base bundle name, a
1292      * candidate locale, and a format. (Refer to the note on the cache
1293      * lookup below.) This step is iterated over all combinations of the
1294      * candidate locales and formats until the <code>newBundle</code> method
1295      * returns a <code>ResourceBundle</code> instance or the iteration has
1296      * used up all the combinations. For example, if the candidate locales
1297      * are <code>Locale("de", "DE")</code>, <code>Locale("de")</code> and
1298      * <code>Locale("")</code> and the formats are <code>"java.class"</code>
1299      * and <code>"java.properties"</code>, then the following is the
1300      * sequence of locale-format combinations to be used to call
1301      * <code>control.newBundle</code>.
1302      *
1303      * <table style="width: 50%; text-align: left; margin-left: 40px;"
1304      *  border="0" cellpadding="2" cellspacing="2" summary="locale-format combinations for newBundle">
1305      * <tbody>
1306      * <tr>
1307      * <td
1308      * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;"><code>Locale</code><br>
1309      * </td>
1310      * <td
1311      * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;"><code>format</code><br>
1312      * </td>
1313      * </tr>
1314      * <tr>
1315      * <td style="vertical-align: top; width: 50%;"><code>Locale("de", "DE")</code><br>
1316      * </td>
1317      * <td style="vertical-align: top; width: 50%;"><code>java.class</code><br>
1318      * </td>
1319      * </tr>
1320      * <tr>
1321      * <td style="vertical-align: top; width: 50%;"><code>Locale("de", "DE")</code></td>
1322      * <td style="vertical-align: top; width: 50%;"><code>java.properties</code><br>
1323      * </td>
1324      * </tr>
1325      * <tr>
1326      * <td style="vertical-align: top; width: 50%;"><code>Locale("de")</code></td>
1327      * <td style="vertical-align: top; width: 50%;"><code>java.class</code></td>
1328      * </tr>
1329      * <tr>
1330      * <td style="vertical-align: top; width: 50%;"><code>Locale("de")</code></td>
1331      * <td style="vertical-align: top; width: 50%;"><code>java.properties</code></td>
1332      * </tr>
1333      * <tr>
1334      * <td style="vertical-align: top; width: 50%;"><code>Locale("")</code><br>
1335      * </td>
1336      * <td style="vertical-align: top; width: 50%;"><code>java.class</code></td>
1337      * </tr>
1338      * <tr>
1339      * <td style="vertical-align: top; width: 50%;"><code>Locale("")</code></td>
1340      * <td style="vertical-align: top; width: 50%;"><code>java.properties</code></td>
1341      * </tr>
1342      * </tbody>
1343      * </table>
1344      * </li>
1345      *
1346      * <li>If the previous step has found no resource bundle, proceed to
1347      * Step 6. If a bundle has been found that is a base bundle (a bundle
1348      * for <code>Locale("")</code>), and the candidate locale list only contained
1349      * <code>Locale("")</code>, return the bundle to the caller. If a bundle
1350      * has been found that is a base bundle, but the candidate locale list
1351      * contained locales other than Locale(""), put the bundle on hold and
1352      * proceed to Step 6. If a bundle has been found that is not a base
1353      * bundle, proceed to Step 7.</li>
1354      *
1355      * <li>The {@link ResourceBundle.Control#getFallbackLocale(String,
1356      * Locale) control.getFallbackLocale} method is called to get a fallback
1357      * locale (alternative to the current target locale) to try further
1358      * finding a resource bundle. If the method returns a non-null locale,
1359      * it becomes the next target locale and the loading process starts over
1360      * from Step 3. Otherwise, if a base bundle was found and put on hold in
1361      * a previous Step 5, it is returned to the caller now. Otherwise, a
1362      * MissingResourceException is thrown.</li>
1363      *
1364      * <li>At this point, we have found a resource bundle that's not the
1365      * base bundle. If this bundle set its parent during its instantiation,
1366      * it is returned to the caller. Otherwise, its <a
1367      * href="./ResourceBundle.html#parent_chain">parent chain</a> is
1368      * instantiated based on the list of candidate locales from which it was
1369      * found. Finally, the bundle is returned to the caller.</li>
1370      * </ol>
1371      *
1372      * <p>During the resource bundle loading process above, this factory
1373      * method looks up the cache before calling the {@link
1374      * Control#newBundle(String, Locale, String, ClassLoader, boolean)
1375      * control.newBundle} method.  If the time-to-live period of the
1376      * resource bundle found in the cache has expired, the factory method
1377      * calls the {@link ResourceBundle.Control#needsReload(String, Locale,
1378      * String, ClassLoader, ResourceBundle, long) control.needsReload}
1379      * method to determine whether the resource bundle needs to be reloaded.
1380      * If reloading is required, the factory method calls
1381      * <code>control.newBundle</code> to reload the resource bundle.  If
1382      * <code>control.newBundle</code> returns <code>null</code>, the factory
1383      * method puts a dummy resource bundle in the cache as a mark of
1384      * nonexistent resource bundles in order to avoid lookup overhead for
1385      * subsequent requests. Such dummy resource bundles are under the same
1386      * expiration control as specified by <code>control</code>.
1387      *
1388      * <p>All resource bundles loaded are cached by default. Refer to
1389      * {@link Control#getTimeToLive(String,Locale)
1390      * control.getTimeToLive} for details.
1391      *
1392      * <p>The following is an example of the bundle loading process with the
1393      * default <code>ResourceBundle.Control</code> implementation.
1394      *
1395      * <p>Conditions:
1396      * <ul>
1397      * <li>Base bundle name: <code>foo.bar.Messages</code>
1398      * <li>Requested <code>Locale</code>: {@link Locale#ITALY}</li>
1399      * <li>Default <code>Locale</code>: {@link Locale#FRENCH}</li>
1400      * <li>Available resource bundles:
1401      * <code>foo/bar/Messages_fr.properties</code> and
1402      * <code>foo/bar/Messages.properties</code></li>
1403      * </ul>
1404      *
1405      * <p>First, <code>getBundle</code> tries loading a resource bundle in
1406      * the following sequence.
1407      *
1408      * <ul>
1409      * <li>class <code>foo.bar.Messages_it_IT</code>
1410      * <li>file <code>foo/bar/Messages_it_IT.properties</code>
1411      * <li>class <code>foo.bar.Messages_it</code></li>
1412      * <li>file <code>foo/bar/Messages_it.properties</code></li>
1413      * <li>class <code>foo.bar.Messages</code></li>
1414      * <li>file <code>foo/bar/Messages.properties</code></li>
1415      * </ul>
1416      *
1417      * <p>At this point, <code>getBundle</code> finds
1418      * <code>foo/bar/Messages.properties</code>, which is put on hold
1419      * because it's the base bundle.  <code>getBundle</code> calls {@link
1420      * Control#getFallbackLocale(String, Locale)
1421      * control.getFallbackLocale("foo.bar.Messages", Locale.ITALY)} which
1422      * returns <code>Locale.FRENCH</code>. Next, <code>getBundle</code>
1423      * tries loading a bundle in the following sequence.
1424      *
1425      * <ul>
1426      * <li>class <code>foo.bar.Messages_fr</code></li>
1427      * <li>file <code>foo/bar/Messages_fr.properties</code></li>
1428      * <li>class <code>foo.bar.Messages</code></li>
1429      * <li>file <code>foo/bar/Messages.properties</code></li>
1430      * </ul>
1431      *
1432      * <p><code>getBundle</code> finds
1433      * <code>foo/bar/Messages_fr.properties</code> and creates a
1434      * <code>ResourceBundle</code> instance. Then, <code>getBundle</code>
1435      * sets up its parent chain from the list of the candidate locales.  Only
1436      * <code>foo/bar/Messages.properties</code> is found in the list and
1437      * <code>getBundle</code> creates a <code>ResourceBundle</code> instance
1438      * that becomes the parent of the instance for
1439      * <code>foo/bar/Messages_fr.properties</code>.
1440      *
1441      * @param baseName
1442      *        the base name of the resource bundle, a fully qualified
1443      *        class name
1444      * @param targetLocale
1445      *        the locale for which a resource bundle is desired
1446      * @param loader
1447      *        the class loader from which to load the resource bundle
1448      * @param control
1449      *        the control which gives information for the resource
1450      *        bundle loading process
1451      * @return a resource bundle for the given base name and locale
1452      * @throws NullPointerException
1453      *         if <code>baseName</code>, <code>targetLocale</code>,
1454      *         <code>loader</code>, or <code>control</code> is
1455      *         <code>null</code>
1456      * @throws MissingResourceException
1457      *         if no resource bundle for the specified base name can be found
1458      * @throws IllegalArgumentException
1459      *         if the given <code>control</code> doesn't perform properly
1460      *         (e.g., <code>control.getCandidateLocales</code> returns null.)
1461      *         Note that validation of <code>control</code> is performed as
1462      *         needed.
1463      * @throws UnsupportedOperationException
1464      *         if this method is called in a named module
1465      * @since 1.6
1466      */
1467     @CallerSensitive
1468     public static ResourceBundle getBundle(String baseName, Locale targetLocale,
1469                                            ClassLoader loader, Control control) {
1470         if (loader == null || control == null) {
1471             throw new NullPointerException();
1472         }
1473         Class<?> caller = Reflection.getCallerClass();
1474         checkNamedModule(caller);
1475         return getBundleImpl(baseName, targetLocale, caller, loader, control);
1476     }
1477 
1478     private static Control getDefaultControl(Class<?> caller, String baseName) {
1479         return getDefaultControl(caller.getModule(), baseName);
1480     }
1481     
1482     private static Control getDefaultControl(Module targetModule, String baseName) {
1483         return targetModule.isNamed() ?
1484             Control.INSTANCE :
1485             ResourceBundleControlProviderHolder.getControl(baseName);
1486     }
1487 
1488     private static class ResourceBundleControlProviderHolder {
1489         private static final PrivilegedAction<List<ResourceBundleControlProvider>> pa =
1490             () -> {
1491                 return Collections.unmodifiableList(
1492                     ServiceLoader.load(ResourceBundleControlProvider.class,
1493                                        ClassLoader.getSystemClassLoader()).stream()
1494                         .map(ServiceLoader.Provider::get)
1495                         .collect(Collectors.toList()));
1496             };
1497 
1498         private static final List<ResourceBundleControlProvider> CONTROL_PROVIDERS =
1499             AccessController.doPrivileged(pa);
1500 
1501         private static Control getControl(String baseName) {
1502             return CONTROL_PROVIDERS.isEmpty() ?
1503                 Control.INSTANCE :
1504                 CONTROL_PROVIDERS.stream()
1505                     .flatMap(provider -> Stream.ofNullable(provider.getControl(baseName)))
1506                     .findFirst()
1507                     .orElse(Control.INSTANCE);
1508         }
1509     }
1510 
1511     private static void checkNamedModule(Class<?> caller) {
1512         if (caller.getModule().isNamed()) {
1513             throw new UnsupportedOperationException(
1514                     "ResourceBundle.Control not supported in named modules");
1515         }
1516     }
1517 
1518     private static ResourceBundle getBundleImpl(String baseName,
1519                                                 Locale locale,
1520                                                 Class<?> caller,
1521                                                 Control control) {
1522         return getBundleImpl(baseName, locale, caller, caller.getClassLoader(), control);
1523     }
1524 
1525     /**
1526      * This method will find resource bundles using the legacy mechanism
1527      * if the caller is unnamed module or the given class loader is
1528      * not the class loader of the caller module getting the resource
1529      * bundle, i.e. find the class that is visible to the class loader
1530      * and properties from unnamed module.
1531      *
1532      * The module-aware resource bundle lookup mechanism will load
1533      * the service providers using the service loader mechanism
1534      * as well as properties local in the caller module.
1535      */
1536     private static ResourceBundle getBundleImpl(String baseName,
1537                                                 Locale locale,
1538                                                 Class<?> caller,
1539                                                 ClassLoader loader,
1540                                                 Control control) {
1541         if (caller == null) {
1542             throw new InternalError("null caller");
1543         }
1544         Module callerModule = caller.getModule();
1545 
1546         // get resource bundles for a named module only if loader is the module's class loader
1547         if (callerModule.isNamed() && loader == getLoader(callerModule)) {
1548             return getBundleImpl(callerModule, callerModule, baseName, locale, control);
1549         }
1550 
1551         // find resource bundles from unnamed module of given class loader
1552         // Java agent can add to the bootclasspath e.g. via
1553         // java.lang.instrument.Instrumentation and load classes in unnamed module.
1554         // It may call RB::getBundle that will end up here with loader == null.
1555         Module unnamedModule = loader != null
1556             ? loader.getUnnamedModule()
1557             : BootLoader.getUnnamedModule();
1558 
1559         return getBundleImpl(callerModule, unnamedModule, baseName, locale, control);
1560     }
1561 
1562     private static ResourceBundle getBundleFromModule(Class<?> caller,
1563                                                       Module module,
1564                                                       String baseName,
1565                                                       Locale locale,
1566                                                       Control control) {
1567         Objects.requireNonNull(module);
1568         Module callerModule = caller.getModule();
1569         if (callerModule != module) {
1570             SecurityManager sm = System.getSecurityManager();
1571             if (sm != null) {
1572                 sm.checkPermission(GET_CLASSLOADER_PERMISSION);
1573             }
1574         }
1575         return getBundleImpl(callerModule, module, baseName, locale, control);
1576     }
1577 
1578     private static ResourceBundle getBundleImpl(Module callerModule,
1579                                                 Module module,
1580                                                 String baseName,
1581                                                 Locale locale,
1582                                                 Control control) {
1583         if (locale == null || control == null) {
1584             throw new NullPointerException();
1585         }
1586 
1587         // We create a CacheKey here for use by this call. The base name
1588         // and modules will never change during the bundle loading
1589         // process. We have to make sure that the locale is set before
1590         // using it as a cache key.
1591         CacheKey cacheKey = new CacheKey(baseName, locale, module, callerModule);
1592         ResourceBundle bundle = null;
1593 
1594         // Quick lookup of the cache.
1595         BundleReference bundleRef = cacheList.get(cacheKey);
1596         if (bundleRef != null) {
1597             bundle = bundleRef.get();
1598             bundleRef = null;
1599         }
1600 
1601         // If this bundle and all of its parents are valid (not expired),
1602         // then return this bundle. If any of the bundles is expired, we
1603         // don't call control.needsReload here but instead drop into the
1604         // complete loading process below.
1605         if (isValidBundle(bundle) && hasValidParentChain(bundle)) {
1606             return bundle;
1607         }
1608 
1609         // No valid bundle was found in the cache, so we need to load the
1610         // resource bundle and its parents.
1611 
1612         boolean isKnownControl = (control == Control.INSTANCE) ||
1613                                    (control instanceof SingleFormatControl);
1614         List<String> formats = control.getFormats(baseName);
1615         if (!isKnownControl && !checkList(formats)) {
1616             throw new IllegalArgumentException("Invalid Control: getFormats");
1617         }
1618 
1619         ResourceBundle baseBundle = null;
1620         for (Locale targetLocale = locale;
1621              targetLocale != null;
1622              targetLocale = control.getFallbackLocale(baseName, targetLocale)) {
1623             List<Locale> candidateLocales = control.getCandidateLocales(baseName, targetLocale);
1624             if (!isKnownControl && !checkList(candidateLocales)) {
1625                 throw new IllegalArgumentException("Invalid Control: getCandidateLocales");
1626             }
1627 
1628             bundle = findBundle(callerModule, module, cacheKey,
1629                                 candidateLocales, formats, 0, control, baseBundle);
1630 
1631             // If the loaded bundle is the base bundle and exactly for the
1632             // requested locale or the only candidate locale, then take the
1633             // bundle as the resulting one. If the loaded bundle is the base
1634             // bundle, it's put on hold until we finish processing all
1635             // fallback locales.
1636             if (isValidBundle(bundle)) {
1637                 boolean isBaseBundle = Locale.ROOT.equals(bundle.locale);
1638                 if (!isBaseBundle || bundle.locale.equals(locale)
1639                     || (candidateLocales.size() == 1
1640                         && bundle.locale.equals(candidateLocales.get(0)))) {
1641                     break;
1642                 }
1643 
1644                 // If the base bundle has been loaded, keep the reference in
1645                 // baseBundle so that we can avoid any redundant loading in case
1646                 // the control specify not to cache bundles.
1647                 if (isBaseBundle && baseBundle == null) {
1648                     baseBundle = bundle;
1649                 }
1650             }
1651         }
1652 
1653         if (bundle == null) {
1654             if (baseBundle == null) {
1655                 throwMissingResourceException(baseName, locale, cacheKey.getCause());
1656             }
1657             bundle = baseBundle;
1658         }
1659 
1660         // keep callerModule and module reachable for as long as we are operating
1661         // with WeakReference(s) to them (in CacheKey)...
1662         Reference.reachabilityFence(callerModule);
1663         Reference.reachabilityFence(module);
1664 
1665         return bundle;
1666     }
1667 
1668     /**
1669      * Checks if the given <code>List</code> is not null, not empty,
1670      * not having null in its elements.
1671      */
1672     private static boolean checkList(List<?> a) {
1673         boolean valid = (a != null && !a.isEmpty());
1674         if (valid) {
1675             int size = a.size();
1676             for (int i = 0; valid && i < size; i++) {
1677                 valid = (a.get(i) != null);
1678             }
1679         }
1680         return valid;
1681     }
1682 
1683     private static ResourceBundle findBundle(Module callerModule,
1684                                              Module module,
1685                                              CacheKey cacheKey,
1686                                              List<Locale> candidateLocales,
1687                                              List<String> formats,
1688                                              int index,
1689                                              Control control,
1690                                              ResourceBundle baseBundle) {
1691         Locale targetLocale = candidateLocales.get(index);
1692         ResourceBundle parent = null;
1693         if (index != candidateLocales.size() - 1) {
1694             parent = findBundle(callerModule, module, cacheKey,
1695                                 candidateLocales, formats, index + 1,
1696                                 control, baseBundle);
1697         } else if (baseBundle != null && Locale.ROOT.equals(targetLocale)) {
1698             return baseBundle;
1699         }
1700 
1701         // Before we do the real loading work, see whether we need to
1702         // do some housekeeping: If references to modules or
1703         // resource bundles have been nulled out, remove all related
1704         // information from the cache.
1705         Object ref;
1706         while ((ref = referenceQueue.poll()) != null) {
1707             cacheList.remove(((CacheKeyReference)ref).getCacheKey());
1708         }
1709 
1710         // flag indicating the resource bundle has expired in the cache
1711         boolean expiredBundle = false;
1712 
1713         // First, look up the cache to see if it's in the cache, without
1714         // attempting to load bundle.
1715         cacheKey.setLocale(targetLocale);
1716         ResourceBundle bundle = findBundleInCache(cacheKey, control);
1717         if (isValidBundle(bundle)) {
1718             expiredBundle = bundle.expired;
1719             if (!expiredBundle) {
1720                 // If its parent is the one asked for by the candidate
1721                 // locales (the runtime lookup path), we can take the cached
1722                 // one. (If it's not identical, then we'd have to check the
1723                 // parent's parents to be consistent with what's been
1724                 // requested.)
1725                 if (bundle.parent == parent) {
1726                     return bundle;
1727                 }
1728                 // Otherwise, remove the cached one since we can't keep
1729                 // the same bundles having different parents.
1730                 BundleReference bundleRef = cacheList.get(cacheKey);
1731                 if (bundleRef != null && bundleRef.get() == bundle) {
1732                     cacheList.remove(cacheKey, bundleRef);
1733                 }
1734             }
1735         }
1736 
1737         if (bundle != NONEXISTENT_BUNDLE) {
1738             trace("findBundle: %d %s %s formats: %s%n", index, candidateLocales, cacheKey, formats);
1739             if (module.isNamed()) {
1740                 bundle = loadBundle(cacheKey, formats, control, module, callerModule);
1741             } else {
1742                 bundle = loadBundle(cacheKey, formats, control, expiredBundle);
1743             }
1744             if (bundle != null) {
1745                 if (bundle.parent == null) {
1746                     bundle.setParent(parent);
1747                 }
1748                 bundle.locale = targetLocale;
1749                 bundle = putBundleInCache(cacheKey, bundle, control);
1750                 return bundle;
1751             }
1752 
1753             // Put NONEXISTENT_BUNDLE in the cache as a mark that there's no bundle
1754             // instance for the locale.
1755             putBundleInCache(cacheKey, NONEXISTENT_BUNDLE, control);
1756         }
1757         return parent;
1758     }
1759 
1760     private static final String UNKNOWN_FORMAT = "";
1761 
1762 
1763     /*
1764      * Loads a ResourceBundle in named modules
1765      */
1766     private static ResourceBundle loadBundle(CacheKey cacheKey,
1767                                              List<String> formats,
1768                                              Control control,
1769                                              Module module,
1770                                              Module callerModule) {
1771         String baseName = cacheKey.getName();
1772         Locale targetLocale = cacheKey.getLocale();
1773 
1774         ResourceBundle bundle = null;
1775         if (cacheKey.hasProviders()) {
1776             if (callerModule == module) {
1777                 bundle = loadBundleFromProviders(baseName,
1778                                                  targetLocale,
1779                                                  cacheKey.getProviders(),
1780                                                  cacheKey);
1781             } else {
1782                 // load from provider if the caller module has access to the
1783                 // service type and also declares `uses`
1784                 ClassLoader loader = getLoader(module);
1785                 Class<ResourceBundleProvider> svc =
1786                     getResourceBundleProviderType(baseName, loader);
1787                 if (svc != null
1788                         && Reflection.verifyModuleAccess(callerModule, svc)
1789                         && callerModule.canUse(svc)) {
1790                     bundle = loadBundleFromProviders(baseName,
1791                                                      targetLocale,
1792                                                      cacheKey.getProviders(),
1793                                                      cacheKey);
1794                 }
1795             }
1796 
1797             if (bundle != null) {
1798                 cacheKey.setFormat(UNKNOWN_FORMAT);
1799             }
1800         }
1801 
1802         // If none of providers returned a bundle and the caller has no provider,
1803         // look up module-local bundles or from the class path
1804         if (bundle == null && !cacheKey.callerHasProvider()) {
1805             for (String format : formats) {
1806                 try {
1807                     switch (format) {
1808                     case "java.class":
1809                         bundle = ResourceBundleProviderHelper
1810                             .loadResourceBundle(callerModule, module, baseName, targetLocale);
1811 
1812                         break;
1813                     case "java.properties":
1814                         bundle = ResourceBundleProviderHelper
1815                             .loadPropertyResourceBundle(callerModule, module, baseName, targetLocale);
1816                         break;
1817                     default:
1818                         throw new InternalError("unexpected format: " + format);
1819                     }
1820 
1821                     if (bundle != null) {
1822                         cacheKey.setFormat(format);
1823                         break;
1824                     }
1825                 } catch (Exception e) {
1826                     cacheKey.setCause(e);
1827                 }
1828             }
1829         }
1830         return bundle;
1831     }
1832 
1833     /**
1834      * Returns a ServiceLoader that will find providers that are bound to
1835      * a given named module.
1836      */
1837     private static ServiceLoader<ResourceBundleProvider> getServiceLoader(Module module,
1838                                                                           String baseName)
1839     {
1840         if (!module.isNamed()) {
1841             return null;
1842         }
1843 
1844         ClassLoader loader = getLoader(module);
1845         Class<ResourceBundleProvider> service =
1846                 getResourceBundleProviderType(baseName, loader);
1847         if (service != null && Reflection.verifyModuleAccess(module, service)) {
1848             try {
1849                 // locate providers that are visible to the class loader
1850                 // ServiceConfigurationError will be thrown if the module
1851                 // does not declare `uses` the service type
1852                 return ServiceLoader.load(service, loader, module);
1853             } catch (ServiceConfigurationError e) {
1854                 // "uses" not declared
1855                 return null;
1856             }
1857         }
1858         return null;
1859     }
1860 
1861     /**
1862      * Returns the service type of the given baseName that is visible
1863      * to the given class loader
1864      */
1865     private static Class<ResourceBundleProvider>
1866             getResourceBundleProviderType(String baseName, ClassLoader loader)
1867     {
1868         // Look up <baseName> + "Provider"
1869         String providerName = baseName + "Provider";
1870         // Use the class loader of the getBundle caller so that the caller's
1871         // visibility of the provider type is checked.
1872         return AccessController.doPrivileged(
1873             new PrivilegedAction<>() {
1874                 @Override
1875                 public Class<ResourceBundleProvider> run() {
1876                     try {
1877                         Class<?> c = Class.forName(providerName, false, loader);
1878                         if (ResourceBundleProvider.class.isAssignableFrom(c)) {
1879                             @SuppressWarnings("unchecked")
1880                             Class<ResourceBundleProvider> s = (Class<ResourceBundleProvider>) c;
1881                             return s;
1882                         }
1883                     } catch (ClassNotFoundException e) {}
1884                     return null;
1885                 }
1886             });
1887     }
1888 
1889     /**
1890      * Loads ResourceBundle from service providers.
1891      */
1892     private static ResourceBundle loadBundleFromProviders(String baseName,
1893                                                           Locale locale,
1894                                                           ServiceLoader<ResourceBundleProvider> providers,
1895                                                           CacheKey cacheKey)
1896     {
1897         if (providers == null) return null;
1898 
1899         return AccessController.doPrivileged(
1900                 new PrivilegedAction<>() {
1901                     public ResourceBundle run() {
1902                         for (Iterator<ResourceBundleProvider> itr = providers.iterator(); itr.hasNext(); ) {
1903                             try {
1904                                 ResourceBundleProvider provider = itr.next();
1905                                 if (cacheKey != null && cacheKey.callerHasProvider == null
1906                                         && cacheKey.getModule() == provider.getClass().getModule()) {
1907                                     cacheKey.callerHasProvider = Boolean.TRUE;
1908                                 }
1909                                 ResourceBundle bundle = provider.getBundle(baseName, locale);
1910                                 trace("provider %s %s locale: %s bundle: %s%n", provider, baseName, locale, bundle);
1911                                 if (bundle != null) {
1912                                     return bundle;
1913                                 }
1914                             } catch (ServiceConfigurationError | SecurityException e) {
1915                                 if (cacheKey != null) {
1916                                     cacheKey.setCause(e);
1917                                 }
1918                             }
1919                         }
1920                         if (cacheKey != null && cacheKey.callerHasProvider == null) {
1921                             cacheKey.callerHasProvider = Boolean.FALSE;
1922                         }
1923                         return null;
1924                     }
1925                 });
1926 
1927     }
1928 
1929     /*
1930      * Legacy mechanism to load resource bundles
1931      */
1932     private static ResourceBundle loadBundle(CacheKey cacheKey,
1933                                              List<String> formats,
1934                                              Control control,
1935                                              boolean reload) {
1936 
1937         // Here we actually load the bundle in the order of formats
1938         // specified by the getFormats() value.
1939         Locale targetLocale = cacheKey.getLocale();
1940 
1941         Module module = cacheKey.getModule();
1942         if (module == null) {
1943             // should not happen
1944             throw new InternalError(
1945                 "Module for cache key: " + cacheKey + " has been GCed.");
1946         }
1947         ClassLoader loader = getLoaderForControl(module);
1948 
1949         ResourceBundle bundle = null;
1950         for (String format : formats) {
1951             try {
1952                 // ResourceBundle.Control.newBundle may be overridden
1953                 bundle = control.newBundle(cacheKey.getName(), targetLocale, format,
1954                                            loader, reload);
1955             } catch (LinkageError | Exception error) {
1956                 // We need to handle the LinkageError case due to
1957                 // inconsistent case-sensitivity in ClassLoader.
1958                 // See 6572242 for details.
1959                 cacheKey.setCause(error);
1960             }
1961             if (bundle != null) {
1962                 // Set the format in the cache key so that it can be
1963                 // used when calling needsReload later.
1964                 cacheKey.setFormat(format);
1965                 bundle.name = cacheKey.getName();
1966                 bundle.locale = targetLocale;
1967                 // Bundle provider might reuse instances. So we should make
1968                 // sure to clear the expired flag here.
1969                 bundle.expired = false;
1970                 break;
1971             }
1972         }
1973 
1974         return bundle;
1975     }
1976 
1977     private static boolean isValidBundle(ResourceBundle bundle) {
1978         return bundle != null && bundle != NONEXISTENT_BUNDLE;
1979     }
1980 
1981     /**
1982      * Determines whether any of resource bundles in the parent chain,
1983      * including the leaf, have expired.
1984      */
1985     private static boolean hasValidParentChain(ResourceBundle bundle) {
1986         long now = System.currentTimeMillis();
1987         while (bundle != null) {
1988             if (bundle.expired) {
1989                 return false;
1990             }
1991             CacheKey key = bundle.cacheKey;
1992             if (key != null) {
1993                 long expirationTime = key.expirationTime;
1994                 if (expirationTime >= 0 && expirationTime <= now) {
1995                     return false;
1996                 }
1997             }
1998             bundle = bundle.parent;
1999         }
2000         return true;
2001     }
2002 
2003     /**
2004      * Throw a MissingResourceException with proper message
2005      */
2006     private static void throwMissingResourceException(String baseName,
2007                                                       Locale locale,
2008                                                       Throwable cause) {
2009         // If the cause is a MissingResourceException, avoid creating
2010         // a long chain. (6355009)
2011         if (cause instanceof MissingResourceException) {
2012             cause = null;
2013         }
2014         throw new MissingResourceException("Can't find bundle for base name "
2015                                            + baseName + ", locale " + locale,
2016                                            baseName + "_" + locale, // className
2017                                            "",                      // key
2018                                            cause);
2019     }
2020 
2021     /**
2022      * Finds a bundle in the cache. Any expired bundles are marked as
2023      * `expired' and removed from the cache upon return.
2024      *
2025      * @param cacheKey the key to look up the cache
2026      * @param control the Control to be used for the expiration control
2027      * @return the cached bundle, or null if the bundle is not found in the
2028      * cache or its parent has expired. <code>bundle.expire</code> is true
2029      * upon return if the bundle in the cache has expired.
2030      */
2031     private static ResourceBundle findBundleInCache(CacheKey cacheKey,
2032                                                     Control control) {
2033         BundleReference bundleRef = cacheList.get(cacheKey);
2034         if (bundleRef == null) {
2035             return null;
2036         }
2037         ResourceBundle bundle = bundleRef.get();
2038         if (bundle == null) {
2039             return null;
2040         }
2041         ResourceBundle p = bundle.parent;
2042         assert p != NONEXISTENT_BUNDLE;
2043         // If the parent has expired, then this one must also expire. We
2044         // check only the immediate parent because the actual loading is
2045         // done from the root (base) to leaf (child) and the purpose of
2046         // checking is to propagate expiration towards the leaf. For
2047         // example, if the requested locale is ja_JP_JP and there are
2048         // bundles for all of the candidates in the cache, we have a list,
2049         //
2050         // base <- ja <- ja_JP <- ja_JP_JP
2051         //
2052         // If ja has expired, then it will reload ja and the list becomes a
2053         // tree.
2054         //
2055         // base <- ja (new)
2056         //  "   <- ja (expired) <- ja_JP <- ja_JP_JP
2057         //
2058         // When looking up ja_JP in the cache, it finds ja_JP in the cache
2059         // which references to the expired ja. Then, ja_JP is marked as
2060         // expired and removed from the cache. This will be propagated to
2061         // ja_JP_JP.
2062         //
2063         // Now, it's possible, for example, that while loading new ja_JP,
2064         // someone else has started loading the same bundle and finds the
2065         // base bundle has expired. Then, what we get from the first
2066         // getBundle call includes the expired base bundle. However, if
2067         // someone else didn't start its loading, we wouldn't know if the
2068         // base bundle has expired at the end of the loading process. The
2069         // expiration control doesn't guarantee that the returned bundle and
2070         // its parents haven't expired.
2071         //
2072         // We could check the entire parent chain to see if there's any in
2073         // the chain that has expired. But this process may never end. An
2074         // extreme case would be that getTimeToLive returns 0 and
2075         // needsReload always returns true.
2076         if (p != null && p.expired) {
2077             assert bundle != NONEXISTENT_BUNDLE;
2078             bundle.expired = true;
2079             bundle.cacheKey = null;
2080             cacheList.remove(cacheKey, bundleRef);
2081             bundle = null;
2082         } else {
2083             CacheKey key = bundleRef.getCacheKey();
2084             long expirationTime = key.expirationTime;
2085             if (!bundle.expired && expirationTime >= 0 &&
2086                 expirationTime <= System.currentTimeMillis()) {
2087                 // its TTL period has expired.
2088                 if (bundle != NONEXISTENT_BUNDLE) {
2089                     // Synchronize here to call needsReload to avoid
2090                     // redundant concurrent calls for the same bundle.
2091                     synchronized (bundle) {
2092                         expirationTime = key.expirationTime;
2093                         if (!bundle.expired && expirationTime >= 0 &&
2094                             expirationTime <= System.currentTimeMillis()) {
2095                             try {
2096                                 Module module = cacheKey.getModule();
2097                                 bundle.expired =
2098                                     module == null || // already GCed
2099                                     control.needsReload(key.getName(),
2100                                                         key.getLocale(),
2101                                                         key.getFormat(),
2102                                                         getLoaderForControl(module),
2103                                                         bundle,
2104                                                         key.loadTime);
2105                             } catch (Exception e) {
2106                                 cacheKey.setCause(e);
2107                             }
2108                             if (bundle.expired) {
2109                                 // If the bundle needs to be reloaded, then
2110                                 // remove the bundle from the cache, but
2111                                 // return the bundle with the expired flag
2112                                 // on.
2113                                 bundle.cacheKey = null;
2114                                 cacheList.remove(cacheKey, bundleRef);
2115                             } else {
2116                                 // Update the expiration control info. and reuse
2117                                 // the same bundle instance
2118                                 setExpirationTime(key, control);
2119                             }
2120                         }
2121                     }
2122                 } else {
2123                     // We just remove NONEXISTENT_BUNDLE from the cache.
2124                     cacheList.remove(cacheKey, bundleRef);
2125                     bundle = null;
2126                 }
2127             }
2128         }
2129         return bundle;
2130     }
2131 
2132     /**
2133      * Put a new bundle in the cache.
2134      *
2135      * @param cacheKey the key for the resource bundle
2136      * @param bundle the resource bundle to be put in the cache
2137      * @return the ResourceBundle for the cacheKey; if someone has put
2138      * the bundle before this call, the one found in the cache is
2139      * returned.
2140      */
2141     private static ResourceBundle putBundleInCache(CacheKey cacheKey,
2142                                                    ResourceBundle bundle,
2143                                                    Control control) {
2144         setExpirationTime(cacheKey, control);
2145         if (cacheKey.expirationTime != Control.TTL_DONT_CACHE) {
2146             CacheKey key = new CacheKey(cacheKey);
2147             BundleReference bundleRef = new BundleReference(bundle, referenceQueue, key);
2148             bundle.cacheKey = key;
2149 
2150             // Put the bundle in the cache if it's not been in the cache.
2151             BundleReference result = cacheList.putIfAbsent(key, bundleRef);
2152 
2153             // If someone else has put the same bundle in the cache before
2154             // us and it has not expired, we should use the one in the cache.
2155             if (result != null) {
2156                 ResourceBundle rb = result.get();
2157                 if (rb != null && !rb.expired) {
2158                     // Clear the back link to the cache key
2159                     bundle.cacheKey = null;
2160                     bundle = rb;
2161                     // Clear the reference in the BundleReference so that
2162                     // it won't be enqueued.
2163                     bundleRef.clear();
2164                 } else {
2165                     // Replace the invalid (garbage collected or expired)
2166                     // instance with the valid one.
2167                     cacheList.put(key, bundleRef);
2168                 }
2169             }
2170         }
2171         return bundle;
2172     }
2173 
2174     private static void setExpirationTime(CacheKey cacheKey, Control control) {
2175         long ttl = control.getTimeToLive(cacheKey.getName(),
2176                                          cacheKey.getLocale());
2177         if (ttl >= 0) {
2178             // If any expiration time is specified, set the time to be
2179             // expired in the cache.
2180             long now = System.currentTimeMillis();
2181             cacheKey.loadTime = now;
2182             cacheKey.expirationTime = now + ttl;
2183         } else if (ttl >= Control.TTL_NO_EXPIRATION_CONTROL) {
2184             cacheKey.expirationTime = ttl;
2185         } else {
2186             throw new IllegalArgumentException("Invalid Control: TTL=" + ttl);
2187         }
2188     }
2189 
2190     /**
2191      * Removes all resource bundles from the cache that have been loaded
2192      * by the caller's module.
2193      *
2194      * @since 1.6
2195      * @see ResourceBundle.Control#getTimeToLive(String,Locale)
2196      */
2197     @CallerSensitive
2198     public static final void clearCache() {
2199         Class<?> caller = Reflection.getCallerClass();
2200         cacheList.keySet().removeIf(
2201             key -> key.getCallerModule() == caller.getModule()
2202         );
2203     }
2204 
2205     /**
2206      * Removes all resource bundles from the cache that have been loaded
2207      * by the given class loader.
2208      *
2209      * @param loader the class loader
2210      * @exception NullPointerException if <code>loader</code> is null
2211      * @since 1.6
2212      * @see ResourceBundle.Control#getTimeToLive(String,Locale)
2213      */
2214     public static final void clearCache(ClassLoader loader) {
2215         Objects.requireNonNull(loader);
2216         cacheList.keySet().removeIf(
2217             key -> {
2218                 Module m;
2219                 return (m = key.getModule()) != null &&
2220                        getLoader(m) == loader;
2221             }
2222         );
2223     }
2224 
2225     /**
2226      * Gets an object for the given key from this resource bundle.
2227      * Returns null if this resource bundle does not contain an
2228      * object for the given key.
2229      *
2230      * @param key the key for the desired object
2231      * @exception NullPointerException if <code>key</code> is <code>null</code>
2232      * @return the object for the given key, or null
2233      */
2234     protected abstract Object handleGetObject(String key);
2235 
2236     /**
2237      * Returns an enumeration of the keys.
2238      *
2239      * @return an <code>Enumeration</code> of the keys contained in
2240      *         this <code>ResourceBundle</code> and its parent bundles.
2241      */
2242     public abstract Enumeration<String> getKeys();
2243 
2244     /**
2245      * Determines whether the given <code>key</code> is contained in
2246      * this <code>ResourceBundle</code> or its parent bundles.
2247      *
2248      * @param key
2249      *        the resource <code>key</code>
2250      * @return <code>true</code> if the given <code>key</code> is
2251      *        contained in this <code>ResourceBundle</code> or its
2252      *        parent bundles; <code>false</code> otherwise.
2253      * @exception NullPointerException
2254      *         if <code>key</code> is <code>null</code>
2255      * @since 1.6
2256      */
2257     public boolean containsKey(String key) {
2258         if (key == null) {
2259             throw new NullPointerException();
2260         }
2261         for (ResourceBundle rb = this; rb != null; rb = rb.parent) {
2262             if (rb.handleKeySet().contains(key)) {
2263                 return true;
2264             }
2265         }
2266         return false;
2267     }
2268 
2269     /**
2270      * Returns a <code>Set</code> of all keys contained in this
2271      * <code>ResourceBundle</code> and its parent bundles.
2272      *
2273      * @return a <code>Set</code> of all keys contained in this
2274      *         <code>ResourceBundle</code> and its parent bundles.
2275      * @since 1.6
2276      */
2277     public Set<String> keySet() {
2278         Set<String> keys = new HashSet<>();
2279         for (ResourceBundle rb = this; rb != null; rb = rb.parent) {
2280             keys.addAll(rb.handleKeySet());
2281         }
2282         return keys;
2283     }
2284 
2285     /**
2286      * Returns a <code>Set</code> of the keys contained <em>only</em>
2287      * in this <code>ResourceBundle</code>.
2288      *
2289      * <p>The default implementation returns a <code>Set</code> of the
2290      * keys returned by the {@link #getKeys() getKeys} method except
2291      * for the ones for which the {@link #handleGetObject(String)
2292      * handleGetObject} method returns <code>null</code>. Once the
2293      * <code>Set</code> has been created, the value is kept in this
2294      * <code>ResourceBundle</code> in order to avoid producing the
2295      * same <code>Set</code> in subsequent calls. Subclasses can
2296      * override this method for faster handling.
2297      *
2298      * @return a <code>Set</code> of the keys contained only in this
2299      *        <code>ResourceBundle</code>
2300      * @since 1.6
2301      */
2302     protected Set<String> handleKeySet() {
2303         if (keySet == null) {
2304             synchronized (this) {
2305                 if (keySet == null) {
2306                     Set<String> keys = new HashSet<>();
2307                     Enumeration<String> enumKeys = getKeys();
2308                     while (enumKeys.hasMoreElements()) {
2309                         String key = enumKeys.nextElement();
2310                         if (handleGetObject(key) != null) {
2311                             keys.add(key);
2312                         }
2313                     }
2314                     keySet = keys;
2315                 }
2316             }
2317         }
2318         return keySet;
2319     }
2320 
2321 
2322 
2323     /**
2324      * <code>ResourceBundle.Control</code> defines a set of callback methods
2325      * that are invoked by the {@link ResourceBundle#getBundle(String,
2326      * Locale, ClassLoader, Control) ResourceBundle.getBundle} factory
2327      * methods during the bundle loading process. In other words, a
2328      * <code>ResourceBundle.Control</code> collaborates with the factory
2329      * methods for loading resource bundles. The default implementation of
2330      * the callback methods provides the information necessary for the
2331      * factory methods to perform the <a
2332      * href="./ResourceBundle.html#default_behavior">default behavior</a>.
2333      * <a href="#note">Note that this class is not supported in named modules.</a>
2334      *
2335      * <p>In addition to the callback methods, the {@link
2336      * #toBundleName(String, Locale) toBundleName} and {@link
2337      * #toResourceName(String, String) toResourceName} methods are defined
2338      * primarily for convenience in implementing the callback
2339      * methods. However, the <code>toBundleName</code> method could be
2340      * overridden to provide different conventions in the organization and
2341      * packaging of localized resources.  The <code>toResourceName</code>
2342      * method is <code>final</code> to avoid use of wrong resource and class
2343      * name separators.
2344      *
2345      * <p>Two factory methods, {@link #getControl(List)} and {@link
2346      * #getNoFallbackControl(List)}, provide
2347      * <code>ResourceBundle.Control</code> instances that implement common
2348      * variations of the default bundle loading process.
2349      *
2350      * <p>The formats returned by the {@link Control#getFormats(String)
2351      * getFormats} method and candidate locales returned by the {@link
2352      * ResourceBundle.Control#getCandidateLocales(String, Locale)
2353      * getCandidateLocales} method must be consistent in all
2354      * <code>ResourceBundle.getBundle</code> invocations for the same base
2355      * bundle. Otherwise, the <code>ResourceBundle.getBundle</code> methods
2356      * may return unintended bundles. For example, if only
2357      * <code>"java.class"</code> is returned by the <code>getFormats</code>
2358      * method for the first call to <code>ResourceBundle.getBundle</code>
2359      * and only <code>"java.properties"</code> for the second call, then the
2360      * second call will return the class-based one that has been cached
2361      * during the first call.
2362      *
2363      * <p>A <code>ResourceBundle.Control</code> instance must be thread-safe
2364      * if it's simultaneously used by multiple threads.
2365      * <code>ResourceBundle.getBundle</code> does not synchronize to call
2366      * the <code>ResourceBundle.Control</code> methods. The default
2367      * implementations of the methods are thread-safe.
2368      *
2369      * <p>Applications can specify <code>ResourceBundle.Control</code>
2370      * instances returned by the <code>getControl</code> factory methods or
2371      * created from a subclass of <code>ResourceBundle.Control</code> to
2372      * customize the bundle loading process. The following are examples of
2373      * changing the default bundle loading process.
2374      *
2375      * <p><b>Example 1</b>
2376      *
2377      * <p>The following code lets <code>ResourceBundle.getBundle</code> look
2378      * up only properties-based resources.
2379      *
2380      * <pre>
2381      * import java.util.*;
2382      * import static java.util.ResourceBundle.Control.*;
2383      * ...
2384      * ResourceBundle bundle =
2385      *   ResourceBundle.getBundle("MyResources", new Locale("fr", "CH"),
2386      *                            ResourceBundle.Control.getControl(FORMAT_PROPERTIES));
2387      * </pre>
2388      *
2389      * Given the resource bundles in the <a
2390      * href="./ResourceBundle.html#default_behavior_example">example</a> in
2391      * the <code>ResourceBundle.getBundle</code> description, this
2392      * <code>ResourceBundle.getBundle</code> call loads
2393      * <code>MyResources_fr_CH.properties</code> whose parent is
2394      * <code>MyResources_fr.properties</code> whose parent is
2395      * <code>MyResources.properties</code>. (<code>MyResources_fr_CH.properties</code>
2396      * is not hidden, but <code>MyResources_fr_CH.class</code> is.)
2397      *
2398      * <p><b>Example 2</b>
2399      *
2400      * <p>The following is an example of loading XML-based bundles
2401      * using {@link Properties#loadFromXML(java.io.InputStream)
2402      * Properties.loadFromXML}.
2403      *
2404      * <pre>
2405      * ResourceBundle rb = ResourceBundle.getBundle("Messages",
2406      *     new ResourceBundle.Control() {
2407      *         public List&lt;String&gt; getFormats(String baseName) {
2408      *             if (baseName == null)
2409      *                 throw new NullPointerException();
2410      *             return Arrays.asList("xml");
2411      *         }
2412      *         public ResourceBundle newBundle(String baseName,
2413      *                                         Locale locale,
2414      *                                         String format,
2415      *                                         ClassLoader loader,
2416      *                                         boolean reload)
2417      *                          throws IllegalAccessException,
2418      *                                 InstantiationException,
2419      *                                 IOException {
2420      *             if (baseName == null || locale == null
2421      *                   || format == null || loader == null)
2422      *                 throw new NullPointerException();
2423      *             ResourceBundle bundle = null;
2424      *             if (format.equals("xml")) {
2425      *                 String bundleName = toBundleName(baseName, locale);
2426      *                 String resourceName = toResourceName(bundleName, format);
2427      *                 InputStream stream = null;
2428      *                 if (reload) {
2429      *                     URL url = loader.getResource(resourceName);
2430      *                     if (url != null) {
2431      *                         URLConnection connection = url.openConnection();
2432      *                         if (connection != null) {
2433      *                             // Disable caches to get fresh data for
2434      *                             // reloading.
2435      *                             connection.setUseCaches(false);
2436      *                             stream = connection.getInputStream();
2437      *                         }
2438      *                     }
2439      *                 } else {
2440      *                     stream = loader.getResourceAsStream(resourceName);
2441      *                 }
2442      *                 if (stream != null) {
2443      *                     BufferedInputStream bis = new BufferedInputStream(stream);
2444      *                     bundle = new XMLResourceBundle(bis);
2445      *                     bis.close();
2446      *                 }
2447      *             }
2448      *             return bundle;
2449      *         }
2450      *     });
2451      *
2452      * ...
2453      *
2454      * private static class XMLResourceBundle extends ResourceBundle {
2455      *     private Properties props;
2456      *     XMLResourceBundle(InputStream stream) throws IOException {
2457      *         props = new Properties();
2458      *         props.loadFromXML(stream);
2459      *     }
2460      *     protected Object handleGetObject(String key) {
2461      *         return props.getProperty(key);
2462      *     }
2463      *     public Enumeration&lt;String&gt; getKeys() {
2464      *         ...
2465      *     }
2466      * }
2467      * </pre>
2468      *
2469      * @apiNote <a name="note">{@code ResourceBundle.Control} is not supported
2470      * in named modules.</a> If the {@code ResourceBundle.getBundle} method with
2471      * a {@code ResourceBundle.Control} is called in a named module, the method
2472      * will throw an {@link UnsupportedOperationException}. Any service providers
2473      * of {@link ResourceBundleControlProvider} are ignored in named modules.
2474      *
2475      * @since 1.6
2476      * @see java.util.spi.ResourceBundleProvider
2477      */
2478     public static class Control {
2479         /**
2480          * The default format <code>List</code>, which contains the strings
2481          * <code>"java.class"</code> and <code>"java.properties"</code>, in
2482          * this order. This <code>List</code> is unmodifiable.
2483          *
2484          * @see #getFormats(String)
2485          */
2486         public static final List<String> FORMAT_DEFAULT
2487             = List.of("java.class", "java.properties");
2488 
2489         /**
2490          * The class-only format <code>List</code> containing
2491          * <code>"java.class"</code>. This <code>List</code> is unmodifiable.
2492          *
2493          * @see #getFormats(String)
2494          */
2495         public static final List<String> FORMAT_CLASS = List.of("java.class");
2496 
2497         /**
2498          * The properties-only format <code>List</code> containing
2499          * <code>"java.properties"</code>. This <code>List</code> is unmodifiable.
2500          *
2501          * @see #getFormats(String)
2502          */
2503         public static final List<String> FORMAT_PROPERTIES
2504             = List.of("java.properties");
2505 
2506         /**
2507          * The time-to-live constant for not caching loaded resource bundle
2508          * instances.
2509          *
2510          * @see #getTimeToLive(String, Locale)
2511          */
2512         public static final long TTL_DONT_CACHE = -1;
2513 
2514         /**
2515          * The time-to-live constant for disabling the expiration control
2516          * for loaded resource bundle instances in the cache.
2517          *
2518          * @see #getTimeToLive(String, Locale)
2519          */
2520         public static final long TTL_NO_EXPIRATION_CONTROL = -2;
2521 
2522         private static final Control INSTANCE = new Control();
2523 
2524         /**
2525          * Sole constructor. (For invocation by subclass constructors,
2526          * typically implicit.)
2527          */
2528         protected Control() {
2529         }
2530 
2531         /**
2532          * Returns a <code>ResourceBundle.Control</code> in which the {@link
2533          * #getFormats(String) getFormats} method returns the specified
2534          * <code>formats</code>. The <code>formats</code> must be equal to
2535          * one of {@link Control#FORMAT_PROPERTIES}, {@link
2536          * Control#FORMAT_CLASS} or {@link
2537          * Control#FORMAT_DEFAULT}. <code>ResourceBundle.Control</code>
2538          * instances returned by this method are singletons and thread-safe.
2539          *
2540          * <p>Specifying {@link Control#FORMAT_DEFAULT} is equivalent to
2541          * instantiating the <code>ResourceBundle.Control</code> class,
2542          * except that this method returns a singleton.
2543          *
2544          * @param formats
2545          *        the formats to be returned by the
2546          *        <code>ResourceBundle.Control.getFormats</code> method
2547          * @return a <code>ResourceBundle.Control</code> supporting the
2548          *        specified <code>formats</code>
2549          * @exception NullPointerException
2550          *        if <code>formats</code> is <code>null</code>
2551          * @exception IllegalArgumentException
2552          *        if <code>formats</code> is unknown
2553          */
2554         public static final Control getControl(List<String> formats) {
2555             if (formats.equals(Control.FORMAT_PROPERTIES)) {
2556                 return SingleFormatControl.PROPERTIES_ONLY;
2557             }
2558             if (formats.equals(Control.FORMAT_CLASS)) {
2559                 return SingleFormatControl.CLASS_ONLY;
2560             }
2561             if (formats.equals(Control.FORMAT_DEFAULT)) {
2562                 return Control.INSTANCE;
2563             }
2564             throw new IllegalArgumentException();
2565         }
2566 
2567         /**
2568          * Returns a <code>ResourceBundle.Control</code> in which the {@link
2569          * #getFormats(String) getFormats} method returns the specified
2570          * <code>formats</code> and the {@link
2571          * Control#getFallbackLocale(String, Locale) getFallbackLocale}
2572          * method returns <code>null</code>. The <code>formats</code> must
2573          * be equal to one of {@link Control#FORMAT_PROPERTIES}, {@link
2574          * Control#FORMAT_CLASS} or {@link Control#FORMAT_DEFAULT}.
2575          * <code>ResourceBundle.Control</code> instances returned by this
2576          * method are singletons and thread-safe.
2577          *
2578          * @param formats
2579          *        the formats to be returned by the
2580          *        <code>ResourceBundle.Control.getFormats</code> method
2581          * @return a <code>ResourceBundle.Control</code> supporting the
2582          *        specified <code>formats</code> with no fallback
2583          *        <code>Locale</code> support
2584          * @exception NullPointerException
2585          *        if <code>formats</code> is <code>null</code>
2586          * @exception IllegalArgumentException
2587          *        if <code>formats</code> is unknown
2588          */
2589         public static final Control getNoFallbackControl(List<String> formats) {
2590             if (formats.equals(Control.FORMAT_DEFAULT)) {
2591                 return NoFallbackControl.NO_FALLBACK;
2592             }
2593             if (formats.equals(Control.FORMAT_PROPERTIES)) {
2594                 return NoFallbackControl.PROPERTIES_ONLY_NO_FALLBACK;
2595             }
2596             if (formats.equals(Control.FORMAT_CLASS)) {
2597                 return NoFallbackControl.CLASS_ONLY_NO_FALLBACK;
2598             }
2599             throw new IllegalArgumentException();
2600         }
2601 
2602         /**
2603          * Returns a <code>List</code> of <code>String</code>s containing
2604          * formats to be used to load resource bundles for the given
2605          * <code>baseName</code>. The <code>ResourceBundle.getBundle</code>
2606          * factory method tries to load resource bundles with formats in the
2607          * order specified by the list. The list returned by this method
2608          * must have at least one <code>String</code>. The predefined
2609          * formats are <code>"java.class"</code> for class-based resource
2610          * bundles and <code>"java.properties"</code> for {@linkplain
2611          * PropertyResourceBundle properties-based} ones. Strings starting
2612          * with <code>"java."</code> are reserved for future extensions and
2613          * must not be used by application-defined formats.
2614          *
2615          * <p>It is not a requirement to return an immutable (unmodifiable)
2616          * <code>List</code>.  However, the returned <code>List</code> must
2617          * not be mutated after it has been returned by
2618          * <code>getFormats</code>.
2619          *
2620          * <p>The default implementation returns {@link #FORMAT_DEFAULT} so
2621          * that the <code>ResourceBundle.getBundle</code> factory method
2622          * looks up first class-based resource bundles, then
2623          * properties-based ones.
2624          *
2625          * @param baseName
2626          *        the base name of the resource bundle, a fully qualified class
2627          *        name
2628          * @return a <code>List</code> of <code>String</code>s containing
2629          *        formats for loading resource bundles.
2630          * @exception NullPointerException
2631          *        if <code>baseName</code> is null
2632          * @see #FORMAT_DEFAULT
2633          * @see #FORMAT_CLASS
2634          * @see #FORMAT_PROPERTIES
2635          */
2636         public List<String> getFormats(String baseName) {
2637             if (baseName == null) {
2638                 throw new NullPointerException();
2639             }
2640             return FORMAT_DEFAULT;
2641         }
2642 
2643         /**
2644          * Returns a <code>List</code> of <code>Locale</code>s as candidate
2645          * locales for <code>baseName</code> and <code>locale</code>. This
2646          * method is called by the <code>ResourceBundle.getBundle</code>
2647          * factory method each time the factory method tries finding a
2648          * resource bundle for a target <code>Locale</code>.
2649          *
2650          * <p>The sequence of the candidate locales also corresponds to the
2651          * runtime resource lookup path (also known as the <I>parent
2652          * chain</I>), if the corresponding resource bundles for the
2653          * candidate locales exist and their parents are not defined by
2654          * loaded resource bundles themselves.  The last element of the list
2655          * must be a {@linkplain Locale#ROOT root locale} if it is desired to
2656          * have the base bundle as the terminal of the parent chain.
2657          *
2658          * <p>If the given locale is equal to <code>Locale.ROOT</code> (the
2659          * root locale), a <code>List</code> containing only the root
2660          * <code>Locale</code> must be returned. In this case, the
2661          * <code>ResourceBundle.getBundle</code> factory method loads only
2662          * the base bundle as the resulting resource bundle.
2663          *
2664          * <p>It is not a requirement to return an immutable (unmodifiable)
2665          * <code>List</code>. However, the returned <code>List</code> must not
2666          * be mutated after it has been returned by
2667          * <code>getCandidateLocales</code>.
2668          *
2669          * <p>The default implementation returns a <code>List</code> containing
2670          * <code>Locale</code>s using the rules described below.  In the
2671          * description below, <em>L</em>, <em>S</em>, <em>C</em> and <em>V</em>
2672          * respectively represent non-empty language, script, country, and
2673          * variant.  For example, [<em>L</em>, <em>C</em>] represents a
2674          * <code>Locale</code> that has non-empty values only for language and
2675          * country.  The form <em>L</em>("xx") represents the (non-empty)
2676          * language value is "xx".  For all cases, <code>Locale</code>s whose
2677          * final component values are empty strings are omitted.
2678          *
2679          * <ol><li>For an input <code>Locale</code> with an empty script value,
2680          * append candidate <code>Locale</code>s by omitting the final component
2681          * one by one as below:
2682          *
2683          * <ul>
2684          * <li> [<em>L</em>, <em>C</em>, <em>V</em>] </li>
2685          * <li> [<em>L</em>, <em>C</em>] </li>
2686          * <li> [<em>L</em>] </li>
2687          * <li> <code>Locale.ROOT</code> </li>
2688          * </ul></li>
2689          *
2690          * <li>For an input <code>Locale</code> with a non-empty script value,
2691          * append candidate <code>Locale</code>s by omitting the final component
2692          * up to language, then append candidates generated from the
2693          * <code>Locale</code> with country and variant restored:
2694          *
2695          * <ul>
2696          * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V</em>]</li>
2697          * <li> [<em>L</em>, <em>S</em>, <em>C</em>]</li>
2698          * <li> [<em>L</em>, <em>S</em>]</li>
2699          * <li> [<em>L</em>, <em>C</em>, <em>V</em>]</li>
2700          * <li> [<em>L</em>, <em>C</em>]</li>
2701          * <li> [<em>L</em>]</li>
2702          * <li> <code>Locale.ROOT</code></li>
2703          * </ul></li>
2704          *
2705          * <li>For an input <code>Locale</code> with a variant value consisting
2706          * of multiple subtags separated by underscore, generate candidate
2707          * <code>Locale</code>s by omitting the variant subtags one by one, then
2708          * insert them after every occurrence of <code> Locale</code>s with the
2709          * full variant value in the original list.  For example, if the
2710          * the variant consists of two subtags <em>V1</em> and <em>V2</em>:
2711          *
2712          * <ul>
2713          * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]</li>
2714          * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>]</li>
2715          * <li> [<em>L</em>, <em>S</em>, <em>C</em>]</li>
2716          * <li> [<em>L</em>, <em>S</em>]</li>
2717          * <li> [<em>L</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]</li>
2718          * <li> [<em>L</em>, <em>C</em>, <em>V1</em>]</li>
2719          * <li> [<em>L</em>, <em>C</em>]</li>
2720          * <li> [<em>L</em>]</li>
2721          * <li> <code>Locale.ROOT</code></li>
2722          * </ul></li>
2723          *
2724          * <li>Special cases for Chinese.  When an input <code>Locale</code> has the
2725          * language "zh" (Chinese) and an empty script value, either "Hans" (Simplified) or
2726          * "Hant" (Traditional) might be supplied, depending on the country.
2727          * When the country is "CN" (China) or "SG" (Singapore), "Hans" is supplied.
2728          * When the country is "HK" (Hong Kong SAR China), "MO" (Macau SAR China),
2729          * or "TW" (Taiwan), "Hant" is supplied.  For all other countries or when the country
2730          * is empty, no script is supplied.  For example, for <code>Locale("zh", "CN")
2731          * </code>, the candidate list will be:
2732          * <ul>
2733          * <li> [<em>L</em>("zh"), <em>S</em>("Hans"), <em>C</em>("CN")]</li>
2734          * <li> [<em>L</em>("zh"), <em>S</em>("Hans")]</li>
2735          * <li> [<em>L</em>("zh"), <em>C</em>("CN")]</li>
2736          * <li> [<em>L</em>("zh")]</li>
2737          * <li> <code>Locale.ROOT</code></li>
2738          * </ul>
2739          *
2740          * For <code>Locale("zh", "TW")</code>, the candidate list will be:
2741          * <ul>
2742          * <li> [<em>L</em>("zh"), <em>S</em>("Hant"), <em>C</em>("TW")]</li>
2743          * <li> [<em>L</em>("zh"), <em>S</em>("Hant")]</li>
2744          * <li> [<em>L</em>("zh"), <em>C</em>("TW")]</li>
2745          * <li> [<em>L</em>("zh")]</li>
2746          * <li> <code>Locale.ROOT</code></li>
2747          * </ul></li>
2748          *
2749          * <li>Special cases for Norwegian.  Both <code>Locale("no", "NO",
2750          * "NY")</code> and <code>Locale("nn", "NO")</code> represent Norwegian
2751          * Nynorsk.  When a locale's language is "nn", the standard candidate
2752          * list is generated up to [<em>L</em>("nn")], and then the following
2753          * candidates are added:
2754          *
2755          * <ul><li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("NY")]</li>
2756          * <li> [<em>L</em>("no"), <em>C</em>("NO")]</li>
2757          * <li> [<em>L</em>("no")]</li>
2758          * <li> <code>Locale.ROOT</code></li>
2759          * </ul>
2760          *
2761          * If the locale is exactly <code>Locale("no", "NO", "NY")</code>, it is first
2762          * converted to <code>Locale("nn", "NO")</code> and then the above procedure is
2763          * followed.
2764          *
2765          * <p>Also, Java treats the language "no" as a synonym of Norwegian
2766          * Bokmål "nb".  Except for the single case <code>Locale("no",
2767          * "NO", "NY")</code> (handled above), when an input <code>Locale</code>
2768          * has language "no" or "nb", candidate <code>Locale</code>s with
2769          * language code "no" and "nb" are interleaved, first using the
2770          * requested language, then using its synonym. For example,
2771          * <code>Locale("nb", "NO", "POSIX")</code> generates the following
2772          * candidate list:
2773          *
2774          * <ul>
2775          * <li> [<em>L</em>("nb"), <em>C</em>("NO"), <em>V</em>("POSIX")]</li>
2776          * <li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("POSIX")]</li>
2777          * <li> [<em>L</em>("nb"), <em>C</em>("NO")]</li>
2778          * <li> [<em>L</em>("no"), <em>C</em>("NO")]</li>
2779          * <li> [<em>L</em>("nb")]</li>
2780          * <li> [<em>L</em>("no")]</li>
2781          * <li> <code>Locale.ROOT</code></li>
2782          * </ul>
2783          *
2784          * <code>Locale("no", "NO", "POSIX")</code> would generate the same list
2785          * except that locales with "no" would appear before the corresponding
2786          * locales with "nb".</li>
2787          * </ol>
2788          *
2789          * <p>The default implementation uses an {@link ArrayList} that
2790          * overriding implementations may modify before returning it to the
2791          * caller. However, a subclass must not modify it after it has
2792          * been returned by <code>getCandidateLocales</code>.
2793          *
2794          * <p>For example, if the given <code>baseName</code> is "Messages"
2795          * and the given <code>locale</code> is
2796          * <code>Locale("ja",&nbsp;"",&nbsp;"XX")</code>, then a
2797          * <code>List</code> of <code>Locale</code>s:
2798          * <pre>
2799          *     Locale("ja", "", "XX")
2800          *     Locale("ja")
2801          *     Locale.ROOT
2802          * </pre>
2803          * is returned. And if the resource bundles for the "ja" and
2804          * "" <code>Locale</code>s are found, then the runtime resource
2805          * lookup path (parent chain) is:
2806          * <pre>{@code
2807          *     Messages_ja -> Messages
2808          * }</pre>
2809          *
2810          * @param baseName
2811          *        the base name of the resource bundle, a fully
2812          *        qualified class name
2813          * @param locale
2814          *        the locale for which a resource bundle is desired
2815          * @return a <code>List</code> of candidate
2816          *        <code>Locale</code>s for the given <code>locale</code>
2817          * @exception NullPointerException
2818          *        if <code>baseName</code> or <code>locale</code> is
2819          *        <code>null</code>
2820          */
2821         public List<Locale> getCandidateLocales(String baseName, Locale locale) {
2822             if (baseName == null) {
2823                 throw new NullPointerException();
2824             }
2825             return new ArrayList<>(CANDIDATES_CACHE.get(locale.getBaseLocale()));
2826         }
2827 
2828         private static final CandidateListCache CANDIDATES_CACHE = new CandidateListCache();
2829 
2830         private static class CandidateListCache extends LocaleObjectCache<BaseLocale, List<Locale>> {
2831             protected List<Locale> createObject(BaseLocale base) {
2832                 String language = base.getLanguage();
2833                 String script = base.getScript();
2834                 String region = base.getRegion();
2835                 String variant = base.getVariant();
2836 
2837                 // Special handling for Norwegian
2838                 boolean isNorwegianBokmal = false;
2839                 boolean isNorwegianNynorsk = false;
2840                 if (language.equals("no")) {
2841                     if (region.equals("NO") && variant.equals("NY")) {
2842                         variant = "";
2843                         isNorwegianNynorsk = true;
2844                     } else {
2845                         isNorwegianBokmal = true;
2846                     }
2847                 }
2848                 if (language.equals("nb") || isNorwegianBokmal) {
2849                     List<Locale> tmpList = getDefaultList("nb", script, region, variant);
2850                     // Insert a locale replacing "nb" with "no" for every list entry
2851                     List<Locale> bokmalList = new LinkedList<>();
2852                     for (Locale l : tmpList) {
2853                         bokmalList.add(l);
2854                         if (l.getLanguage().length() == 0) {
2855                             break;
2856                         }
2857                         bokmalList.add(Locale.getInstance("no", l.getScript(), l.getCountry(),
2858                                 l.getVariant(), null));
2859                     }
2860                     return bokmalList;
2861                 } else if (language.equals("nn") || isNorwegianNynorsk) {
2862                     // Insert no_NO_NY, no_NO, no after nn
2863                     List<Locale> nynorskList = getDefaultList("nn", script, region, variant);
2864                     int idx = nynorskList.size() - 1;
2865                     nynorskList.add(idx++, Locale.getInstance("no", "NO", "NY"));
2866                     nynorskList.add(idx++, Locale.getInstance("no", "NO", ""));
2867                     nynorskList.add(idx++, Locale.getInstance("no", "", ""));
2868                     return nynorskList;
2869                 }
2870                 // Special handling for Chinese
2871                 else if (language.equals("zh")) {
2872                     if (script.length() == 0 && region.length() > 0) {
2873                         // Supply script for users who want to use zh_Hans/zh_Hant
2874                         // as bundle names (recommended for Java7+)
2875                         switch (region) {
2876                         case "TW":
2877                         case "HK":
2878                         case "MO":
2879                             script = "Hant";
2880                             break;
2881                         case "CN":
2882                         case "SG":
2883                             script = "Hans";
2884                             break;
2885                         }
2886                     }
2887                 }
2888 
2889                 return getDefaultList(language, script, region, variant);
2890             }
2891 
2892             private static List<Locale> getDefaultList(String language, String script, String region, String variant) {
2893                 List<String> variants = null;
2894 
2895                 if (variant.length() > 0) {
2896                     variants = new LinkedList<>();
2897                     int idx = variant.length();
2898                     while (idx != -1) {
2899                         variants.add(variant.substring(0, idx));
2900                         idx = variant.lastIndexOf('_', --idx);
2901                     }
2902                 }
2903 
2904                 List<Locale> list = new LinkedList<>();
2905 
2906                 if (variants != null) {
2907                     for (String v : variants) {
2908                         list.add(Locale.getInstance(language, script, region, v, null));
2909                     }
2910                 }
2911                 if (region.length() > 0) {
2912                     list.add(Locale.getInstance(language, script, region, "", null));
2913                 }
2914                 if (script.length() > 0) {
2915                     list.add(Locale.getInstance(language, script, "", "", null));
2916                     // Special handling for Chinese
2917                     if (language.equals("zh")) {
2918                         if (region.length() == 0) {
2919                             // Supply region(country) for users who still package Chinese
2920                             // bundles using old convension.
2921                             switch (script) {
2922                                 case "Hans":
2923                                     region = "CN";
2924                                     break;
2925                                 case "Hant":
2926                                     region = "TW";
2927                                     break;
2928                             }
2929                         }
2930                     }
2931 
2932                     // With script, after truncating variant, region and script,
2933                     // start over without script.
2934                     if (variants != null) {
2935                         for (String v : variants) {
2936                             list.add(Locale.getInstance(language, "", region, v, null));
2937                         }
2938                     }
2939                     if (region.length() > 0) {
2940                         list.add(Locale.getInstance(language, "", region, "", null));
2941                     }
2942                 }
2943                 if (language.length() > 0) {
2944                     list.add(Locale.getInstance(language, "", "", "", null));
2945                 }
2946                 // Add root locale at the end
2947                 list.add(Locale.ROOT);
2948 
2949                 return list;
2950             }
2951         }
2952 
2953         /**
2954          * Returns a <code>Locale</code> to be used as a fallback locale for
2955          * further resource bundle searches by the
2956          * <code>ResourceBundle.getBundle</code> factory method. This method
2957          * is called from the factory method every time when no resulting
2958          * resource bundle has been found for <code>baseName</code> and
2959          * <code>locale</code>, where locale is either the parameter for
2960          * <code>ResourceBundle.getBundle</code> or the previous fallback
2961          * locale returned by this method.
2962          *
2963          * <p>The method returns <code>null</code> if no further fallback
2964          * search is desired.
2965          *
2966          * <p>The default implementation returns the {@linkplain
2967          * Locale#getDefault() default <code>Locale</code>} if the given
2968          * <code>locale</code> isn't the default one.  Otherwise,
2969          * <code>null</code> is returned.
2970          *
2971          * @param baseName
2972          *        the base name of the resource bundle, a fully
2973          *        qualified class name for which
2974          *        <code>ResourceBundle.getBundle</code> has been
2975          *        unable to find any resource bundles (except for the
2976          *        base bundle)
2977          * @param locale
2978          *        the <code>Locale</code> for which
2979          *        <code>ResourceBundle.getBundle</code> has been
2980          *        unable to find any resource bundles (except for the
2981          *        base bundle)
2982          * @return a <code>Locale</code> for the fallback search,
2983          *        or <code>null</code> if no further fallback search
2984          *        is desired.
2985          * @exception NullPointerException
2986          *        if <code>baseName</code> or <code>locale</code>
2987          *        is <code>null</code>
2988          */
2989         public Locale getFallbackLocale(String baseName, Locale locale) {
2990             if (baseName == null) {
2991                 throw new NullPointerException();
2992             }
2993             Locale defaultLocale = Locale.getDefault();
2994             return locale.equals(defaultLocale) ? null : defaultLocale;
2995         }
2996 
2997         /**
2998          * Instantiates a resource bundle for the given bundle name of the
2999          * given format and locale, using the given class loader if
3000          * necessary. This method returns <code>null</code> if there is no
3001          * resource bundle available for the given parameters. If a resource
3002          * bundle can't be instantiated due to an unexpected error, the
3003          * error must be reported by throwing an <code>Error</code> or
3004          * <code>Exception</code> rather than simply returning
3005          * <code>null</code>.
3006          *
3007          * <p>If the <code>reload</code> flag is <code>true</code>, it
3008          * indicates that this method is being called because the previously
3009          * loaded resource bundle has expired.
3010          *
3011          * @implSpec
3012          *
3013          * Resource bundles in named modules are subject to the encapsulation
3014          * rules specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
3015          * A resource bundle in a named module visible to the given class loader
3016          * is accessible when the package of the resource file corresponding
3017          * to the resource bundle is open unconditionally.
3018          *
3019          * <p>The default implementation instantiates a
3020          * <code>ResourceBundle</code> as follows.
3021          *
3022          * <ul>
3023          *
3024          * <li>The bundle name is obtained by calling {@link
3025          * #toBundleName(String, Locale) toBundleName(baseName,
3026          * locale)}.</li>
3027          *
3028          * <li>If <code>format</code> is <code>"java.class"</code>, the
3029          * {@link Class} specified by the bundle name is loaded with the
3030          * given class loader. If the {@code Class} is found and accessible
3031          * then the <code>ResourceBundle</code> is instantiated.  The
3032          * resource bundle is accessible if the package of the bundle class file
3033          * is open unconditionally; otherwise, {@code IllegalAccessException}
3034          * will be thrown.
3035          * Note that the <code>reload</code> flag is ignored for loading
3036          * class-based resource bundles in this default implementation.
3037          * </li>
3038          *
3039          * <li>If <code>format</code> is <code>"java.properties"</code>,
3040          * {@link #toResourceName(String, String) toResourceName(bundlename,
3041          * "properties")} is called to get the resource name.
3042          * If <code>reload</code> is <code>true</code>, {@link
3043          * ClassLoader#getResource(String) load.getResource} is called
3044          * to get a {@link URL} for creating a {@link
3045          * URLConnection}. This <code>URLConnection</code> is used to
3046          * {@linkplain URLConnection#setUseCaches(boolean) disable the
3047          * caches} of the underlying resource loading layers,
3048          * and to {@linkplain URLConnection#getInputStream() get an
3049          * <code>InputStream</code>}.
3050          * Otherwise, {@link ClassLoader#getResourceAsStream(String)
3051          * loader.getResourceAsStream} is called to get an {@link
3052          * InputStream}. Then, a {@link
3053          * PropertyResourceBundle} is constructed with the
3054          * <code>InputStream</code>.</li>
3055          *
3056          * <li>If <code>format</code> is neither <code>"java.class"</code>
3057          * nor <code>"java.properties"</code>, an
3058          * <code>IllegalArgumentException</code> is thrown.</li>
3059          *
3060          * </ul>
3061          *
3062          * @param baseName
3063          *        the base bundle name of the resource bundle, a fully
3064          *        qualified class name
3065          * @param locale
3066          *        the locale for which the resource bundle should be
3067          *        instantiated
3068          * @param format
3069          *        the resource bundle format to be loaded
3070          * @param loader
3071          *        the <code>ClassLoader</code> to use to load the bundle
3072          * @param reload
3073          *        the flag to indicate bundle reloading; <code>true</code>
3074          *        if reloading an expired resource bundle,
3075          *        <code>false</code> otherwise
3076          * @return the resource bundle instance,
3077          *        or <code>null</code> if none could be found.
3078          * @exception NullPointerException
3079          *        if <code>bundleName</code>, <code>locale</code>,
3080          *        <code>format</code>, or <code>loader</code> is
3081          *        <code>null</code>, or if <code>null</code> is returned by
3082          *        {@link #toBundleName(String, Locale) toBundleName}
3083          * @exception IllegalArgumentException
3084          *        if <code>format</code> is unknown, or if the resource
3085          *        found for the given parameters contains malformed data.
3086          * @exception ClassCastException
3087          *        if the loaded class cannot be cast to <code>ResourceBundle</code>
3088          * @exception IllegalAccessException
3089          *        if the class or its nullary constructor is not
3090          *        accessible.
3091          * @exception InstantiationException
3092          *        if the instantiation of a class fails for some other
3093          *        reason.
3094          * @exception ExceptionInInitializerError
3095          *        if the initialization provoked by this method fails.
3096          * @exception SecurityException
3097          *        If a security manager is present and creation of new
3098          *        instances is denied. See {@link Class#newInstance()}
3099          *        for details.
3100          * @exception IOException
3101          *        if an error occurred when reading resources using
3102          *        any I/O operations
3103          * @see java.util.spi.ResourceBundleProvider#getBundle(String, Locale)
3104          */
3105         public ResourceBundle newBundle(String baseName, Locale locale, String format,
3106                                         ClassLoader loader, boolean reload)
3107                     throws IllegalAccessException, InstantiationException, IOException {
3108             /*
3109              * Legacy mechanism to locate resource bundle in unnamed module only
3110              * that is visible to the given loader and accessible to the given caller.
3111              */
3112             String bundleName = toBundleName(baseName, locale);
3113             ResourceBundle bundle = null;
3114             if (format.equals("java.class")) {
3115                 try {
3116                     Class<?> c = loader.loadClass(bundleName);
3117                     // If the class isn't a ResourceBundle subclass, throw a
3118                     // ClassCastException.
3119                     if (ResourceBundle.class.isAssignableFrom(c)) {
3120                         @SuppressWarnings("unchecked")
3121                         Class<ResourceBundle> bundleClass = (Class<ResourceBundle>)c;
3122                         Module m = bundleClass.getModule();
3123 
3124                         // To access a resource bundle in a named module,
3125                         // either class-based or properties-based, the resource
3126                         // bundle must be opened unconditionally,
3127                         // same rule as accessing a resource file.
3128                         if (m.isNamed() && !m.isOpen(bundleClass.getPackageName())) {
3129                             throw new IllegalAccessException("unnamed module can't load " +
3130                                 bundleClass.getName() + " in " + m.toString());
3131                         }
3132                         try {
3133                             // bundle in a unnamed module
3134                             Constructor<ResourceBundle> ctor = bundleClass.getConstructor();
3135                             if (!Modifier.isPublic(ctor.getModifiers())) {
3136                                 return null;
3137                             }
3138 
3139                             // java.base may not be able to read the bundleClass's module.
3140                             PrivilegedAction<Void> pa1 = () -> { ctor.setAccessible(true); return null; };
3141                             AccessController.doPrivileged(pa1);
3142                             bundle = ctor.newInstance((Object[]) null);
3143                         } catch (InvocationTargetException e) {
3144                             uncheckedThrow(e);
3145                         }
3146                     } else {
3147                         throw new ClassCastException(c.getName()
3148                                 + " cannot be cast to ResourceBundle");
3149                     }
3150                 } catch (ClassNotFoundException|NoSuchMethodException e) {
3151                 }
3152             } else if (format.equals("java.properties")) {
3153                 final String resourceName = toResourceName0(bundleName, "properties");
3154                 if (resourceName == null) {
3155                     return bundle;
3156                 }
3157 
3158                 final boolean reloadFlag = reload;
3159                 InputStream stream = null;
3160                 try {
3161                     stream = AccessController.doPrivileged(
3162                         new PrivilegedExceptionAction<>() {
3163                             public InputStream run() throws IOException {
3164                                 URL url = loader.getResource(resourceName);
3165                                 if (url == null) return null;
3166 
3167                                 URLConnection connection = url.openConnection();
3168                                 if (reloadFlag) {
3169                                     // Disable caches to get fresh data for
3170                                     // reloading.
3171                                     connection.setUseCaches(false);
3172                                 }
3173                                 return connection.getInputStream();
3174                             }
3175                         });
3176                 } catch (PrivilegedActionException e) {
3177                     throw (IOException) e.getException();
3178                 }
3179                 if (stream != null) {
3180                     try {
3181                         bundle = new PropertyResourceBundle(stream);
3182                     } finally {
3183                         stream.close();
3184                     }
3185                 }
3186             } else {
3187                 throw new IllegalArgumentException("unknown format: " + format);
3188             }
3189             return bundle;
3190         }
3191 
3192         /**
3193          * Returns the time-to-live (TTL) value for resource bundles that
3194          * are loaded under this
3195          * <code>ResourceBundle.Control</code>. Positive time-to-live values
3196          * specify the number of milliseconds a bundle can remain in the
3197          * cache without being validated against the source data from which
3198          * it was constructed. The value 0 indicates that a bundle must be
3199          * validated each time it is retrieved from the cache. {@link
3200          * #TTL_DONT_CACHE} specifies that loaded resource bundles are not
3201          * put in the cache. {@link #TTL_NO_EXPIRATION_CONTROL} specifies
3202          * that loaded resource bundles are put in the cache with no
3203          * expiration control.
3204          *
3205          * <p>The expiration affects only the bundle loading process by the
3206          * <code>ResourceBundle.getBundle</code> factory method.  That is,
3207          * if the factory method finds a resource bundle in the cache that
3208          * has expired, the factory method calls the {@link
3209          * #needsReload(String, Locale, String, ClassLoader, ResourceBundle,
3210          * long) needsReload} method to determine whether the resource
3211          * bundle needs to be reloaded. If <code>needsReload</code> returns
3212          * <code>true</code>, the cached resource bundle instance is removed
3213          * from the cache. Otherwise, the instance stays in the cache,
3214          * updated with the new TTL value returned by this method.
3215          *
3216          * <p>All cached resource bundles are subject to removal from the
3217          * cache due to memory constraints of the runtime environment.
3218          * Returning a large positive value doesn't mean to lock loaded
3219          * resource bundles in the cache.
3220          *
3221          * <p>The default implementation returns {@link #TTL_NO_EXPIRATION_CONTROL}.
3222          *
3223          * @param baseName
3224          *        the base name of the resource bundle for which the
3225          *        expiration value is specified.
3226          * @param locale
3227          *        the locale of the resource bundle for which the
3228          *        expiration value is specified.
3229          * @return the time (0 or a positive millisecond offset from the
3230          *        cached time) to get loaded bundles expired in the cache,
3231          *        {@link #TTL_NO_EXPIRATION_CONTROL} to disable the
3232          *        expiration control, or {@link #TTL_DONT_CACHE} to disable
3233          *        caching.
3234          * @exception NullPointerException
3235          *        if <code>baseName</code> or <code>locale</code> is
3236          *        <code>null</code>
3237          */
3238         public long getTimeToLive(String baseName, Locale locale) {
3239             if (baseName == null || locale == null) {
3240                 throw new NullPointerException();
3241             }
3242             return TTL_NO_EXPIRATION_CONTROL;
3243         }
3244 
3245         /**
3246          * Determines if the expired <code>bundle</code> in the cache needs
3247          * to be reloaded based on the loading time given by
3248          * <code>loadTime</code> or some other criteria. The method returns
3249          * <code>true</code> if reloading is required; <code>false</code>
3250          * otherwise. <code>loadTime</code> is a millisecond offset since
3251          * the <a href="Calendar.html#Epoch"> <code>Calendar</code>
3252          * Epoch</a>.
3253          *
3254          * <p>
3255          * The calling <code>ResourceBundle.getBundle</code> factory method
3256          * calls this method on the <code>ResourceBundle.Control</code>
3257          * instance used for its current invocation, not on the instance
3258          * used in the invocation that originally loaded the resource
3259          * bundle.
3260          *
3261          * <p>The default implementation compares <code>loadTime</code> and
3262          * the last modified time of the source data of the resource
3263          * bundle. If it's determined that the source data has been modified
3264          * since <code>loadTime</code>, <code>true</code> is
3265          * returned. Otherwise, <code>false</code> is returned. This
3266          * implementation assumes that the given <code>format</code> is the
3267          * same string as its file suffix if it's not one of the default
3268          * formats, <code>"java.class"</code> or
3269          * <code>"java.properties"</code>.
3270          *
3271          * @param baseName
3272          *        the base bundle name of the resource bundle, a
3273          *        fully qualified class name
3274          * @param locale
3275          *        the locale for which the resource bundle
3276          *        should be instantiated
3277          * @param format
3278          *        the resource bundle format to be loaded
3279          * @param loader
3280          *        the <code>ClassLoader</code> to use to load the bundle
3281          * @param bundle
3282          *        the resource bundle instance that has been expired
3283          *        in the cache
3284          * @param loadTime
3285          *        the time when <code>bundle</code> was loaded and put
3286          *        in the cache
3287          * @return <code>true</code> if the expired bundle needs to be
3288          *        reloaded; <code>false</code> otherwise.
3289          * @exception NullPointerException
3290          *        if <code>baseName</code>, <code>locale</code>,
3291          *        <code>format</code>, <code>loader</code>, or
3292          *        <code>bundle</code> is <code>null</code>
3293          */
3294         public boolean needsReload(String baseName, Locale locale,
3295                                    String format, ClassLoader loader,
3296                                    ResourceBundle bundle, long loadTime) {
3297             if (bundle == null) {
3298                 throw new NullPointerException();
3299             }
3300             if (format.equals("java.class") || format.equals("java.properties")) {
3301                 format = format.substring(5);
3302             }
3303             boolean result = false;
3304             try {
3305                 String resourceName = toResourceName0(toBundleName(baseName, locale), format);
3306                 if (resourceName == null) {
3307                     return result;
3308                 }
3309                 URL url = loader.getResource(resourceName);
3310                 if (url != null) {
3311                     long lastModified = 0;
3312                     URLConnection connection = url.openConnection();
3313                     if (connection != null) {
3314                         // disable caches to get the correct data
3315                         connection.setUseCaches(false);
3316                         if (connection instanceof JarURLConnection) {
3317                             JarEntry ent = ((JarURLConnection)connection).getJarEntry();
3318                             if (ent != null) {
3319                                 lastModified = ent.getTime();
3320                                 if (lastModified == -1) {
3321                                     lastModified = 0;
3322                                 }
3323                             }
3324                         } else {
3325                             lastModified = connection.getLastModified();
3326                         }
3327                     }
3328                     result = lastModified >= loadTime;
3329                 }
3330             } catch (NullPointerException npe) {
3331                 throw npe;
3332             } catch (Exception e) {
3333                 // ignore other exceptions
3334             }
3335             return result;
3336         }
3337 
3338         /**
3339          * Converts the given <code>baseName</code> and <code>locale</code>
3340          * to the bundle name. This method is called from the default
3341          * implementation of the {@link #newBundle(String, Locale, String,
3342          * ClassLoader, boolean) newBundle} and {@link #needsReload(String,
3343          * Locale, String, ClassLoader, ResourceBundle, long) needsReload}
3344          * methods.
3345          *
3346          * <p>This implementation returns the following value:
3347          * <pre>
3348          *     baseName + "_" + language + "_" + script + "_" + country + "_" + variant
3349          * </pre>
3350          * where <code>language</code>, <code>script</code>, <code>country</code>,
3351          * and <code>variant</code> are the language, script, country, and variant
3352          * values of <code>locale</code>, respectively. Final component values that
3353          * are empty Strings are omitted along with the preceding '_'.  When the
3354          * script is empty, the script value is omitted along with the preceding '_'.
3355          * If all of the values are empty strings, then <code>baseName</code>
3356          * is returned.
3357          *
3358          * <p>For example, if <code>baseName</code> is
3359          * <code>"baseName"</code> and <code>locale</code> is
3360          * <code>Locale("ja",&nbsp;"",&nbsp;"XX")</code>, then
3361          * <code>"baseName_ja_&thinsp;_XX"</code> is returned. If the given
3362          * locale is <code>Locale("en")</code>, then
3363          * <code>"baseName_en"</code> is returned.
3364          *
3365          * <p>Overriding this method allows applications to use different
3366          * conventions in the organization and packaging of localized
3367          * resources.
3368          *
3369          * @param baseName
3370          *        the base name of the resource bundle, a fully
3371          *        qualified class name
3372          * @param locale
3373          *        the locale for which a resource bundle should be
3374          *        loaded
3375          * @return the bundle name for the resource bundle
3376          * @exception NullPointerException
3377          *        if <code>baseName</code> or <code>locale</code>
3378          *        is <code>null</code>
3379          * @see java.util.spi.AbstractResourceBundleProvider#toBundleName(String, Locale)
3380          */
3381         public String toBundleName(String baseName, Locale locale) {
3382             if (locale == Locale.ROOT) {
3383                 return baseName;
3384             }
3385 
3386             String language = locale.getLanguage();
3387             String script = locale.getScript();
3388             String country = locale.getCountry();
3389             String variant = locale.getVariant();
3390 
3391             if (language == "" && country == "" && variant == "") {
3392                 return baseName;
3393             }
3394 
3395             StringBuilder sb = new StringBuilder(baseName);
3396             sb.append('_');
3397             if (script != "") {
3398                 if (variant != "") {
3399                     sb.append(language).append('_').append(script).append('_').append(country).append('_').append(variant);
3400                 } else if (country != "") {
3401                     sb.append(language).append('_').append(script).append('_').append(country);
3402                 } else {
3403                     sb.append(language).append('_').append(script);
3404                 }
3405             } else {
3406                 if (variant != "") {
3407                     sb.append(language).append('_').append(country).append('_').append(variant);
3408                 } else if (country != "") {
3409                     sb.append(language).append('_').append(country);
3410                 } else {
3411                     sb.append(language);
3412                 }
3413             }
3414             return sb.toString();
3415 
3416         }
3417 
3418         /**
3419          * Converts the given <code>bundleName</code> to the form required
3420          * by the {@link ClassLoader#getResource ClassLoader.getResource}
3421          * method by replacing all occurrences of <code>'.'</code> in
3422          * <code>bundleName</code> with <code>'/'</code> and appending a
3423          * <code>'.'</code> and the given file <code>suffix</code>. For
3424          * example, if <code>bundleName</code> is
3425          * <code>"foo.bar.MyResources_ja_JP"</code> and <code>suffix</code>
3426          * is <code>"properties"</code>, then
3427          * <code>"foo/bar/MyResources_ja_JP.properties"</code> is returned.
3428          *
3429          * @param bundleName
3430          *        the bundle name
3431          * @param suffix
3432          *        the file type suffix
3433          * @return the converted resource name
3434          * @exception NullPointerException
3435          *         if <code>bundleName</code> or <code>suffix</code>
3436          *         is <code>null</code>
3437          */
3438         public final String toResourceName(String bundleName, String suffix) {
3439             StringBuilder sb = new StringBuilder(bundleName.length() + 1 + suffix.length());
3440             sb.append(bundleName.replace('.', '/')).append('.').append(suffix);
3441             return sb.toString();
3442         }
3443 
3444         private String toResourceName0(String bundleName, String suffix) {
3445             // application protocol check
3446             if (bundleName.contains("://")) {
3447                 return null;
3448             } else {
3449                 return toResourceName(bundleName, suffix);
3450             }
3451         }
3452     }
3453 
3454     @SuppressWarnings("unchecked")
3455     private static <T extends Throwable> void uncheckedThrow(Throwable t) throws T {
3456         if (t != null)
3457             throw (T)t;
3458         else
3459             throw new Error("Unknown Exception");
3460     }
3461 
3462     private static class SingleFormatControl extends Control {
3463         private static final Control PROPERTIES_ONLY
3464             = new SingleFormatControl(FORMAT_PROPERTIES);
3465 
3466         private static final Control CLASS_ONLY
3467             = new SingleFormatControl(FORMAT_CLASS);
3468 
3469         private final List<String> formats;
3470 
3471         protected SingleFormatControl(List<String> formats) {
3472             this.formats = formats;
3473         }
3474 
3475         public List<String> getFormats(String baseName) {
3476             if (baseName == null) {
3477                 throw new NullPointerException();
3478             }
3479             return formats;
3480         }
3481     }
3482 
3483     private static final class NoFallbackControl extends SingleFormatControl {
3484         private static final Control NO_FALLBACK
3485             = new NoFallbackControl(FORMAT_DEFAULT);
3486 
3487         private static final Control PROPERTIES_ONLY_NO_FALLBACK
3488             = new NoFallbackControl(FORMAT_PROPERTIES);
3489 
3490         private static final Control CLASS_ONLY_NO_FALLBACK
3491             = new NoFallbackControl(FORMAT_CLASS);
3492 
3493         protected NoFallbackControl(List<String> formats) {
3494             super(formats);
3495         }
3496 
3497         public Locale getFallbackLocale(String baseName, Locale locale) {
3498             if (baseName == null || locale == null) {
3499                 throw new NullPointerException();
3500             }
3501             return null;
3502         }
3503     }
3504 
3505     private static class ResourceBundleProviderHelper {
3506         /**
3507          * Returns a new ResourceBundle instance of the given bundleClass
3508          */
3509         static ResourceBundle newResourceBundle(Class<? extends ResourceBundle> bundleClass) {
3510             try {
3511                 @SuppressWarnings("unchecked")
3512                 Constructor<? extends ResourceBundle> ctor =
3513                     bundleClass.getConstructor();
3514                 if (!Modifier.isPublic(ctor.getModifiers())) {
3515                     return null;
3516                 }
3517                 // java.base may not be able to read the bundleClass's module.
3518                 PrivilegedAction<Void> pa = () -> { ctor.setAccessible(true); return null;};
3519                 AccessController.doPrivileged(pa);
3520                 try {
3521                     return ctor.newInstance((Object[]) null);
3522                 } catch (InvocationTargetException e) {
3523                     uncheckedThrow(e);
3524                 } catch (InstantiationException | IllegalAccessException e) {
3525                     throw new InternalError(e);
3526                 }
3527             } catch (NoSuchMethodException e) {
3528                 throw new InternalError(e);
3529             }
3530             return null;
3531         }
3532 
3533         /**
3534          * Loads a {@code ResourceBundle} of the given {@code bundleName} local to
3535          * the given {@code module}. If not found, search the bundle class
3536          * that is visible from the module's class loader.
3537          *
3538          * The caller module is used for access check only.
3539          */
3540         static ResourceBundle loadResourceBundle(Module callerModule,
3541                                                  Module module,
3542                                                  String baseName,
3543                                                  Locale locale)
3544         {
3545             String bundleName = Control.INSTANCE.toBundleName(baseName, locale);
3546             try {
3547                 PrivilegedAction<Class<?>> pa = () -> Class.forName(module, bundleName);
3548                 Class<?> c = AccessController.doPrivileged(pa, null, GET_CLASSLOADER_PERMISSION);
3549                 trace("local in %s %s caller %s: %s%n", module, bundleName, callerModule, c);
3550 
3551                 if (c == null) {
3552                     // if not found from the given module, locate resource bundle
3553                     // that is visible to the module's class loader
3554                     ClassLoader loader = getLoader(module);
3555                     if (loader != null) {
3556                         c = Class.forName(bundleName, false, loader);
3557                     } else {
3558                         c = BootLoader.loadClassOrNull(bundleName);
3559                     }
3560                     trace("loader for %s %s caller %s: %s%n", module, bundleName, callerModule, c);
3561                 }
3562 
3563                 if (c != null && ResourceBundle.class.isAssignableFrom(c)) {
3564                     @SuppressWarnings("unchecked")
3565                     Class<ResourceBundle> bundleClass = (Class<ResourceBundle>) c;
3566                     Module m = bundleClass.getModule();
3567                     if (!isAccessible(callerModule, m, bundleClass.getPackageName())) {
3568                         trace("   %s does not have access to %s/%s%n", callerModule,
3569                               m.getName(), bundleClass.getPackageName());
3570                         return null;
3571                     }
3572 
3573                     return newResourceBundle(bundleClass);
3574                 }
3575             } catch (ClassNotFoundException e) {}
3576             return null;
3577         }
3578 
3579         /**
3580          * Tests if resources of the given package name from the given module are
3581          * open to the caller module.
3582          */
3583         static boolean isAccessible(Module callerModule, Module module, String pn) {
3584             if (!module.isNamed() || callerModule == module)
3585                 return true;
3586 
3587             return module.isOpen(pn, callerModule);
3588         }
3589 
3590         /**
3591          * Loads properties of the given {@code bundleName} local in the given
3592          * {@code module}.  If the .properties is not found or not open
3593          * to the caller module to access, it will find the resource that
3594          * is visible to the module's class loader.
3595          *
3596          * The caller module is used for access check only.
3597          */
3598         static ResourceBundle loadPropertyResourceBundle(Module callerModule,
3599                                                          Module module,
3600                                                          String baseName,
3601                                                          Locale locale)
3602             throws IOException
3603         {
3604             String bundleName = Control.INSTANCE.toBundleName(baseName, locale);
3605 
3606             PrivilegedAction<InputStream> pa = () -> {
3607                 try {
3608                     String resourceName = Control.INSTANCE
3609                         .toResourceName0(bundleName, "properties");
3610                     if (resourceName == null) {
3611                         return null;
3612                     }
3613                     trace("local in %s %s caller %s%n", module, resourceName, callerModule);
3614 
3615                     // if the package is in the given module but not opened
3616                     // locate it from the given module first.
3617                     String pn = toPackageName(bundleName);
3618                     trace("   %s/%s is accessible to %s : %s%n",
3619                             module.getName(), pn, callerModule,
3620                             isAccessible(callerModule, module, pn));
3621                     if (isAccessible(callerModule, module, pn)) {
3622                         InputStream in = module.getResourceAsStream(resourceName);
3623                         if (in != null) {
3624                             return in;
3625                         }
3626                     }
3627 
3628                     ClassLoader loader = module.getClassLoader();
3629                     trace("loader for %s %s caller %s%n", module, resourceName, callerModule);
3630 
3631                     try {
3632                         if (loader != null) {
3633                             return loader.getResourceAsStream(resourceName);
3634                         } else {
3635                             URL url = BootLoader.findResource(resourceName);
3636                             if (url != null) {
3637                                 return url.openStream();
3638                             }
3639                         }
3640                     } catch (Exception e) {}
3641                     return null;
3642 
3643                 } catch (IOException e) {
3644                     throw new UncheckedIOException(e);
3645                 }
3646             };
3647 
3648             try (InputStream stream = AccessController.doPrivileged(pa)) {
3649                 if (stream != null) {
3650                     return new PropertyResourceBundle(stream);
3651                 } else {
3652                     return null;
3653                 }
3654             } catch (UncheckedIOException e) {
3655                 throw e.getCause();
3656             }
3657         }
3658 
3659         private static String toPackageName(String bundleName) {
3660             int i = bundleName.lastIndexOf('.');
3661             return i != -1 ? bundleName.substring(0, i) : "";
3662         }
3663 
3664     }
3665 
3666     private static final boolean TRACE_ON = Boolean.valueOf(
3667         GetPropertyAction.privilegedGetProperty("resource.bundle.debug", "false"));
3668 
3669     private static void trace(String format, Object... params) {
3670         if (TRACE_ON)
3671             System.out.format(format, params);
3672     }
3673 }