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