rev 16532 : [mq]: 8172365

   1 /*
   2  * Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
  28  * (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved
  29  *
  30  * The original version of this source code and documentation
  31  * is copyrighted and owned by Taligent, Inc., a wholly-owned
  32  * subsidiary of IBM. These materials are provided under terms
  33  * of a License Agreement between Taligent and Sun. This technology
  34  * is protected by multiple US and International patents.
  35  *
  36  * This notice and attribution to Taligent may not be removed.
  37  * Taligent is a registered trademark of Taligent, Inc.
  38  *
  39  */
  40 
  41 package java.util;
  42 
  43 import java.io.IOException;
  44 import java.io.InputStream;
  45 import java.io.UncheckedIOException;
  46 import java.lang.ref.Reference;
  47 import java.lang.ref.ReferenceQueue;
  48 import java.lang.ref.SoftReference;
  49 import java.lang.ref.WeakReference;
  50 import java.lang.reflect.Constructor;
  51 import java.lang.reflect.InvocationTargetException;
  52 import java.lang.reflect.Modifier;
  53 import java.lang.reflect.Module;
  54 import java.net.JarURLConnection;
  55 import java.net.URL;
  56 import java.net.URLConnection;
  57 import java.security.AccessController;
  58 import java.security.PrivilegedAction;
  59 import java.security.PrivilegedActionException;
  60 import java.security.PrivilegedExceptionAction;
  61 import java.util.concurrent.ConcurrentHashMap;
  62 import java.util.concurrent.ConcurrentMap;
  63 import java.util.jar.JarEntry;

  64 import java.util.spi.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  * </li>
 236  * </ul>
 237  *
 238  * <h3><a name="RBP_support">ResourceBundleProvider Service Providers</a></h3>
 239  *
 240  * The {@code getBundle} factory methods load service providers of
 241  * {@link ResourceBundleProvider}, if available, using {@link ServiceLoader}.
 242  * The service type is designated by {@code basename+"Provider"}. For
 243  * example, if the base name is "{@code com.example.app.MyResources}", the service
 244  * type is {@code com.example.app.MyResourcesProvider}.
 245  * <p>
 246  * In named modules, the loaded service providers for the given base name are
 247  * used to load resource bundles. If no service provider is available, or if
 248  * none of the service providers returns a resource bundle and the caller module
 249  * doesn't have its own service provider, the {@code getBundle} factory method
 250  * searches for resource bundles that are local in the caller module and that
 251  * are visible to the class loader of the caller module.  The resource bundle
 252  * formats for local module searching are "java.class" and "java.properties".
 253  *
 254  * <h3>ResourceBundle.Control</h3>
 255  *
 256  * The {@link ResourceBundle.Control} class provides information necessary
 257  * to perform the bundle loading process by the <code>getBundle</code>
 258  * factory methods that take a <code>ResourceBundle.Control</code>
 259  * instance. You can implement your own subclass in order to enable
 260  * non-standard resource bundle formats, change the search strategy, or
 261  * define caching parameters. Refer to the descriptions of the class and the
 262  * {@link #getBundle(String, Locale, ClassLoader, Control) getBundle}
 263  * factory method for details.
 264  *












 265  * <h3>Cache Management</h3>
 266  *
 267  * Resource bundle instances created by the <code>getBundle</code> factory
 268  * methods are cached by default, and the factory methods return the same
 269  * resource bundle instance multiple times if it has been
 270  * cached. <code>getBundle</code> clients may clear the cache, manage the
 271  * lifetime of cached resource bundle instances using time-to-live values,
 272  * or specify not to cache resource bundle instances. Refer to the
 273  * descriptions of the {@linkplain #getBundle(String, Locale, ClassLoader,
 274  * Control) <code>getBundle</code> factory method}, {@link
 275  * #clearCache(ClassLoader) clearCache}, {@link
 276  * Control#getTimeToLive(String, Locale)
 277  * ResourceBundle.Control.getTimeToLive}, and {@link
 278  * Control#needsReload(String, Locale, String, ClassLoader, ResourceBundle,
 279  * long) ResourceBundle.Control.needsReload} for details.
 280  *
 281  * <h3>Example</h3>
 282  *
 283  * The following is a very simple example of a <code>ResourceBundle</code>
 284  * subclass, <code>MyResources</code>, that manages two resources (for a larger number of
 285  * resources you would probably use a <code>Map</code>).
 286  * Notice that you don't need to supply a value if
 287  * a "parent-level" <code>ResourceBundle</code> handles the same
 288  * key with the same value (as for the okKey below).
 289  * <blockquote>
 290  * <pre>
 291  * // default (English language, United States)
 292  * public class MyResources extends ResourceBundle {
 293  *     public Object handleGetObject(String key) {
 294  *         if (key.equals("okKey")) return "Ok";
 295  *         if (key.equals("cancelKey")) return "Cancel";
 296  *         return null;
 297  *     }
 298  *
 299  *     public Enumeration&lt;String&gt; getKeys() {
 300  *         return Collections.enumeration(keySet());
 301  *     }
 302  *
 303  *     // Overrides handleKeySet() so that the getKeys() implementation
 304  *     // can rely on the keySet() value.
 305  *     protected Set&lt;String&gt; handleKeySet() {
 306  *         return new HashSet&lt;String&gt;(Arrays.asList("okKey", "cancelKey"));
 307  *     }
 308  * }
 309  *
 310  * // German language
 311  * public class MyResources_de extends MyResources {
 312  *     public Object handleGetObject(String key) {
 313  *         // don't need okKey, since parent level handles it.
 314  *         if (key.equals("cancelKey")) return "Abbrechen";
 315  *         return null;
 316  *     }
 317  *
 318  *     protected Set&lt;String&gt; handleKeySet() {
 319  *         return new HashSet&lt;String&gt;(Arrays.asList("cancelKey"));
 320  *     }
 321  * }
 322  * </pre>
 323  * </blockquote>
 324  * You do not have to restrict yourself to using a single family of
 325  * <code>ResourceBundle</code>s. For example, you could have a set of bundles for
 326  * exception messages, <code>ExceptionResources</code>
 327  * (<code>ExceptionResources_fr</code>, <code>ExceptionResources_de</code>, ...),
 328  * and one for widgets, <code>WidgetResource</code> (<code>WidgetResources_fr</code>,
 329  * <code>WidgetResources_de</code>, ...); breaking up the resources however you like.
 330  *
 331  * @see ListResourceBundle
 332  * @see PropertyResourceBundle
 333  * @see MissingResourceException
 334  * @see ResourceBundleProvider
 335  * @since 1.1
 336  */
 337 public abstract class ResourceBundle {
 338 
 339     /** initial size of the bundle cache */
 340     private static final int INITIAL_CACHE_SIZE = 32;
 341 
 342     static {
 343         SharedSecrets.setJavaUtilResourceBundleAccess(
 344             new JavaUtilResourceBundleAccess() {
 345                 @Override
 346                 public void setParent(ResourceBundle bundle,
 347                                       ResourceBundle parent) {
 348                     bundle.setParent(parent);
 349                 }
 350 
 351                 @Override
 352                 public ResourceBundle getParent(ResourceBundle bundle) {
 353                     return bundle.parent;
 354                 }
 355 
 356                 @Override
 357                 public void setLocale(ResourceBundle bundle, Locale locale) {
 358                     bundle.locale = locale;
 359                 }
 360 
 361                 @Override
 362                 public void setName(ResourceBundle bundle, String name) {
 363                     bundle.name = name;
 364                 }
 365 
 366                 @Override
 367                 public ResourceBundle getBundle(String baseName, Locale locale, Module module) {
 368                     // use the given module as the caller to bypass the access check
 369                     return getBundleImpl(module, module,
 370                                          baseName, locale, Control.INSTANCE);

 371                 }
 372 
 373                 @Override
 374                 public ResourceBundle newResourceBundle(Class<? extends ResourceBundle> bundleClass) {
 375                     return ResourceBundleProviderHelper.newResourceBundle(bundleClass);
 376                 }
 377             });
 378     }
 379 
 380     /** constant indicating that no resource bundle exists */
 381     private static final ResourceBundle NONEXISTENT_BUNDLE = new ResourceBundle() {
 382             public Enumeration<String> getKeys() { return null; }
 383             protected Object handleGetObject(String key) { return null; }
 384             public String toString() { return "NONEXISTENT_BUNDLE"; }
 385         };
 386 
 387 
 388     /**
 389      * The cache is a map from cache keys (with bundle base name, locale, and
 390      * class loader) to either a resource bundle or NONEXISTENT_BUNDLE wrapped by a
 391      * BundleReference.
 392      *
 393      * The cache is a ConcurrentMap, allowing the cache to be searched
 394      * concurrently by multiple threads.  This will also allow the cache keys
 395      * to be reclaimed along with the ClassLoaders they reference.
 396      *
 397      * This variable would be better named "cache", but we keep the old
 398      * name for compatibility with some workarounds for bug 4212439.
 399      */
 400     private static final ConcurrentMap<CacheKey, BundleReference> cacheList
 401         = new ConcurrentHashMap<>(INITIAL_CACHE_SIZE);
 402 
 403     /**
 404      * Queue for reference objects referring to class loaders or bundles.
 405      */
 406     private static final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
 407 
 408     /**
 409      * Returns the base name of this bundle, if known, or {@code null} if unknown.
 410      *
 411      * If not null, then this is the value of the {@code baseName} parameter
 412      * that was passed to the {@code ResourceBundle.getBundle(...)} method
 413      * when the resource bundle was loaded.
 414      *
 415      * @return The base name of the resource bundle, as provided to and expected
 416      * by the {@code ResourceBundle.getBundle(...)} methods.
 417      *
 418      * @see #getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader)
 419      *
 420      * @since 1.8
 421      */
 422     public String getBaseBundleName() {
 423         return name;
 424     }
 425 
 426     /**
 427      * The parent bundle of this bundle.
 428      * The parent bundle is searched by {@link #getObject getObject}
 429      * when this bundle does not contain a particular resource.
 430      */
 431     protected ResourceBundle parent = null;
 432 
 433     /**
 434      * The locale for this bundle.
 435      */
 436     private Locale locale = null;
 437 
 438     /**
 439      * The base bundle name for this bundle.
 440      */
 441     private String name;
 442 
 443     /**
 444      * The flag indicating this bundle has expired in the cache.
 445      */
 446     private volatile boolean expired;
 447 
 448     /**
 449      * The back link to the cache key. null if this bundle isn't in
 450      * the cache (yet) or has expired.
 451      */
 452     private volatile CacheKey cacheKey;
 453 
 454     /**
 455      * A Set of the keys contained only in this ResourceBundle.
 456      */
 457     private volatile Set<String> keySet;
 458 
 459     /**
 460      * Sole constructor.  (For invocation by subclass constructors, typically
 461      * implicit.)
 462      */
 463     public ResourceBundle() {
 464     }
 465 
 466     /**
 467      * Gets a string for the given key from this resource bundle or one of its parents.
 468      * Calling this method is equivalent to calling
 469      * <blockquote>
 470      * <code>(String) {@link #getObject(java.lang.String) getObject}(key)</code>.
 471      * </blockquote>
 472      *
 473      * @param key the key for the desired string
 474      * @exception NullPointerException if <code>key</code> is <code>null</code>
 475      * @exception MissingResourceException if no object for the given key can be found
 476      * @exception ClassCastException if the object found for the given key is not a string
 477      * @return the string for the given key
 478      */
 479     public final String getString(String key) {
 480         return (String) getObject(key);
 481     }
 482 
 483     /**
 484      * Gets a string array for the given key from this resource bundle or one of its parents.
 485      * Calling this method is equivalent to calling
 486      * <blockquote>
 487      * <code>(String[]) {@link #getObject(java.lang.String) getObject}(key)</code>.
 488      * </blockquote>
 489      *
 490      * @param key the key for the desired string array
 491      * @exception NullPointerException if <code>key</code> is <code>null</code>
 492      * @exception MissingResourceException if no object for the given key can be found
 493      * @exception ClassCastException if the object found for the given key is not a string array
 494      * @return the string array for the given key
 495      */
 496     public final String[] getStringArray(String key) {
 497         return (String[]) getObject(key);
 498     }
 499 
 500     /**
 501      * Gets an object for the given key from this resource bundle or one of its parents.
 502      * This method first tries to obtain the object from this resource bundle using
 503      * {@link #handleGetObject(java.lang.String) handleGetObject}.
 504      * If not successful, and the parent resource bundle is not null,
 505      * it calls the parent's <code>getObject</code> method.
 506      * If still not successful, it throws a MissingResourceException.
 507      *
 508      * @param key the key for the desired object
 509      * @exception NullPointerException if <code>key</code> is <code>null</code>
 510      * @exception MissingResourceException if no object for the given key can be found
 511      * @return the object for the given key
 512      */
 513     public final Object getObject(String key) {
 514         Object obj = handleGetObject(key);
 515         if (obj == null) {
 516             if (parent != null) {
 517                 obj = parent.getObject(key);
 518             }
 519             if (obj == null) {
 520                 throw new MissingResourceException("Can't find resource for bundle "
 521                                                    +this.getClass().getName()
 522                                                    +", key "+key,
 523                                                    this.getClass().getName(),
 524                                                    key);
 525             }
 526         }
 527         return obj;
 528     }
 529 
 530     /**
 531      * Returns the locale of this resource bundle. This method can be used after a
 532      * call to getBundle() to determine whether the resource bundle returned really
 533      * corresponds to the requested locale or is a fallback.
 534      *
 535      * @return the locale of this resource bundle
 536      */
 537     public Locale getLocale() {
 538         return locale;
 539     }
 540 
 541     private static ClassLoader getLoader(Module module) {
 542         PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 543         return AccessController.doPrivileged(pa);
 544     }
 545 
 546     /**
 547      * @param module a non-null-screened module form the {@link CacheKey#getModule()}.
 548      * @return the ClassLoader to use in {@link Control#needsReload}
 549      *         and {@link Control#newBundle}
 550      */
 551     private static ClassLoader getLoaderForControl(Module module) {
 552         ClassLoader loader = getLoader(module);
 553         return loader == null ? ClassLoader.getSystemClassLoader() : loader;
 554     }
 555 
 556     /**
 557      * Sets the parent bundle of this bundle.
 558      * The parent bundle is searched by {@link #getObject getObject}
 559      * when this bundle does not contain a particular resource.
 560      *
 561      * @param parent this bundle's parent bundle.
 562      */
 563     protected void setParent(ResourceBundle parent) {
 564         assert parent != NONEXISTENT_BUNDLE;
 565         this.parent = parent;
 566     }
 567 
 568     /**
 569      * Key used for cached resource bundles.  The key checks the base
 570      * name, the locale, the bundle module, and the caller module
 571      * to determine if the resource is a match to the requested one.
 572      * The base name, the locale and both modules must have a non-null value.
 573      */
 574     private static final class CacheKey {
 575         // These four are the actual keys for lookup in Map.
 576         private final String name;
 577         private volatile Locale locale;
 578         private final KeyElementReference<Module> moduleRef;
 579         private final KeyElementReference<Module> callerRef;
 580         // this is the part of hashCode that pertains to module and callerModule
 581         // which can be GCed..
 582         private final int modulesHash;
 583 
 584         // bundle format which is necessary for calling
 585         // Control.needsReload().
 586         private volatile String format;
 587 
 588         // These time values are in CacheKey so that NONEXISTENT_BUNDLE
 589         // doesn't need to be cloned for caching.
 590 
 591         // The time when the bundle has been loaded
 592         private volatile long loadTime;
 593 
 594         // The time when the bundle expires in the cache, or either
 595         // Control.TTL_DONT_CACHE or Control.TTL_NO_EXPIRATION_CONTROL.
 596         private volatile long expirationTime;
 597 
 598         // Placeholder for an error report by a Throwable
 599         private volatile Throwable cause;
 600 
 601         // ResourceBundleProviders for loading ResourceBundles
 602         private volatile ServiceLoader<ResourceBundleProvider> providers;
 603         private volatile boolean providersChecked;
 604 
 605         // Boolean.TRUE if the factory method caller provides a ResourceBundleProvier.
 606         private volatile Boolean callerHasProvider;
 607 
 608         CacheKey(String baseName, Locale locale, Module module, Module caller) {
 609             Objects.requireNonNull(module);
 610             Objects.requireNonNull(caller);
 611 
 612             this.name = baseName;
 613             this.locale = locale;
 614             this.moduleRef = new KeyElementReference<>(module, referenceQueue, this);
 615             this.callerRef = new KeyElementReference<>(caller, referenceQueue, this);
 616             this.modulesHash = module.hashCode() ^ caller.hashCode();
 617         }
 618 
 619         CacheKey(CacheKey src) {
 620             // Create References to src's modules
 621             this.moduleRef = new KeyElementReference<>(
 622                 Objects.requireNonNull(src.getModule()), referenceQueue, this);
 623             this.callerRef = new KeyElementReference<>(
 624                 Objects.requireNonNull(src.getCallerModule()), referenceQueue, this);
 625             // Copy fields from src. ResourceBundleProviders related fields
 626             // and "cause" should not be copied.
 627             this.name = src.name;
 628             this.locale = src.locale;
 629             this.modulesHash = src.modulesHash;
 630             this.format = src.format;
 631             this.loadTime = src.loadTime;
 632             this.expirationTime = src.expirationTime;
 633         }
 634 
 635         String getName() {
 636             return name;
 637         }
 638 
 639         Locale getLocale() {
 640             return locale;
 641         }
 642 
 643         CacheKey setLocale(Locale locale) {
 644             this.locale = locale;
 645             return this;
 646         }
 647 
 648         Module getModule() {
 649             return moduleRef.get();
 650         }
 651 
 652         Module getCallerModule() {
 653             return callerRef.get();
 654         }
 655 
 656         ServiceLoader<ResourceBundleProvider> getProviders() {
 657             if (!providersChecked) {
 658                 providers = getServiceLoader(getModule(), name);
 659                 providersChecked = true;
 660             }
 661             return providers;
 662         }
 663 
 664         boolean hasProviders() {
 665             return getProviders() != null;
 666         }
 667 
 668         boolean callerHasProvider() {
 669             return callerHasProvider == Boolean.TRUE;
 670         }
 671 
 672         @Override
 673         public boolean equals(Object other) {
 674             if (this == other) {
 675                 return true;
 676             }
 677             try {
 678                 final CacheKey otherEntry = (CacheKey)other;
 679                 //quick check to see if they are not equal
 680                 if (modulesHash != otherEntry.modulesHash) {
 681                     return false;
 682                 }
 683                 //are the names the same?
 684                 if (!name.equals(otherEntry.name)) {
 685                     return false;
 686                 }
 687                 // are the locales the same?
 688                 if (!locale.equals(otherEntry.locale)) {
 689                     return false;
 690                 }
 691                 // are modules and callerModules the same and non-null?
 692                 Module module = getModule();
 693                 Module caller = getCallerModule();
 694                 return ((module != null) && (module.equals(otherEntry.getModule())) &&
 695                         (caller != null) && (caller.equals(otherEntry.getCallerModule())));
 696             } catch (NullPointerException | ClassCastException e) {
 697             }
 698             return false;
 699         }
 700 
 701         @Override
 702         public int hashCode() {
 703             return (name.hashCode() << 3) ^ locale.hashCode() ^ modulesHash;
 704         }
 705 
 706         String getFormat() {
 707             return format;
 708         }
 709 
 710         void setFormat(String format) {
 711             this.format = format;
 712         }
 713 
 714         private void setCause(Throwable cause) {
 715             if (this.cause == null) {
 716                 this.cause = cause;
 717             } else {
 718                 // Override the cause if the previous one is
 719                 // ClassNotFoundException.
 720                 if (this.cause instanceof ClassNotFoundException) {
 721                     this.cause = cause;
 722                 }
 723             }
 724         }
 725 
 726         private Throwable getCause() {
 727             return cause;
 728         }
 729 
 730         @Override
 731         public String toString() {
 732             String l = locale.toString();
 733             if (l.length() == 0) {
 734                 if (locale.getVariant().length() != 0) {
 735                     l = "__" + locale.getVariant();
 736                 } else {
 737                     l = "\"\"";
 738                 }
 739             }
 740             return "CacheKey[" + name +
 741                    ", locale=" + l +
 742                    ", module=" + getModule() +
 743                    ", callerModule=" + getCallerModule() +
 744                    ", format=" + format +
 745                    "]";
 746         }
 747     }
 748 
 749     /**
 750      * The common interface to get a CacheKey in LoaderReference and
 751      * BundleReference.
 752      */
 753     private static interface CacheKeyReference {
 754         public CacheKey getCacheKey();
 755     }
 756 
 757     /**
 758      * References to a CacheKey element as a WeakReference so that it can be
 759      * garbage collected when nobody else is using it.
 760      */
 761     private static class KeyElementReference<T> extends WeakReference<T>
 762                                                 implements CacheKeyReference {
 763         private final CacheKey cacheKey;
 764 
 765         KeyElementReference(T referent, ReferenceQueue<Object> q, CacheKey key) {
 766             super(referent, q);
 767             cacheKey = key;
 768         }
 769 
 770         @Override
 771         public CacheKey getCacheKey() {
 772             return cacheKey;
 773         }
 774     }
 775 
 776     /**
 777      * References to bundles are soft references so that they can be garbage
 778      * collected when they have no hard references.
 779      */
 780     private static class BundleReference extends SoftReference<ResourceBundle>
 781                                          implements CacheKeyReference {
 782         private final CacheKey cacheKey;
 783 
 784         BundleReference(ResourceBundle referent, ReferenceQueue<Object> q, CacheKey key) {
 785             super(referent, q);
 786             cacheKey = key;
 787         }
 788 
 789         @Override
 790         public CacheKey getCacheKey() {
 791             return cacheKey;
 792         }
 793     }
 794 
 795     /**
 796      * Gets a resource bundle using the specified base name, the default locale,
 797      * and the caller's class loader. Calling this method is equivalent to calling
 798      * <blockquote>
 799      * <code>getBundle(baseName, Locale.getDefault(), this.getClass().getClassLoader())</code>,
 800      * </blockquote>
 801      * except that <code>getClassLoader()</code> is run with the security
 802      * privileges of <code>ResourceBundle</code>.
 803      * See {@link #getBundle(String, Locale, ClassLoader) getBundle}
 804      * for a complete description of the search and instantiation strategy.
 805      *
 806      * @param baseName the base name of the resource bundle, a fully qualified class name
 807      * @exception java.lang.NullPointerException
 808      *     if <code>baseName</code> is <code>null</code>
 809      * @exception MissingResourceException
 810      *     if no resource bundle for the specified base name can be found
 811      * @return a resource bundle for the given base name and the default locale
 812      */
 813     @CallerSensitive
 814     public static final ResourceBundle getBundle(String baseName)
 815     {
 816         Class<?> caller = Reflection.getCallerClass();
 817         return getBundleImpl(baseName, Locale.getDefault(),
 818                              caller, Control.INSTANCE);
 819     }
 820 
 821     /**
 822      * Returns a resource bundle using the specified base name, the
 823      * default locale and the specified control. Calling this method
 824      * is equivalent to calling
 825      * <pre>
 826      * getBundle(baseName, Locale.getDefault(),
 827      *           this.getClass().getClassLoader(), control),
 828      * </pre>
 829      * except that <code>getClassLoader()</code> is run with the security
 830      * privileges of <code>ResourceBundle</code>.  See {@link
 831      * #getBundle(String, Locale, ClassLoader, Control) getBundle} for the
 832      * complete description of the resource bundle loading process with a
 833      * <code>ResourceBundle.Control</code>.
 834      *
 835      * @param baseName
 836      *        the base name of the resource bundle, a fully qualified class
 837      *        name
 838      * @param control
 839      *        the control which gives information for the resource bundle
 840      *        loading process
 841      * @return a resource bundle for the given base name and the default locale
 842      * @throws NullPointerException
 843      *         if <code>baseName</code> or <code>control</code> is
 844      *         <code>null</code>
 845      * @throws MissingResourceException
 846      *         if no resource bundle for the specified base name can be found
 847      * @throws IllegalArgumentException
 848      *         if the given <code>control</code> doesn't perform properly
 849      *         (e.g., <code>control.getCandidateLocales</code> returns null.)
 850      *         Note that validation of <code>control</code> is performed as
 851      *         needed.
 852      * @throws UnsupportedOperationException
 853      *         if this method is called in a named module
 854      * @since 1.6
 855      */
 856     @CallerSensitive
 857     public static final ResourceBundle getBundle(String baseName,
 858                                                  Control control) {
 859         Class<?> caller = Reflection.getCallerClass();
 860         Locale targetLocale = Locale.getDefault();
 861         checkNamedModule(caller);
 862         return getBundleImpl(baseName, targetLocale, caller, control);
 863     }
 864 
 865     /**
 866      * Gets a resource bundle using the specified base name and locale,
 867      * and the caller's class loader. Calling this method is equivalent to calling
 868      * <blockquote>
 869      * <code>getBundle(baseName, locale, this.getClass().getClassLoader())</code>,
 870      * </blockquote>
 871      * except that <code>getClassLoader()</code> is run with the security
 872      * privileges of <code>ResourceBundle</code>.
 873      * See {@link #getBundle(String, Locale, ClassLoader) getBundle}
 874      * for a complete description of the search and instantiation strategy.
 875      *
 876      * @param baseName
 877      *        the base name of the resource bundle, a fully qualified class name
 878      * @param locale
 879      *        the locale for which a resource bundle is desired
 880      * @exception NullPointerException
 881      *        if <code>baseName</code> or <code>locale</code> is <code>null</code>
 882      * @exception MissingResourceException
 883      *        if no resource bundle for the specified base name can be found
 884      * @return a resource bundle for the given base name and locale
 885      */
 886     @CallerSensitive
 887     public static final ResourceBundle getBundle(String baseName,
 888                                                  Locale locale)
 889     {
 890         Class<?> caller = Reflection.getCallerClass();
 891         return getBundleImpl(baseName, locale,
 892                              caller, Control.INSTANCE);
 893     }
 894 
 895     /**
 896      * Gets a resource bundle using the specified base name and the default locale
 897      * on behalf of the specified module. This method is equivalent to calling
 898      * <blockquote>
 899      * <code>getBundle(baseName, Locale.getDefault(), module)</code>
 900      * </blockquote>
 901      *
 902      * <p> Resource bundles in named modules may be encapsulated.  When
 903      * the resource bundle is loaded from a provider, the caller module
 904      * must have an appropriate <i>uses</i> clause in its <i>module descriptor</i>
 905      * to declare that the module uses implementations of {@code "baseName"Provider}.
 906      * When the resource bundle is loaded from the specified module, it is
 907      * subject to the encapsulation rules specified by
 908      * {@link Module#getResourceAsStream Module.getResourceAsStream}.
 909      *
 910      * @param baseName the base name of the resource bundle,
 911      *                 a fully qualified class name
 912      * @param module   the module for which the resource bundle is searched
 913      * @throws NullPointerException
 914      *         if {@code baseName} or {@code module} is {@code null}
 915      * @throws SecurityException
 916      *         if a security manager exists and the caller is not the specified
 917      *         module and doesn't have {@code RuntimePermission("getClassLoader")}
 918      * @throws MissingResourceException
 919      *         if no resource bundle for the specified base name can be found in the
 920      *         specified module
 921      * @return a resource bundle for the given base name and the default locale
 922      * @since 9
 923      * @see ResourceBundleProvider
 924      */
 925     @CallerSensitive
 926     public static ResourceBundle getBundle(String baseName, Module module) {
 927         return getBundleFromModule(Reflection.getCallerClass(), module, baseName,
 928                                    Locale.getDefault(), Control.INSTANCE);

 929     }
 930 
 931     /**
 932      * Gets a resource bundle using the specified base name and locale
 933      * on behalf of the specified module.
 934      *
 935      * <p> Resource bundles in named modules may be encapsulated.  When
 936      * the resource bundle is loaded from a provider, the caller module
 937      * must have an appropriate <i>uses</i> clause in its <i>module descriptor</i>
 938      * to declare that the module uses implementations of {@code "baseName"Provider}.
 939      * When the resource bundle is loaded from the specified module, it is
 940      * subject to the encapsulation rules specified by
 941      * {@link Module#getResourceAsStream Module.getResourceAsStream}.
 942      *
 943      * <p>
 944      * If the given {@code module} is a named module, this method will
 945      * load the service providers for {@link java.util.spi.ResourceBundleProvider}
 946      * and also resource bundles that are local in the given module or that
 947      * are visible to the class loader of the given module (refer to the
 948      * <a href="#bundleprovider">Resource Bundles in Named Modules</a> section
 949      * for details).
 950      *
 951      * <p>
 952      * If the given {@code module} is an unnamed module, then this method is
 953      * equivalent to calling {@link #getBundle(String, Locale, ClassLoader)
 954      * getBundle(baseName, targetLocale, module.getClassLoader()} to load
 955      * resource bundles that are visible to the class loader of the given
 956      * unnamed module.
 957      *
 958      * @param baseName the base name of the resource bundle,
 959      *                 a fully qualified class name
 960      * @param targetLocale the locale for which a resource bundle is desired
 961      * @param module   the module for which the resource bundle is searched
 962      * @throws NullPointerException
 963      *         if {@code baseName}, {@code targetLocale}, or {@code module} is
 964      *         {@code null}
 965      * @throws SecurityException
 966      *         if a security manager exists and the caller is not the specified
 967      *         module and doesn't have {@code RuntimePermission("getClassLoader")}
 968      * @throws MissingResourceException
 969      *         if no resource bundle for the specified base name and locale can
 970      *         be found in the specified {@code module}
 971      * @return a resource bundle for the given base name and locale in the module
 972      * @since 9
 973      */
 974     @CallerSensitive
 975     public static ResourceBundle getBundle(String baseName, Locale targetLocale, Module module) {
 976         return getBundleFromModule(Reflection.getCallerClass(), module, baseName, targetLocale,
 977                                    Control.INSTANCE);
 978     }
 979 
 980     /**
 981      * Returns a resource bundle using the specified base name, target
 982      * locale and control, and the caller's class loader. Calling this
 983      * method is equivalent to calling
 984      * <pre>
 985      * getBundle(baseName, targetLocale, this.getClass().getClassLoader(),
 986      *           control),
 987      * </pre>
 988      * except that <code>getClassLoader()</code> is run with the security
 989      * privileges of <code>ResourceBundle</code>.  See {@link
 990      * #getBundle(String, Locale, ClassLoader, Control) getBundle} for the
 991      * complete description of the resource bundle loading process with a
 992      * <code>ResourceBundle.Control</code>.
 993      *
 994      * @param baseName
 995      *        the base name of the resource bundle, a fully qualified
 996      *        class name
 997      * @param targetLocale
 998      *        the locale for which a resource bundle is desired
 999      * @param control
1000      *        the control which gives information for the resource
1001      *        bundle loading process
1002      * @return a resource bundle for the given base name and a
1003      *         <code>Locale</code> in <code>locales</code>
1004      * @throws NullPointerException
1005      *         if <code>baseName</code>, <code>locales</code> or
1006      *         <code>control</code> is <code>null</code>
1007      * @throws MissingResourceException
1008      *         if no resource bundle for the specified base name in any
1009      *         of the <code>locales</code> can be found.
1010      * @throws IllegalArgumentException
1011      *         if the given <code>control</code> doesn't perform properly
1012      *         (e.g., <code>control.getCandidateLocales</code> returns null.)
1013      *         Note that validation of <code>control</code> is performed as
1014      *         needed.
1015      * @throws UnsupportedOperationException
1016      *         if this method is called in a named module
1017      * @since 1.6
1018      */
1019     @CallerSensitive
1020     public static final ResourceBundle getBundle(String baseName, Locale targetLocale,
1021                                                  Control control) {
1022         Class<?> caller = Reflection.getCallerClass();
1023         checkNamedModule(caller);
1024         return getBundleImpl(baseName, targetLocale, caller, control);
1025     }
1026 
1027     /**
1028      * Gets a resource bundle using the specified base name, locale, and class
1029      * loader.
1030      *
1031      * <p>This method behaves the same as calling
1032      * {@link #getBundle(String, Locale, ClassLoader, Control)} passing a
1033      * default instance of {@link Control}.



1034      *
1035      * <p><a name="default_behavior">The following describes the default
1036      * behavior</a>.
1037      *
1038      * <p>
1039      * Resource bundles in a named module are private to that module.  If
1040      * the caller is in a named module, this method will find resource bundles
1041      * from the service providers of {@link java.util.spi.ResourceBundleProvider}
1042      * and also find resource bundles that are in the caller's module or
1043      * that are visible to the given class loader.
1044      * If the caller is in a named module and the given {@code loader} is
1045      * different than the caller's class loader, or if the caller is not in
1046      * a named module, this method will not find resource bundles from named
1047      * modules.
1048      *
1049      * <p><code>getBundle</code> uses the base name, the specified locale, and
1050      * the default locale (obtained from {@link java.util.Locale#getDefault()
1051      * Locale.getDefault}) to generate a sequence of <a
1052      * name="candidates"><em>candidate bundle names</em></a>.  If the specified
1053      * locale's language, script, country, and variant are all empty strings,
1054      * then the base name is the only candidate bundle name.  Otherwise, a list
1055      * of candidate locales is generated from the attribute values of the
1056      * specified locale (language, script, country and variant) and appended to
1057      * the base name.  Typically, this will look like the following:
1058      *
1059      * <pre>
1060      *     baseName + "_" + language + "_" + script + "_" + country + "_" + variant
1061      *     baseName + "_" + language + "_" + script + "_" + country
1062      *     baseName + "_" + language + "_" + script
1063      *     baseName + "_" + language + "_" + country + "_" + variant
1064      *     baseName + "_" + language + "_" + country
1065      *     baseName + "_" + language
1066      * </pre>
1067      *
1068      * <p>Candidate bundle names where the final component is an empty string
1069      * are omitted, along with the underscore.  For example, if country is an
1070      * empty string, the second and the fifth candidate bundle names above
1071      * would be omitted.  Also, if script is an empty string, the candidate names
1072      * including script are omitted.  For example, a locale with language "de"
1073      * and variant "JAVA" will produce candidate names with base name
1074      * "MyResource" below.
1075      *
1076      * <pre>
1077      *     MyResource_de__JAVA
1078      *     MyResource_de
1079      * </pre>
1080      *
1081      * In the case that the variant contains one or more underscores ('_'), a
1082      * sequence of bundle names generated by truncating the last underscore and
1083      * the part following it is inserted after a candidate bundle name with the
1084      * original variant.  For example, for a locale with language "en", script
1085      * "Latn, country "US" and variant "WINDOWS_VISTA", and bundle base name
1086      * "MyResource", the list of candidate bundle names below is generated:
1087      *
1088      * <pre>
1089      * MyResource_en_Latn_US_WINDOWS_VISTA
1090      * MyResource_en_Latn_US_WINDOWS
1091      * MyResource_en_Latn_US
1092      * MyResource_en_Latn
1093      * MyResource_en_US_WINDOWS_VISTA
1094      * MyResource_en_US_WINDOWS
1095      * MyResource_en_US
1096      * MyResource_en
1097      * </pre>
1098      *
1099      * <blockquote><b>Note:</b> For some <code>Locale</code>s, the list of
1100      * candidate bundle names contains extra names, or the order of bundle names
1101      * is slightly modified.  See the description of the default implementation
1102      * of {@link Control#getCandidateLocales(String, Locale)
1103      * getCandidateLocales} for details.</blockquote>
1104      *
1105      * <p><code>getBundle</code> then iterates over the candidate bundle names
1106      * to find the first one for which it can <em>instantiate</em> an actual
1107      * resource bundle. It uses the default controls' {@link Control#getFormats
1108      * getFormats} method, which generates two bundle names for each generated
1109      * name, the first a class name and the second a properties file name. For
1110      * each candidate bundle name, it attempts to create a resource bundle:
1111      *
1112      * <ul><li>First, it attempts to load a class using the generated class name.
1113      * If such a class can be found and loaded using the specified class
1114      * loader, is assignment compatible with ResourceBundle, is accessible from
1115      * ResourceBundle, and can be instantiated, <code>getBundle</code> creates a
1116      * new instance of this class and uses it as the <em>result resource
1117      * bundle</em>.
1118      *
1119      * <li>Otherwise, <code>getBundle</code> attempts to locate a property
1120      * resource file using the generated properties file name.  It generates a
1121      * path name from the candidate bundle name by replacing all "." characters
1122      * with "/" and appending the string ".properties".  It attempts to find a
1123      * "resource" with this name using {@link
1124      * java.lang.ClassLoader#getResource(java.lang.String)
1125      * ClassLoader.getResource}.  (Note that a "resource" in the sense of
1126      * <code>getResource</code> has nothing to do with the contents of a
1127      * resource bundle, it is just a container of data, such as a file.)  If it
1128      * finds a "resource", it attempts to create a new {@link
1129      * PropertyResourceBundle} instance from its contents.  If successful, this
1130      * instance becomes the <em>result resource bundle</em>.  </ul>
1131      *
1132      * <p>This continues until a result resource bundle is instantiated or the
1133      * list of candidate bundle names is exhausted.  If no matching resource
1134      * bundle is found, the default control's {@link Control#getFallbackLocale
1135      * getFallbackLocale} method is called, which returns the current default
1136      * locale.  A new sequence of candidate locale names is generated using this
1137      * locale and searched again, as above.
1138      *
1139      * <p>If still no result bundle is found, the base name alone is looked up. If
1140      * this still fails, a <code>MissingResourceException</code> is thrown.
1141      *
1142      * <p><a name="parent_chain"> Once a result resource bundle has been found,
1143      * its <em>parent chain</em> is instantiated</a>.  If the result bundle already
1144      * has a parent (perhaps because it was returned from a cache) the chain is
1145      * complete.
1146      *
1147      * <p>Otherwise, <code>getBundle</code> examines the remainder of the
1148      * candidate locale list that was used during the pass that generated the
1149      * result resource bundle.  (As before, candidate bundle names where the
1150      * final component is an empty string are omitted.)  When it comes to the
1151      * end of the candidate list, it tries the plain bundle name.  With each of the
1152      * candidate bundle names it attempts to instantiate a resource bundle (first
1153      * looking for a class and then a properties file, as described above).
1154      *
1155      * <p>Whenever it succeeds, it calls the previously instantiated resource
1156      * bundle's {@link #setParent(java.util.ResourceBundle) setParent} method
1157      * with the new resource bundle.  This continues until the list of names
1158      * is exhausted or the current bundle already has a non-null parent.
1159      *
1160      * <p>Once the parent chain is complete, the bundle is returned.
1161      *
1162      * <p><b>Note:</b> <code>getBundle</code> caches instantiated resource
1163      * bundles and might return the same resource bundle instance multiple times.
1164      *
1165      * <p><b>Note:</b>The <code>baseName</code> argument should be a fully
1166      * qualified class name. However, for compatibility with earlier versions,
1167      * Sun's Java SE Runtime Environments do not verify this, and so it is
1168      * possible to access <code>PropertyResourceBundle</code>s by specifying a
1169      * path name (using "/") instead of a fully qualified class name (using
1170      * ".").
1171      *
1172      * <p><a name="default_behavior_example">
1173      * <strong>Example:</strong></a>
1174      * <p>
1175      * The following class and property files are provided:
1176      * <pre>
1177      *     MyResources.class
1178      *     MyResources.properties
1179      *     MyResources_fr.properties
1180      *     MyResources_fr_CH.class
1181      *     MyResources_fr_CH.properties
1182      *     MyResources_en.properties
1183      *     MyResources_es_ES.class
1184      * </pre>
1185      *
1186      * The contents of all files are valid (that is, public non-abstract
1187      * subclasses of <code>ResourceBundle</code> for the ".class" files,
1188      * syntactically correct ".properties" files).  The default locale is
1189      * <code>Locale("en", "GB")</code>.
1190      *
1191      * <p>Calling <code>getBundle</code> with the locale arguments below will
1192      * instantiate resource bundles as follows:
1193      *
1194      * <table summary="getBundle() locale to resource bundle mapping">
1195      * <tr><td>Locale("fr", "CH")</td><td>MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class</td></tr>
1196      * <tr><td>Locale("fr", "FR")</td><td>MyResources_fr.properties, parent MyResources.class</td></tr>
1197      * <tr><td>Locale("de", "DE")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
1198      * <tr><td>Locale("en", "US")</td><td>MyResources_en.properties, parent MyResources.class</td></tr>
1199      * <tr><td>Locale("es", "ES")</td><td>MyResources_es_ES.class, parent MyResources.class</td></tr>
1200      * </table>
1201      *
1202      * <p>The file MyResources_fr_CH.properties is never used because it is
1203      * hidden by the MyResources_fr_CH.class. Likewise, MyResources.properties
1204      * is also hidden by MyResources.class.
1205      *
1206      * @apiNote If the caller module is a named module and the given
1207      * {@code loader} is the caller module's class loader, this method is
1208      * equivalent to {@code getBundle(baseName, locale)}; otherwise, it will not
1209      * find resource bundles from named modules.
1210      * Use {@link #getBundle(String, Locale, Module)} to load resource bundles
1211      * on behalf on a specific module instead.
1212      *
1213      * @param baseName the base name of the resource bundle, a fully qualified class name
1214      * @param locale the locale for which a resource bundle is desired
1215      * @param loader the class loader from which to load the resource bundle
1216      * @return a resource bundle for the given base name and locale
1217      * @exception java.lang.NullPointerException
1218      *        if <code>baseName</code>, <code>locale</code>, or <code>loader</code> is <code>null</code>
1219      * @exception MissingResourceException
1220      *        if no resource bundle for the specified base name can be found
1221      * @since 1.2
1222      */
1223     @CallerSensitive
1224     public static ResourceBundle getBundle(String baseName, Locale locale,
1225                                            ClassLoader loader)
1226     {
1227         if (loader == null) {
1228             throw new NullPointerException();
1229         }
1230         Class<?> caller = Reflection.getCallerClass();
1231         return getBundleImpl(baseName, locale, caller, loader, Control.INSTANCE);
1232     }
1233 
1234     /**
1235      * Returns a resource bundle using the specified base name, target
1236      * locale, class loader and control. Unlike the {@linkplain
1237      * #getBundle(String, Locale, ClassLoader) <code>getBundle</code>
1238      * factory methods with no <code>control</code> argument}, the given
1239      * <code>control</code> specifies how to locate and instantiate resource
1240      * bundles. Conceptually, the bundle loading process with the given
1241      * <code>control</code> is performed in the following steps.
1242      *
1243      * <ol>
1244      * <li>This factory method looks up the resource bundle in the cache for
1245      * the specified <code>baseName</code>, <code>targetLocale</code> and
1246      * <code>loader</code>.  If the requested resource bundle instance is
1247      * found in the cache and the time-to-live periods of the instance and
1248      * all of its parent instances have not expired, the instance is returned
1249      * to the caller. Otherwise, this factory method proceeds with the
1250      * loading process below.</li>
1251      *
1252      * <li>The {@link ResourceBundle.Control#getFormats(String)
1253      * control.getFormats} method is called to get resource bundle formats
1254      * to produce bundle or resource names. The strings
1255      * <code>"java.class"</code> and <code>"java.properties"</code>
1256      * designate class-based and {@linkplain PropertyResourceBundle
1257      * property}-based resource bundles, respectively. Other strings
1258      * starting with <code>"java."</code> are reserved for future extensions
1259      * and must not be used for application-defined formats. Other strings
1260      * designate application-defined formats.</li>
1261      *
1262      * <li>The {@link ResourceBundle.Control#getCandidateLocales(String,
1263      * Locale) control.getCandidateLocales} method is called with the target
1264      * locale to get a list of <em>candidate <code>Locale</code>s</em> for
1265      * which resource bundles are searched.</li>
1266      *
1267      * <li>The {@link ResourceBundle.Control#newBundle(String, Locale,
1268      * String, ClassLoader, boolean) control.newBundle} method is called to
1269      * instantiate a <code>ResourceBundle</code> for the base bundle name, a
1270      * candidate locale, and a format. (Refer to the note on the cache
1271      * lookup below.) This step is iterated over all combinations of the
1272      * candidate locales and formats until the <code>newBundle</code> method
1273      * returns a <code>ResourceBundle</code> instance or the iteration has
1274      * used up all the combinations. For example, if the candidate locales
1275      * are <code>Locale("de", "DE")</code>, <code>Locale("de")</code> and
1276      * <code>Locale("")</code> and the formats are <code>"java.class"</code>
1277      * and <code>"java.properties"</code>, then the following is the
1278      * sequence of locale-format combinations to be used to call
1279      * <code>control.newBundle</code>.
1280      *
1281      * <table style="width: 50%; text-align: left; margin-left: 40px;"
1282      *  border="0" cellpadding="2" cellspacing="2" summary="locale-format combinations for newBundle">
1283      * <tbody>
1284      * <tr>
1285      * <td
1286      * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;"><code>Locale</code><br>
1287      * </td>
1288      * <td
1289      * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;"><code>format</code><br>
1290      * </td>
1291      * </tr>
1292      * <tr>
1293      * <td style="vertical-align: top; width: 50%;"><code>Locale("de", "DE")</code><br>
1294      * </td>
1295      * <td style="vertical-align: top; width: 50%;"><code>java.class</code><br>
1296      * </td>
1297      * </tr>
1298      * <tr>
1299      * <td style="vertical-align: top; width: 50%;"><code>Locale("de", "DE")</code></td>
1300      * <td style="vertical-align: top; width: 50%;"><code>java.properties</code><br>
1301      * </td>
1302      * </tr>
1303      * <tr>
1304      * <td style="vertical-align: top; width: 50%;"><code>Locale("de")</code></td>
1305      * <td style="vertical-align: top; width: 50%;"><code>java.class</code></td>
1306      * </tr>
1307      * <tr>
1308      * <td style="vertical-align: top; width: 50%;"><code>Locale("de")</code></td>
1309      * <td style="vertical-align: top; width: 50%;"><code>java.properties</code></td>
1310      * </tr>
1311      * <tr>
1312      * <td style="vertical-align: top; width: 50%;"><code>Locale("")</code><br>
1313      * </td>
1314      * <td style="vertical-align: top; width: 50%;"><code>java.class</code></td>
1315      * </tr>
1316      * <tr>
1317      * <td style="vertical-align: top; width: 50%;"><code>Locale("")</code></td>
1318      * <td style="vertical-align: top; width: 50%;"><code>java.properties</code></td>
1319      * </tr>
1320      * </tbody>
1321      * </table>
1322      * </li>
1323      *
1324      * <li>If the previous step has found no resource bundle, proceed to
1325      * Step 6. If a bundle has been found that is a base bundle (a bundle
1326      * for <code>Locale("")</code>), and the candidate locale list only contained
1327      * <code>Locale("")</code>, return the bundle to the caller. If a bundle
1328      * has been found that is a base bundle, but the candidate locale list
1329      * contained locales other than Locale(""), put the bundle on hold and
1330      * proceed to Step 6. If a bundle has been found that is not a base
1331      * bundle, proceed to Step 7.</li>
1332      *
1333      * <li>The {@link ResourceBundle.Control#getFallbackLocale(String,
1334      * Locale) control.getFallbackLocale} method is called to get a fallback
1335      * locale (alternative to the current target locale) to try further
1336      * finding a resource bundle. If the method returns a non-null locale,
1337      * it becomes the next target locale and the loading process starts over
1338      * from Step 3. Otherwise, if a base bundle was found and put on hold in
1339      * a previous Step 5, it is returned to the caller now. Otherwise, a
1340      * MissingResourceException is thrown.</li>
1341      *
1342      * <li>At this point, we have found a resource bundle that's not the
1343      * base bundle. If this bundle set its parent during its instantiation,
1344      * it is returned to the caller. Otherwise, its <a
1345      * href="./ResourceBundle.html#parent_chain">parent chain</a> is
1346      * instantiated based on the list of candidate locales from which it was
1347      * found. Finally, the bundle is returned to the caller.</li>
1348      * </ol>
1349      *
1350      * <p>During the resource bundle loading process above, this factory
1351      * method looks up the cache before calling the {@link
1352      * Control#newBundle(String, Locale, String, ClassLoader, boolean)
1353      * control.newBundle} method.  If the time-to-live period of the
1354      * resource bundle found in the cache has expired, the factory method
1355      * calls the {@link ResourceBundle.Control#needsReload(String, Locale,
1356      * String, ClassLoader, ResourceBundle, long) control.needsReload}
1357      * method to determine whether the resource bundle needs to be reloaded.
1358      * If reloading is required, the factory method calls
1359      * <code>control.newBundle</code> to reload the resource bundle.  If
1360      * <code>control.newBundle</code> returns <code>null</code>, the factory
1361      * method puts a dummy resource bundle in the cache as a mark of
1362      * nonexistent resource bundles in order to avoid lookup overhead for
1363      * subsequent requests. Such dummy resource bundles are under the same
1364      * expiration control as specified by <code>control</code>.
1365      *
1366      * <p>All resource bundles loaded are cached by default. Refer to
1367      * {@link Control#getTimeToLive(String,Locale)
1368      * control.getTimeToLive} for details.
1369      *
1370      * <p>The following is an example of the bundle loading process with the
1371      * default <code>ResourceBundle.Control</code> implementation.
1372      *
1373      * <p>Conditions:
1374      * <ul>
1375      * <li>Base bundle name: <code>foo.bar.Messages</code>
1376      * <li>Requested <code>Locale</code>: {@link Locale#ITALY}</li>
1377      * <li>Default <code>Locale</code>: {@link Locale#FRENCH}</li>
1378      * <li>Available resource bundles:
1379      * <code>foo/bar/Messages_fr.properties</code> and
1380      * <code>foo/bar/Messages.properties</code></li>
1381      * </ul>
1382      *
1383      * <p>First, <code>getBundle</code> tries loading a resource bundle in
1384      * the following sequence.
1385      *
1386      * <ul>
1387      * <li>class <code>foo.bar.Messages_it_IT</code>
1388      * <li>file <code>foo/bar/Messages_it_IT.properties</code>
1389      * <li>class <code>foo.bar.Messages_it</code></li>
1390      * <li>file <code>foo/bar/Messages_it.properties</code></li>
1391      * <li>class <code>foo.bar.Messages</code></li>
1392      * <li>file <code>foo/bar/Messages.properties</code></li>
1393      * </ul>
1394      *
1395      * <p>At this point, <code>getBundle</code> finds
1396      * <code>foo/bar/Messages.properties</code>, which is put on hold
1397      * because it's the base bundle.  <code>getBundle</code> calls {@link
1398      * Control#getFallbackLocale(String, Locale)
1399      * control.getFallbackLocale("foo.bar.Messages", Locale.ITALY)} which
1400      * returns <code>Locale.FRENCH</code>. Next, <code>getBundle</code>
1401      * tries loading a bundle in the following sequence.
1402      *
1403      * <ul>
1404      * <li>class <code>foo.bar.Messages_fr</code></li>
1405      * <li>file <code>foo/bar/Messages_fr.properties</code></li>
1406      * <li>class <code>foo.bar.Messages</code></li>
1407      * <li>file <code>foo/bar/Messages.properties</code></li>
1408      * </ul>
1409      *
1410      * <p><code>getBundle</code> finds
1411      * <code>foo/bar/Messages_fr.properties</code> and creates a
1412      * <code>ResourceBundle</code> instance. Then, <code>getBundle</code>
1413      * sets up its parent chain from the list of the candidate locales.  Only
1414      * <code>foo/bar/Messages.properties</code> is found in the list and
1415      * <code>getBundle</code> creates a <code>ResourceBundle</code> instance
1416      * that becomes the parent of the instance for
1417      * <code>foo/bar/Messages_fr.properties</code>.
1418      *
1419      * @param baseName
1420      *        the base name of the resource bundle, a fully qualified
1421      *        class name
1422      * @param targetLocale
1423      *        the locale for which a resource bundle is desired
1424      * @param loader
1425      *        the class loader from which to load the resource bundle
1426      * @param control
1427      *        the control which gives information for the resource
1428      *        bundle loading process
1429      * @return a resource bundle for the given base name and locale
1430      * @throws NullPointerException
1431      *         if <code>baseName</code>, <code>targetLocale</code>,
1432      *         <code>loader</code>, or <code>control</code> is
1433      *         <code>null</code>
1434      * @throws MissingResourceException
1435      *         if no resource bundle for the specified base name can be found
1436      * @throws IllegalArgumentException
1437      *         if the given <code>control</code> doesn't perform properly
1438      *         (e.g., <code>control.getCandidateLocales</code> returns null.)
1439      *         Note that validation of <code>control</code> is performed as
1440      *         needed.
1441      * @throws UnsupportedOperationException
1442      *         if this method is called in a named module
1443      * @since 1.6
1444      */
1445     @CallerSensitive
1446     public static ResourceBundle getBundle(String baseName, Locale targetLocale,
1447                                            ClassLoader loader, Control control) {
1448         if (loader == null || control == null) {
1449             throw new NullPointerException();
1450         }
1451         Class<?> caller = Reflection.getCallerClass();
1452         checkNamedModule(caller);
1453         return getBundleImpl(baseName, targetLocale, caller, loader, control);
1454     }
1455 

































1456     private static void checkNamedModule(Class<?> caller) {
1457         if (caller.getModule().isNamed()) {
1458             throw new UnsupportedOperationException(
1459                     "ResourceBundle.Control not supported in named modules");
1460         }
1461     }
1462 
1463     private static ResourceBundle getBundleImpl(String baseName,
1464                                                 Locale locale,
1465                                                 Class<?> caller,
1466                                                 Control control) {
1467         return getBundleImpl(baseName, locale, caller, caller.getClassLoader(), control);
1468     }
1469 
1470     /**
1471      * This method will find resource bundles using the legacy mechanism
1472      * if the caller is unnamed module or the given class loader is
1473      * not the class loader of the caller module getting the resource
1474      * bundle, i.e. find the class that is visible to the class loader
1475      * and properties from unnamed module.
1476      *
1477      * The module-aware resource bundle lookup mechanism will load
1478      * the service providers using the service loader mechanism
1479      * as well as properties local in the caller module.
1480      */
1481     private static ResourceBundle getBundleImpl(String baseName,
1482                                                 Locale locale,
1483                                                 Class<?> caller,
1484                                                 ClassLoader loader,
1485                                                 Control control) {
1486         if (caller == null) {
1487             throw new InternalError("null caller");
1488         }
1489         Module callerModule = caller.getModule();
1490 
1491         // get resource bundles for a named module only if loader is the module's class loader
1492         if (callerModule.isNamed() && loader == getLoader(callerModule)) {
1493             return getBundleImpl(callerModule, callerModule, baseName, locale, control);
1494         }
1495 
1496         // find resource bundles from unnamed module of given class loader
1497         // Java agent can add to the bootclasspath e.g. via
1498         // java.lang.instrument.Instrumentation and load classes in unnamed module.
1499         // It may call RB::getBundle that will end up here with loader == null.
1500         Module unnamedModule = loader != null
1501             ? loader.getUnnamedModule()
1502             : BootLoader.getUnnamedModule();
1503 
1504         return getBundleImpl(callerModule, unnamedModule, baseName, locale, control);
1505     }
1506 
1507     private static ResourceBundle getBundleFromModule(Class<?> caller,
1508                                                       Module module,
1509                                                       String baseName,
1510                                                       Locale locale,
1511                                                       Control control) {
1512         Objects.requireNonNull(module);
1513         Module callerModule = caller.getModule();
1514         if (callerModule != module) {
1515             SecurityManager sm = System.getSecurityManager();
1516             if (sm != null) {
1517                 sm.checkPermission(GET_CLASSLOADER_PERMISSION);
1518             }
1519         }
1520         return getBundleImpl(callerModule, module, baseName, locale, control);
1521     }
1522 
1523     private static ResourceBundle getBundleImpl(Module callerModule,
1524                                                 Module module,
1525                                                 String baseName,
1526                                                 Locale locale,
1527                                                 Control control) {
1528         if (locale == null || control == null) {
1529             throw new NullPointerException();
1530         }
1531 
1532         // We create a CacheKey here for use by this call. The base name
1533         // and modules will never change during the bundle loading
1534         // process. We have to make sure that the locale is set before
1535         // using it as a cache key.
1536         CacheKey cacheKey = new CacheKey(baseName, locale, module, callerModule);
1537         ResourceBundle bundle = null;
1538 
1539         // Quick lookup of the cache.
1540         BundleReference bundleRef = cacheList.get(cacheKey);
1541         if (bundleRef != null) {
1542             bundle = bundleRef.get();
1543             bundleRef = null;
1544         }
1545 
1546         // If this bundle and all of its parents are valid (not expired),
1547         // then return this bundle. If any of the bundles is expired, we
1548         // don't call control.needsReload here but instead drop into the
1549         // complete loading process below.
1550         if (isValidBundle(bundle) && hasValidParentChain(bundle)) {
1551             return bundle;
1552         }
1553 
1554         // No valid bundle was found in the cache, so we need to load the
1555         // resource bundle and its parents.
1556 
1557         boolean isKnownControl = (control == Control.INSTANCE) ||
1558                                    (control instanceof SingleFormatControl);
1559         List<String> formats = control.getFormats(baseName);
1560         if (!isKnownControl && !checkList(formats)) {
1561             throw new IllegalArgumentException("Invalid Control: getFormats");
1562         }
1563 
1564         ResourceBundle baseBundle = null;
1565         for (Locale targetLocale = locale;
1566              targetLocale != null;
1567              targetLocale = control.getFallbackLocale(baseName, targetLocale)) {
1568             List<Locale> candidateLocales = control.getCandidateLocales(baseName, targetLocale);
1569             if (!isKnownControl && !checkList(candidateLocales)) {
1570                 throw new IllegalArgumentException("Invalid Control: getCandidateLocales");
1571             }
1572 
1573             bundle = findBundle(callerModule, module, cacheKey,
1574                                 candidateLocales, formats, 0, control, baseBundle);
1575 
1576             // If the loaded bundle is the base bundle and exactly for the
1577             // requested locale or the only candidate locale, then take the
1578             // bundle as the resulting one. If the loaded bundle is the base
1579             // bundle, it's put on hold until we finish processing all
1580             // fallback locales.
1581             if (isValidBundle(bundle)) {
1582                 boolean isBaseBundle = Locale.ROOT.equals(bundle.locale);
1583                 if (!isBaseBundle || bundle.locale.equals(locale)
1584                     || (candidateLocales.size() == 1
1585                         && bundle.locale.equals(candidateLocales.get(0)))) {
1586                     break;
1587                 }
1588 
1589                 // If the base bundle has been loaded, keep the reference in
1590                 // baseBundle so that we can avoid any redundant loading in case
1591                 // the control specify not to cache bundles.
1592                 if (isBaseBundle && baseBundle == null) {
1593                     baseBundle = bundle;
1594                 }
1595             }
1596         }
1597 
1598         if (bundle == null) {
1599             if (baseBundle == null) {
1600                 throwMissingResourceException(baseName, locale, cacheKey.getCause());
1601             }
1602             bundle = baseBundle;
1603         }
1604 
1605         // keep callerModule and module reachable for as long as we are operating
1606         // with WeakReference(s) to them (in CacheKey)...
1607         Reference.reachabilityFence(callerModule);
1608         Reference.reachabilityFence(module);
1609 
1610         return bundle;
1611     }
1612 
1613     /**
1614      * Checks if the given <code>List</code> is not null, not empty,
1615      * not having null in its elements.
1616      */
1617     private static boolean checkList(List<?> a) {
1618         boolean valid = (a != null && !a.isEmpty());
1619         if (valid) {
1620             int size = a.size();
1621             for (int i = 0; valid && i < size; i++) {
1622                 valid = (a.get(i) != null);
1623             }
1624         }
1625         return valid;
1626     }
1627 
1628     private static ResourceBundle findBundle(Module callerModule,
1629                                              Module module,
1630                                              CacheKey cacheKey,
1631                                              List<Locale> candidateLocales,
1632                                              List<String> formats,
1633                                              int index,
1634                                              Control control,
1635                                              ResourceBundle baseBundle) {
1636         Locale targetLocale = candidateLocales.get(index);
1637         ResourceBundle parent = null;
1638         if (index != candidateLocales.size() - 1) {
1639             parent = findBundle(callerModule, module, cacheKey,
1640                                 candidateLocales, formats, index + 1,
1641                                 control, baseBundle);
1642         } else if (baseBundle != null && Locale.ROOT.equals(targetLocale)) {
1643             return baseBundle;
1644         }
1645 
1646         // Before we do the real loading work, see whether we need to
1647         // do some housekeeping: If references to modules or
1648         // resource bundles have been nulled out, remove all related
1649         // information from the cache.
1650         Object ref;
1651         while ((ref = referenceQueue.poll()) != null) {
1652             cacheList.remove(((CacheKeyReference)ref).getCacheKey());
1653         }
1654 
1655         // flag indicating the resource bundle has expired in the cache
1656         boolean expiredBundle = false;
1657 
1658         // First, look up the cache to see if it's in the cache, without
1659         // attempting to load bundle.
1660         cacheKey.setLocale(targetLocale);
1661         ResourceBundle bundle = findBundleInCache(cacheKey, control);
1662         if (isValidBundle(bundle)) {
1663             expiredBundle = bundle.expired;
1664             if (!expiredBundle) {
1665                 // If its parent is the one asked for by the candidate
1666                 // locales (the runtime lookup path), we can take the cached
1667                 // one. (If it's not identical, then we'd have to check the
1668                 // parent's parents to be consistent with what's been
1669                 // requested.)
1670                 if (bundle.parent == parent) {
1671                     return bundle;
1672                 }
1673                 // Otherwise, remove the cached one since we can't keep
1674                 // the same bundles having different parents.
1675                 BundleReference bundleRef = cacheList.get(cacheKey);
1676                 if (bundleRef != null && bundleRef.get() == bundle) {
1677                     cacheList.remove(cacheKey, bundleRef);
1678                 }
1679             }
1680         }
1681 
1682         if (bundle != NONEXISTENT_BUNDLE) {
1683             trace("findBundle: %d %s %s formats: %s%n", index, candidateLocales, cacheKey, formats);
1684             if (module.isNamed()) {
1685                 bundle = loadBundle(cacheKey, formats, control, module, callerModule);
1686             } else {
1687                 bundle = loadBundle(cacheKey, formats, control, expiredBundle);
1688             }
1689             if (bundle != null) {
1690                 if (bundle.parent == null) {
1691                     bundle.setParent(parent);
1692                 }
1693                 bundle.locale = targetLocale;
1694                 bundle = putBundleInCache(cacheKey, bundle, control);
1695                 return bundle;
1696             }
1697 
1698             // Put NONEXISTENT_BUNDLE in the cache as a mark that there's no bundle
1699             // instance for the locale.
1700             putBundleInCache(cacheKey, NONEXISTENT_BUNDLE, control);
1701         }
1702         return parent;
1703     }
1704 
1705     private static final String UNKNOWN_FORMAT = "";
1706 
1707 
1708     /*
1709      * Loads a ResourceBundle in named modules
1710      */
1711     private static ResourceBundle loadBundle(CacheKey cacheKey,
1712                                              List<String> formats,
1713                                              Control control,
1714                                              Module module,
1715                                              Module callerModule) {
1716         String baseName = cacheKey.getName();
1717         Locale targetLocale = cacheKey.getLocale();
1718 
1719         ResourceBundle bundle = null;
1720         if (cacheKey.hasProviders()) {
1721             if (callerModule == module) {
1722                 bundle = loadBundleFromProviders(baseName,
1723                                                  targetLocale,
1724                                                  cacheKey.getProviders(),
1725                                                  cacheKey);
1726             } else {
1727                 // load from provider if the caller module has access to the
1728                 // service type and also declares `uses`
1729                 ClassLoader loader = getLoader(module);
1730                 Class<ResourceBundleProvider> svc =
1731                     getResourceBundleProviderType(baseName, loader);
1732                 if (svc != null
1733                         && Reflection.verifyModuleAccess(callerModule, svc)
1734                         && callerModule.canUse(svc)) {
1735                     bundle = loadBundleFromProviders(baseName,
1736                                                      targetLocale,
1737                                                      cacheKey.getProviders(),
1738                                                      cacheKey);
1739                 }
1740             }
1741 
1742             if (bundle != null) {
1743                 cacheKey.setFormat(UNKNOWN_FORMAT);
1744             }
1745         }
1746 
1747         // If none of providers returned a bundle and the caller has no provider,
1748         // look up module-local bundles or from the class path
1749         if (bundle == null && !cacheKey.callerHasProvider()) {
1750             for (String format : formats) {
1751                 try {
1752                     switch (format) {
1753                     case "java.class":
1754                         bundle = ResourceBundleProviderHelper
1755                             .loadResourceBundle(callerModule, module, baseName, targetLocale);
1756 
1757                         break;
1758                     case "java.properties":
1759                         bundle = ResourceBundleProviderHelper
1760                             .loadPropertyResourceBundle(callerModule, module, baseName, targetLocale);
1761                         break;
1762                     default:
1763                         throw new InternalError("unexpected format: " + format);
1764                     }
1765 
1766                     if (bundle != null) {
1767                         cacheKey.setFormat(format);
1768                         break;
1769                     }
1770                 } catch (Exception e) {
1771                     cacheKey.setCause(e);
1772                 }
1773             }
1774         }
1775         return bundle;
1776     }
1777 
1778     /**
1779      * Returns a ServiceLoader that will find providers that are bound to
1780      * a given named module.
1781      */
1782     private static ServiceLoader<ResourceBundleProvider> getServiceLoader(Module module,
1783                                                                           String baseName)
1784     {
1785         if (!module.isNamed()) {
1786             return null;
1787         }
1788 
1789         ClassLoader loader = getLoader(module);
1790         Class<ResourceBundleProvider> service =
1791                 getResourceBundleProviderType(baseName, loader);
1792         if (service != null && Reflection.verifyModuleAccess(module, service)) {
1793             try {
1794                 // locate providers that are visible to the class loader
1795                 // ServiceConfigurationError will be thrown if the module
1796                 // does not declare `uses` the service type
1797                 return ServiceLoader.load(service, loader, module);
1798             } catch (ServiceConfigurationError e) {
1799                 // "uses" not declared
1800                 return null;
1801             }
1802         }
1803         return null;
1804     }
1805 
1806     /**
1807      * Returns the service type of the given baseName that is visible
1808      * to the given class loader
1809      */
1810     private static Class<ResourceBundleProvider>
1811             getResourceBundleProviderType(String baseName, ClassLoader loader)
1812     {
1813         // Look up <baseName> + "Provider"
1814         String providerName = baseName + "Provider";
1815         // Use the class loader of the getBundle caller so that the caller's
1816         // visibility of the provider type is checked.
1817         return AccessController.doPrivileged(
1818             new PrivilegedAction<>() {
1819                 @Override
1820                 public Class<ResourceBundleProvider> run() {
1821                     try {
1822                         Class<?> c = Class.forName(providerName, false, loader);
1823                         if (ResourceBundleProvider.class.isAssignableFrom(c)) {
1824                             @SuppressWarnings("unchecked")
1825                             Class<ResourceBundleProvider> s = (Class<ResourceBundleProvider>) c;
1826                             return s;
1827                         }
1828                     } catch (ClassNotFoundException e) {}
1829                     return null;
1830                 }
1831             });
1832     }
1833 
1834     /**
1835      * Loads ResourceBundle from service providers.
1836      */
1837     private static ResourceBundle loadBundleFromProviders(String baseName,
1838                                                           Locale locale,
1839                                                           ServiceLoader<ResourceBundleProvider> providers,
1840                                                           CacheKey cacheKey)
1841     {
1842         if (providers == null) return null;
1843 
1844         return AccessController.doPrivileged(
1845                 new PrivilegedAction<>() {
1846                     public ResourceBundle run() {
1847                         for (Iterator<ResourceBundleProvider> itr = providers.iterator(); itr.hasNext(); ) {
1848                             try {
1849                                 ResourceBundleProvider provider = itr.next();
1850                                 if (cacheKey != null && cacheKey.callerHasProvider == null
1851                                         && cacheKey.getModule() == provider.getClass().getModule()) {
1852                                     cacheKey.callerHasProvider = Boolean.TRUE;
1853                                 }
1854                                 ResourceBundle bundle = provider.getBundle(baseName, locale);
1855                                 trace("provider %s %s locale: %s bundle: %s%n", provider, baseName, locale, bundle);
1856                                 if (bundle != null) {
1857                                     return bundle;
1858                                 }
1859                             } catch (ServiceConfigurationError | SecurityException e) {
1860                                 if (cacheKey != null) {
1861                                     cacheKey.setCause(e);
1862                                 }
1863                             }
1864                         }
1865                         if (cacheKey != null && cacheKey.callerHasProvider == null) {
1866                             cacheKey.callerHasProvider = Boolean.FALSE;
1867                         }
1868                         return null;
1869                     }
1870                 });
1871 
1872     }
1873 
1874     /*
1875      * Legacy mechanism to load resource bundles
1876      */
1877     private static ResourceBundle loadBundle(CacheKey cacheKey,
1878                                              List<String> formats,
1879                                              Control control,
1880                                              boolean reload) {
1881 
1882         // Here we actually load the bundle in the order of formats
1883         // specified by the getFormats() value.
1884         Locale targetLocale = cacheKey.getLocale();
1885 
1886         Module module = cacheKey.getModule();
1887         if (module == null) {
1888             // should not happen
1889             throw new InternalError(
1890                 "Module for cache key: " + cacheKey + " has been GCed.");
1891         }
1892         ClassLoader loader = getLoaderForControl(module);
1893 
1894         ResourceBundle bundle = null;
1895         for (String format : formats) {
1896             try {
1897                 // ResourceBundle.Control.newBundle may be overridden
1898                 bundle = control.newBundle(cacheKey.getName(), targetLocale, format,
1899                                            loader, reload);
1900             } catch (LinkageError | Exception error) {
1901                 // We need to handle the LinkageError case due to
1902                 // inconsistent case-sensitivity in ClassLoader.
1903                 // See 6572242 for details.
1904                 cacheKey.setCause(error);
1905             }
1906             if (bundle != null) {
1907                 // Set the format in the cache key so that it can be
1908                 // used when calling needsReload later.
1909                 cacheKey.setFormat(format);
1910                 bundle.name = cacheKey.getName();
1911                 bundle.locale = targetLocale;
1912                 // Bundle provider might reuse instances. So we should make
1913                 // sure to clear the expired flag here.
1914                 bundle.expired = false;
1915                 break;
1916             }
1917         }
1918 
1919         return bundle;
1920     }
1921 
1922     private static boolean isValidBundle(ResourceBundle bundle) {
1923         return bundle != null && bundle != NONEXISTENT_BUNDLE;
1924     }
1925 
1926     /**
1927      * Determines whether any of resource bundles in the parent chain,
1928      * including the leaf, have expired.
1929      */
1930     private static boolean hasValidParentChain(ResourceBundle bundle) {
1931         long now = System.currentTimeMillis();
1932         while (bundle != null) {
1933             if (bundle.expired) {
1934                 return false;
1935             }
1936             CacheKey key = bundle.cacheKey;
1937             if (key != null) {
1938                 long expirationTime = key.expirationTime;
1939                 if (expirationTime >= 0 && expirationTime <= now) {
1940                     return false;
1941                 }
1942             }
1943             bundle = bundle.parent;
1944         }
1945         return true;
1946     }
1947 
1948     /**
1949      * Throw a MissingResourceException with proper message
1950      */
1951     private static void throwMissingResourceException(String baseName,
1952                                                       Locale locale,
1953                                                       Throwable cause) {
1954         // If the cause is a MissingResourceException, avoid creating
1955         // a long chain. (6355009)
1956         if (cause instanceof MissingResourceException) {
1957             cause = null;
1958         }
1959         throw new MissingResourceException("Can't find bundle for base name "
1960                                            + baseName + ", locale " + locale,
1961                                            baseName + "_" + locale, // className
1962                                            "",                      // key
1963                                            cause);
1964     }
1965 
1966     /**
1967      * Finds a bundle in the cache. Any expired bundles are marked as
1968      * `expired' and removed from the cache upon return.
1969      *
1970      * @param cacheKey the key to look up the cache
1971      * @param control the Control to be used for the expiration control
1972      * @return the cached bundle, or null if the bundle is not found in the
1973      * cache or its parent has expired. <code>bundle.expire</code> is true
1974      * upon return if the bundle in the cache has expired.
1975      */
1976     private static ResourceBundle findBundleInCache(CacheKey cacheKey,
1977                                                     Control control) {
1978         BundleReference bundleRef = cacheList.get(cacheKey);
1979         if (bundleRef == null) {
1980             return null;
1981         }
1982         ResourceBundle bundle = bundleRef.get();
1983         if (bundle == null) {
1984             return null;
1985         }
1986         ResourceBundle p = bundle.parent;
1987         assert p != NONEXISTENT_BUNDLE;
1988         // If the parent has expired, then this one must also expire. We
1989         // check only the immediate parent because the actual loading is
1990         // done from the root (base) to leaf (child) and the purpose of
1991         // checking is to propagate expiration towards the leaf. For
1992         // example, if the requested locale is ja_JP_JP and there are
1993         // bundles for all of the candidates in the cache, we have a list,
1994         //
1995         // base <- ja <- ja_JP <- ja_JP_JP
1996         //
1997         // If ja has expired, then it will reload ja and the list becomes a
1998         // tree.
1999         //
2000         // base <- ja (new)
2001         //  "   <- ja (expired) <- ja_JP <- ja_JP_JP
2002         //
2003         // When looking up ja_JP in the cache, it finds ja_JP in the cache
2004         // which references to the expired ja. Then, ja_JP is marked as
2005         // expired and removed from the cache. This will be propagated to
2006         // ja_JP_JP.
2007         //
2008         // Now, it's possible, for example, that while loading new ja_JP,
2009         // someone else has started loading the same bundle and finds the
2010         // base bundle has expired. Then, what we get from the first
2011         // getBundle call includes the expired base bundle. However, if
2012         // someone else didn't start its loading, we wouldn't know if the
2013         // base bundle has expired at the end of the loading process. The
2014         // expiration control doesn't guarantee that the returned bundle and
2015         // its parents haven't expired.
2016         //
2017         // We could check the entire parent chain to see if there's any in
2018         // the chain that has expired. But this process may never end. An
2019         // extreme case would be that getTimeToLive returns 0 and
2020         // needsReload always returns true.
2021         if (p != null && p.expired) {
2022             assert bundle != NONEXISTENT_BUNDLE;
2023             bundle.expired = true;
2024             bundle.cacheKey = null;
2025             cacheList.remove(cacheKey, bundleRef);
2026             bundle = null;
2027         } else {
2028             CacheKey key = bundleRef.getCacheKey();
2029             long expirationTime = key.expirationTime;
2030             if (!bundle.expired && expirationTime >= 0 &&
2031                 expirationTime <= System.currentTimeMillis()) {
2032                 // its TTL period has expired.
2033                 if (bundle != NONEXISTENT_BUNDLE) {
2034                     // Synchronize here to call needsReload to avoid
2035                     // redundant concurrent calls for the same bundle.
2036                     synchronized (bundle) {
2037                         expirationTime = key.expirationTime;
2038                         if (!bundle.expired && expirationTime >= 0 &&
2039                             expirationTime <= System.currentTimeMillis()) {
2040                             try {
2041                                 Module module = cacheKey.getModule();
2042                                 bundle.expired =
2043                                     module == null || // already GCed
2044                                     control.needsReload(key.getName(),
2045                                                         key.getLocale(),
2046                                                         key.getFormat(),
2047                                                         getLoaderForControl(module),
2048                                                         bundle,
2049                                                         key.loadTime);
2050                             } catch (Exception e) {
2051                                 cacheKey.setCause(e);
2052                             }
2053                             if (bundle.expired) {
2054                                 // If the bundle needs to be reloaded, then
2055                                 // remove the bundle from the cache, but
2056                                 // return the bundle with the expired flag
2057                                 // on.
2058                                 bundle.cacheKey = null;
2059                                 cacheList.remove(cacheKey, bundleRef);
2060                             } else {
2061                                 // Update the expiration control info. and reuse
2062                                 // the same bundle instance
2063                                 setExpirationTime(key, control);
2064                             }
2065                         }
2066                     }
2067                 } else {
2068                     // We just remove NONEXISTENT_BUNDLE from the cache.
2069                     cacheList.remove(cacheKey, bundleRef);
2070                     bundle = null;
2071                 }
2072             }
2073         }
2074         return bundle;
2075     }
2076 
2077     /**
2078      * Put a new bundle in the cache.
2079      *
2080      * @param cacheKey the key for the resource bundle
2081      * @param bundle the resource bundle to be put in the cache
2082      * @return the ResourceBundle for the cacheKey; if someone has put
2083      * the bundle before this call, the one found in the cache is
2084      * returned.
2085      */
2086     private static ResourceBundle putBundleInCache(CacheKey cacheKey,
2087                                                    ResourceBundle bundle,
2088                                                    Control control) {
2089         setExpirationTime(cacheKey, control);
2090         if (cacheKey.expirationTime != Control.TTL_DONT_CACHE) {
2091             CacheKey key = new CacheKey(cacheKey);
2092             BundleReference bundleRef = new BundleReference(bundle, referenceQueue, key);
2093             bundle.cacheKey = key;
2094 
2095             // Put the bundle in the cache if it's not been in the cache.
2096             BundleReference result = cacheList.putIfAbsent(key, bundleRef);
2097 
2098             // If someone else has put the same bundle in the cache before
2099             // us and it has not expired, we should use the one in the cache.
2100             if (result != null) {
2101                 ResourceBundle rb = result.get();
2102                 if (rb != null && !rb.expired) {
2103                     // Clear the back link to the cache key
2104                     bundle.cacheKey = null;
2105                     bundle = rb;
2106                     // Clear the reference in the BundleReference so that
2107                     // it won't be enqueued.
2108                     bundleRef.clear();
2109                 } else {
2110                     // Replace the invalid (garbage collected or expired)
2111                     // instance with the valid one.
2112                     cacheList.put(key, bundleRef);
2113                 }
2114             }
2115         }
2116         return bundle;
2117     }
2118 
2119     private static void setExpirationTime(CacheKey cacheKey, Control control) {
2120         long ttl = control.getTimeToLive(cacheKey.getName(),
2121                                          cacheKey.getLocale());
2122         if (ttl >= 0) {
2123             // If any expiration time is specified, set the time to be
2124             // expired in the cache.
2125             long now = System.currentTimeMillis();
2126             cacheKey.loadTime = now;
2127             cacheKey.expirationTime = now + ttl;
2128         } else if (ttl >= Control.TTL_NO_EXPIRATION_CONTROL) {
2129             cacheKey.expirationTime = ttl;
2130         } else {
2131             throw new IllegalArgumentException("Invalid Control: TTL=" + ttl);
2132         }
2133     }
2134 
2135     /**
2136      * Removes all resource bundles from the cache that have been loaded
2137      * by the caller's module.
2138      *
2139      * @since 1.6
2140      * @see ResourceBundle.Control#getTimeToLive(String,Locale)
2141      */
2142     @CallerSensitive
2143     public static final void clearCache() {
2144         Class<?> caller = Reflection.getCallerClass();
2145         cacheList.keySet().removeIf(
2146             key -> key.getCallerModule() == caller.getModule()
2147         );
2148     }
2149 
2150     /**
2151      * Removes all resource bundles from the cache that have been loaded
2152      * by the given class loader.
2153      *
2154      * @param loader the class loader
2155      * @exception NullPointerException if <code>loader</code> is null
2156      * @since 1.6
2157      * @see ResourceBundle.Control#getTimeToLive(String,Locale)
2158      */
2159     public static final void clearCache(ClassLoader loader) {
2160         Objects.requireNonNull(loader);
2161         cacheList.keySet().removeIf(
2162             key -> {
2163                 Module m;
2164                 return (m = key.getModule()) != null &&
2165                        getLoader(m) == loader;
2166             }
2167         );
2168     }
2169 
2170     /**
2171      * Gets an object for the given key from this resource bundle.
2172      * Returns null if this resource bundle does not contain an
2173      * object for the given key.
2174      *
2175      * @param key the key for the desired object
2176      * @exception NullPointerException if <code>key</code> is <code>null</code>
2177      * @return the object for the given key, or null
2178      */
2179     protected abstract Object handleGetObject(String key);
2180 
2181     /**
2182      * Returns an enumeration of the keys.
2183      *
2184      * @return an <code>Enumeration</code> of the keys contained in
2185      *         this <code>ResourceBundle</code> and its parent bundles.
2186      */
2187     public abstract Enumeration<String> getKeys();
2188 
2189     /**
2190      * Determines whether the given <code>key</code> is contained in
2191      * this <code>ResourceBundle</code> or its parent bundles.
2192      *
2193      * @param key
2194      *        the resource <code>key</code>
2195      * @return <code>true</code> if the given <code>key</code> is
2196      *        contained in this <code>ResourceBundle</code> or its
2197      *        parent bundles; <code>false</code> otherwise.
2198      * @exception NullPointerException
2199      *         if <code>key</code> is <code>null</code>
2200      * @since 1.6
2201      */
2202     public boolean containsKey(String key) {
2203         if (key == null) {
2204             throw new NullPointerException();
2205         }
2206         for (ResourceBundle rb = this; rb != null; rb = rb.parent) {
2207             if (rb.handleKeySet().contains(key)) {
2208                 return true;
2209             }
2210         }
2211         return false;
2212     }
2213 
2214     /**
2215      * Returns a <code>Set</code> of all keys contained in this
2216      * <code>ResourceBundle</code> and its parent bundles.
2217      *
2218      * @return a <code>Set</code> of all keys contained in this
2219      *         <code>ResourceBundle</code> and its parent bundles.
2220      * @since 1.6
2221      */
2222     public Set<String> keySet() {
2223         Set<String> keys = new HashSet<>();
2224         for (ResourceBundle rb = this; rb != null; rb = rb.parent) {
2225             keys.addAll(rb.handleKeySet());
2226         }
2227         return keys;
2228     }
2229 
2230     /**
2231      * Returns a <code>Set</code> of the keys contained <em>only</em>
2232      * in this <code>ResourceBundle</code>.
2233      *
2234      * <p>The default implementation returns a <code>Set</code> of the
2235      * keys returned by the {@link #getKeys() getKeys} method except
2236      * for the ones for which the {@link #handleGetObject(String)
2237      * handleGetObject} method returns <code>null</code>. Once the
2238      * <code>Set</code> has been created, the value is kept in this
2239      * <code>ResourceBundle</code> in order to avoid producing the
2240      * same <code>Set</code> in subsequent calls. Subclasses can
2241      * override this method for faster handling.
2242      *
2243      * @return a <code>Set</code> of the keys contained only in this
2244      *        <code>ResourceBundle</code>
2245      * @since 1.6
2246      */
2247     protected Set<String> handleKeySet() {
2248         if (keySet == null) {
2249             synchronized (this) {
2250                 if (keySet == null) {
2251                     Set<String> keys = new HashSet<>();
2252                     Enumeration<String> enumKeys = getKeys();
2253                     while (enumKeys.hasMoreElements()) {
2254                         String key = enumKeys.nextElement();
2255                         if (handleGetObject(key) != null) {
2256                             keys.add(key);
2257                         }
2258                     }
2259                     keySet = keys;
2260                 }
2261             }
2262         }
2263         return keySet;
2264     }
2265 
2266 
2267 
2268     /**
2269      * <code>ResourceBundle.Control</code> defines a set of callback methods
2270      * that are invoked by the {@link ResourceBundle#getBundle(String,
2271      * Locale, ClassLoader, Control) ResourceBundle.getBundle} factory
2272      * methods during the bundle loading process. In other words, a
2273      * <code>ResourceBundle.Control</code> collaborates with the factory
2274      * methods for loading resource bundles. The default implementation of
2275      * the callback methods provides the information necessary for the
2276      * factory methods to perform the <a
2277      * href="./ResourceBundle.html#default_behavior">default behavior</a>.
2278      * <a href="#note">Note that this class is not supported in named modules.</a>
2279      *
2280      * <p>In addition to the callback methods, the {@link
2281      * #toBundleName(String, Locale) toBundleName} and {@link
2282      * #toResourceName(String, String) toResourceName} methods are defined
2283      * primarily for convenience in implementing the callback
2284      * methods. However, the <code>toBundleName</code> method could be
2285      * overridden to provide different conventions in the organization and
2286      * packaging of localized resources.  The <code>toResourceName</code>
2287      * method is <code>final</code> to avoid use of wrong resource and class
2288      * name separators.
2289      *
2290      * <p>Two factory methods, {@link #getControl(List)} and {@link
2291      * #getNoFallbackControl(List)}, provide
2292      * <code>ResourceBundle.Control</code> instances that implement common
2293      * variations of the default bundle loading process.
2294      *
2295      * <p>The formats returned by the {@link Control#getFormats(String)
2296      * getFormats} method and candidate locales returned by the {@link
2297      * ResourceBundle.Control#getCandidateLocales(String, Locale)
2298      * getCandidateLocales} method must be consistent in all
2299      * <code>ResourceBundle.getBundle</code> invocations for the same base
2300      * bundle. Otherwise, the <code>ResourceBundle.getBundle</code> methods
2301      * may return unintended bundles. For example, if only
2302      * <code>"java.class"</code> is returned by the <code>getFormats</code>
2303      * method for the first call to <code>ResourceBundle.getBundle</code>
2304      * and only <code>"java.properties"</code> for the second call, then the
2305      * second call will return the class-based one that has been cached
2306      * during the first call.
2307      *
2308      * <p>A <code>ResourceBundle.Control</code> instance must be thread-safe
2309      * if it's simultaneously used by multiple threads.
2310      * <code>ResourceBundle.getBundle</code> does not synchronize to call
2311      * the <code>ResourceBundle.Control</code> methods. The default
2312      * implementations of the methods are thread-safe.
2313      *
2314      * <p>Applications can specify <code>ResourceBundle.Control</code>
2315      * instances returned by the <code>getControl</code> factory methods or
2316      * created from a subclass of <code>ResourceBundle.Control</code> to
2317      * customize the bundle loading process. The following are examples of
2318      * changing the default bundle loading process.
2319      *
2320      * <p><b>Example 1</b>
2321      *
2322      * <p>The following code lets <code>ResourceBundle.getBundle</code> look
2323      * up only properties-based resources.
2324      *
2325      * <pre>
2326      * import java.util.*;
2327      * import static java.util.ResourceBundle.Control.*;
2328      * ...
2329      * ResourceBundle bundle =
2330      *   ResourceBundle.getBundle("MyResources", new Locale("fr", "CH"),
2331      *                            ResourceBundle.Control.getControl(FORMAT_PROPERTIES));
2332      * </pre>
2333      *
2334      * Given the resource bundles in the <a
2335      * href="./ResourceBundle.html#default_behavior_example">example</a> in
2336      * the <code>ResourceBundle.getBundle</code> description, this
2337      * <code>ResourceBundle.getBundle</code> call loads
2338      * <code>MyResources_fr_CH.properties</code> whose parent is
2339      * <code>MyResources_fr.properties</code> whose parent is
2340      * <code>MyResources.properties</code>. (<code>MyResources_fr_CH.properties</code>
2341      * is not hidden, but <code>MyResources_fr_CH.class</code> is.)
2342      *
2343      * <p><b>Example 2</b>
2344      *
2345      * <p>The following is an example of loading XML-based bundles
2346      * using {@link Properties#loadFromXML(java.io.InputStream)
2347      * Properties.loadFromXML}.
2348      *
2349      * <pre>
2350      * ResourceBundle rb = ResourceBundle.getBundle("Messages",
2351      *     new ResourceBundle.Control() {
2352      *         public List&lt;String&gt; getFormats(String baseName) {
2353      *             if (baseName == null)
2354      *                 throw new NullPointerException();
2355      *             return Arrays.asList("xml");
2356      *         }
2357      *         public ResourceBundle newBundle(String baseName,
2358      *                                         Locale locale,
2359      *                                         String format,
2360      *                                         ClassLoader loader,
2361      *                                         boolean reload)
2362      *                          throws IllegalAccessException,
2363      *                                 InstantiationException,
2364      *                                 IOException {
2365      *             if (baseName == null || locale == null
2366      *                   || format == null || loader == null)
2367      *                 throw new NullPointerException();
2368      *             ResourceBundle bundle = null;
2369      *             if (format.equals("xml")) {
2370      *                 String bundleName = toBundleName(baseName, locale);
2371      *                 String resourceName = toResourceName(bundleName, format);
2372      *                 InputStream stream = null;
2373      *                 if (reload) {
2374      *                     URL url = loader.getResource(resourceName);
2375      *                     if (url != null) {
2376      *                         URLConnection connection = url.openConnection();
2377      *                         if (connection != null) {
2378      *                             // Disable caches to get fresh data for
2379      *                             // reloading.
2380      *                             connection.setUseCaches(false);
2381      *                             stream = connection.getInputStream();
2382      *                         }
2383      *                     }
2384      *                 } else {
2385      *                     stream = loader.getResourceAsStream(resourceName);
2386      *                 }
2387      *                 if (stream != null) {
2388      *                     BufferedInputStream bis = new BufferedInputStream(stream);
2389      *                     bundle = new XMLResourceBundle(bis);
2390      *                     bis.close();
2391      *                 }
2392      *             }
2393      *             return bundle;
2394      *         }
2395      *     });
2396      *
2397      * ...
2398      *
2399      * private static class XMLResourceBundle extends ResourceBundle {
2400      *     private Properties props;
2401      *     XMLResourceBundle(InputStream stream) throws IOException {
2402      *         props = new Properties();
2403      *         props.loadFromXML(stream);
2404      *     }
2405      *     protected Object handleGetObject(String key) {
2406      *         return props.getProperty(key);
2407      *     }
2408      *     public Enumeration&lt;String&gt; getKeys() {
2409      *         ...
2410      *     }
2411      * }
2412      * </pre>
2413      *
2414      * @apiNote <a name="note">{@code ResourceBundle.Control} is not supported
2415      * in named modules.</a> If the {@code ResourceBundle.getBundle} method with
2416      * a {@code ResourceBundle.Control} is called in a named module, the method
2417      * will throw an {@link UnsupportedOperationException}.

2418      *
2419      * @since 1.6
2420      * @see java.util.spi.ResourceBundleProvider
2421      */
2422     public static class Control {
2423         /**
2424          * The default format <code>List</code>, which contains the strings
2425          * <code>"java.class"</code> and <code>"java.properties"</code>, in
2426          * this order. This <code>List</code> is unmodifiable.
2427          *
2428          * @see #getFormats(String)
2429          */
2430         public static final List<String> FORMAT_DEFAULT
2431             = List.of("java.class", "java.properties");
2432 
2433         /**
2434          * The class-only format <code>List</code> containing
2435          * <code>"java.class"</code>. This <code>List</code> is unmodifiable.
2436          *
2437          * @see #getFormats(String)
2438          */
2439         public static final List<String> FORMAT_CLASS = List.of("java.class");
2440 
2441         /**
2442          * The properties-only format <code>List</code> containing
2443          * <code>"java.properties"</code>. This <code>List</code> is unmodifiable.
2444          *
2445          * @see #getFormats(String)
2446          */
2447         public static final List<String> FORMAT_PROPERTIES
2448             = List.of("java.properties");
2449 
2450         /**
2451          * The time-to-live constant for not caching loaded resource bundle
2452          * instances.
2453          *
2454          * @see #getTimeToLive(String, Locale)
2455          */
2456         public static final long TTL_DONT_CACHE = -1;
2457 
2458         /**
2459          * The time-to-live constant for disabling the expiration control
2460          * for loaded resource bundle instances in the cache.
2461          *
2462          * @see #getTimeToLive(String, Locale)
2463          */
2464         public static final long TTL_NO_EXPIRATION_CONTROL = -2;
2465 
2466         private static final Control INSTANCE = new Control();
2467 
2468         /**
2469          * Sole constructor. (For invocation by subclass constructors,
2470          * typically implicit.)
2471          */
2472         protected Control() {
2473         }
2474 
2475         /**
2476          * Returns a <code>ResourceBundle.Control</code> in which the {@link
2477          * #getFormats(String) getFormats} method returns the specified
2478          * <code>formats</code>. The <code>formats</code> must be equal to
2479          * one of {@link Control#FORMAT_PROPERTIES}, {@link
2480          * Control#FORMAT_CLASS} or {@link
2481          * Control#FORMAT_DEFAULT}. <code>ResourceBundle.Control</code>
2482          * instances returned by this method are singletons and thread-safe.
2483          *
2484          * <p>Specifying {@link Control#FORMAT_DEFAULT} is equivalent to
2485          * instantiating the <code>ResourceBundle.Control</code> class,
2486          * except that this method returns a singleton.
2487          *
2488          * @param formats
2489          *        the formats to be returned by the
2490          *        <code>ResourceBundle.Control.getFormats</code> method
2491          * @return a <code>ResourceBundle.Control</code> supporting the
2492          *        specified <code>formats</code>
2493          * @exception NullPointerException
2494          *        if <code>formats</code> is <code>null</code>
2495          * @exception IllegalArgumentException
2496          *        if <code>formats</code> is unknown
2497          */
2498         public static final Control getControl(List<String> formats) {
2499             if (formats.equals(Control.FORMAT_PROPERTIES)) {
2500                 return SingleFormatControl.PROPERTIES_ONLY;
2501             }
2502             if (formats.equals(Control.FORMAT_CLASS)) {
2503                 return SingleFormatControl.CLASS_ONLY;
2504             }
2505             if (formats.equals(Control.FORMAT_DEFAULT)) {
2506                 return Control.INSTANCE;
2507             }
2508             throw new IllegalArgumentException();
2509         }
2510 
2511         /**
2512          * Returns a <code>ResourceBundle.Control</code> in which the {@link
2513          * #getFormats(String) getFormats} method returns the specified
2514          * <code>formats</code> and the {@link
2515          * Control#getFallbackLocale(String, Locale) getFallbackLocale}
2516          * method returns <code>null</code>. The <code>formats</code> must
2517          * be equal to one of {@link Control#FORMAT_PROPERTIES}, {@link
2518          * Control#FORMAT_CLASS} or {@link Control#FORMAT_DEFAULT}.
2519          * <code>ResourceBundle.Control</code> instances returned by this
2520          * method are singletons and thread-safe.
2521          *
2522          * @param formats
2523          *        the formats to be returned by the
2524          *        <code>ResourceBundle.Control.getFormats</code> method
2525          * @return a <code>ResourceBundle.Control</code> supporting the
2526          *        specified <code>formats</code> with no fallback
2527          *        <code>Locale</code> support
2528          * @exception NullPointerException
2529          *        if <code>formats</code> is <code>null</code>
2530          * @exception IllegalArgumentException
2531          *        if <code>formats</code> is unknown
2532          */
2533         public static final Control getNoFallbackControl(List<String> formats) {
2534             if (formats.equals(Control.FORMAT_DEFAULT)) {
2535                 return NoFallbackControl.NO_FALLBACK;
2536             }
2537             if (formats.equals(Control.FORMAT_PROPERTIES)) {
2538                 return NoFallbackControl.PROPERTIES_ONLY_NO_FALLBACK;
2539             }
2540             if (formats.equals(Control.FORMAT_CLASS)) {
2541                 return NoFallbackControl.CLASS_ONLY_NO_FALLBACK;
2542             }
2543             throw new IllegalArgumentException();
2544         }
2545 
2546         /**
2547          * Returns a <code>List</code> of <code>String</code>s containing
2548          * formats to be used to load resource bundles for the given
2549          * <code>baseName</code>. The <code>ResourceBundle.getBundle</code>
2550          * factory method tries to load resource bundles with formats in the
2551          * order specified by the list. The list returned by this method
2552          * must have at least one <code>String</code>. The predefined
2553          * formats are <code>"java.class"</code> for class-based resource
2554          * bundles and <code>"java.properties"</code> for {@linkplain
2555          * PropertyResourceBundle properties-based} ones. Strings starting
2556          * with <code>"java."</code> are reserved for future extensions and
2557          * must not be used by application-defined formats.
2558          *
2559          * <p>It is not a requirement to return an immutable (unmodifiable)
2560          * <code>List</code>.  However, the returned <code>List</code> must
2561          * not be mutated after it has been returned by
2562          * <code>getFormats</code>.
2563          *
2564          * <p>The default implementation returns {@link #FORMAT_DEFAULT} so
2565          * that the <code>ResourceBundle.getBundle</code> factory method
2566          * looks up first class-based resource bundles, then
2567          * properties-based ones.
2568          *
2569          * @param baseName
2570          *        the base name of the resource bundle, a fully qualified class
2571          *        name
2572          * @return a <code>List</code> of <code>String</code>s containing
2573          *        formats for loading resource bundles.
2574          * @exception NullPointerException
2575          *        if <code>baseName</code> is null
2576          * @see #FORMAT_DEFAULT
2577          * @see #FORMAT_CLASS
2578          * @see #FORMAT_PROPERTIES
2579          */
2580         public List<String> getFormats(String baseName) {
2581             if (baseName == null) {
2582                 throw new NullPointerException();
2583             }
2584             return FORMAT_DEFAULT;
2585         }
2586 
2587         /**
2588          * Returns a <code>List</code> of <code>Locale</code>s as candidate
2589          * locales for <code>baseName</code> and <code>locale</code>. This
2590          * method is called by the <code>ResourceBundle.getBundle</code>
2591          * factory method each time the factory method tries finding a
2592          * resource bundle for a target <code>Locale</code>.
2593          *
2594          * <p>The sequence of the candidate locales also corresponds to the
2595          * runtime resource lookup path (also known as the <I>parent
2596          * chain</I>), if the corresponding resource bundles for the
2597          * candidate locales exist and their parents are not defined by
2598          * loaded resource bundles themselves.  The last element of the list
2599          * must be a {@linkplain Locale#ROOT root locale} if it is desired to
2600          * have the base bundle as the terminal of the parent chain.
2601          *
2602          * <p>If the given locale is equal to <code>Locale.ROOT</code> (the
2603          * root locale), a <code>List</code> containing only the root
2604          * <code>Locale</code> must be returned. In this case, the
2605          * <code>ResourceBundle.getBundle</code> factory method loads only
2606          * the base bundle as the resulting resource bundle.
2607          *
2608          * <p>It is not a requirement to return an immutable (unmodifiable)
2609          * <code>List</code>. However, the returned <code>List</code> must not
2610          * be mutated after it has been returned by
2611          * <code>getCandidateLocales</code>.
2612          *
2613          * <p>The default implementation returns a <code>List</code> containing
2614          * <code>Locale</code>s using the rules described below.  In the
2615          * description below, <em>L</em>, <em>S</em>, <em>C</em> and <em>V</em>
2616          * respectively represent non-empty language, script, country, and
2617          * variant.  For example, [<em>L</em>, <em>C</em>] represents a
2618          * <code>Locale</code> that has non-empty values only for language and
2619          * country.  The form <em>L</em>("xx") represents the (non-empty)
2620          * language value is "xx".  For all cases, <code>Locale</code>s whose
2621          * final component values are empty strings are omitted.
2622          *
2623          * <ol><li>For an input <code>Locale</code> with an empty script value,
2624          * append candidate <code>Locale</code>s by omitting the final component
2625          * one by one as below:
2626          *
2627          * <ul>
2628          * <li> [<em>L</em>, <em>C</em>, <em>V</em>] </li>
2629          * <li> [<em>L</em>, <em>C</em>] </li>
2630          * <li> [<em>L</em>] </li>
2631          * <li> <code>Locale.ROOT</code> </li>
2632          * </ul></li>
2633          *
2634          * <li>For an input <code>Locale</code> with a non-empty script value,
2635          * append candidate <code>Locale</code>s by omitting the final component
2636          * up to language, then append candidates generated from the
2637          * <code>Locale</code> with country and variant restored:
2638          *
2639          * <ul>
2640          * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V</em>]</li>
2641          * <li> [<em>L</em>, <em>S</em>, <em>C</em>]</li>
2642          * <li> [<em>L</em>, <em>S</em>]</li>
2643          * <li> [<em>L</em>, <em>C</em>, <em>V</em>]</li>
2644          * <li> [<em>L</em>, <em>C</em>]</li>
2645          * <li> [<em>L</em>]</li>
2646          * <li> <code>Locale.ROOT</code></li>
2647          * </ul></li>
2648          *
2649          * <li>For an input <code>Locale</code> with a variant value consisting
2650          * of multiple subtags separated by underscore, generate candidate
2651          * <code>Locale</code>s by omitting the variant subtags one by one, then
2652          * insert them after every occurrence of <code> Locale</code>s with the
2653          * full variant value in the original list.  For example, if the
2654          * the variant consists of two subtags <em>V1</em> and <em>V2</em>:
2655          *
2656          * <ul>
2657          * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]</li>
2658          * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>]</li>
2659          * <li> [<em>L</em>, <em>S</em>, <em>C</em>]</li>
2660          * <li> [<em>L</em>, <em>S</em>]</li>
2661          * <li> [<em>L</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]</li>
2662          * <li> [<em>L</em>, <em>C</em>, <em>V1</em>]</li>
2663          * <li> [<em>L</em>, <em>C</em>]</li>
2664          * <li> [<em>L</em>]</li>
2665          * <li> <code>Locale.ROOT</code></li>
2666          * </ul></li>
2667          *
2668          * <li>Special cases for Chinese.  When an input <code>Locale</code> has the
2669          * language "zh" (Chinese) and an empty script value, either "Hans" (Simplified) or
2670          * "Hant" (Traditional) might be supplied, depending on the country.
2671          * When the country is "CN" (China) or "SG" (Singapore), "Hans" is supplied.
2672          * When the country is "HK" (Hong Kong SAR China), "MO" (Macau SAR China),
2673          * or "TW" (Taiwan), "Hant" is supplied.  For all other countries or when the country
2674          * is empty, no script is supplied.  For example, for <code>Locale("zh", "CN")
2675          * </code>, the candidate list will be:
2676          * <ul>
2677          * <li> [<em>L</em>("zh"), <em>S</em>("Hans"), <em>C</em>("CN")]</li>
2678          * <li> [<em>L</em>("zh"), <em>S</em>("Hans")]</li>
2679          * <li> [<em>L</em>("zh"), <em>C</em>("CN")]</li>
2680          * <li> [<em>L</em>("zh")]</li>
2681          * <li> <code>Locale.ROOT</code></li>
2682          * </ul>
2683          *
2684          * For <code>Locale("zh", "TW")</code>, the candidate list will be:
2685          * <ul>
2686          * <li> [<em>L</em>("zh"), <em>S</em>("Hant"), <em>C</em>("TW")]</li>
2687          * <li> [<em>L</em>("zh"), <em>S</em>("Hant")]</li>
2688          * <li> [<em>L</em>("zh"), <em>C</em>("TW")]</li>
2689          * <li> [<em>L</em>("zh")]</li>
2690          * <li> <code>Locale.ROOT</code></li>
2691          * </ul></li>
2692          *
2693          * <li>Special cases for Norwegian.  Both <code>Locale("no", "NO",
2694          * "NY")</code> and <code>Locale("nn", "NO")</code> represent Norwegian
2695          * Nynorsk.  When a locale's language is "nn", the standard candidate
2696          * list is generated up to [<em>L</em>("nn")], and then the following
2697          * candidates are added:
2698          *
2699          * <ul><li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("NY")]</li>
2700          * <li> [<em>L</em>("no"), <em>C</em>("NO")]</li>
2701          * <li> [<em>L</em>("no")]</li>
2702          * <li> <code>Locale.ROOT</code></li>
2703          * </ul>
2704          *
2705          * If the locale is exactly <code>Locale("no", "NO", "NY")</code>, it is first
2706          * converted to <code>Locale("nn", "NO")</code> and then the above procedure is
2707          * followed.
2708          *
2709          * <p>Also, Java treats the language "no" as a synonym of Norwegian
2710          * Bokmål "nb".  Except for the single case <code>Locale("no",
2711          * "NO", "NY")</code> (handled above), when an input <code>Locale</code>
2712          * has language "no" or "nb", candidate <code>Locale</code>s with
2713          * language code "no" and "nb" are interleaved, first using the
2714          * requested language, then using its synonym. For example,
2715          * <code>Locale("nb", "NO", "POSIX")</code> generates the following
2716          * candidate list:
2717          *
2718          * <ul>
2719          * <li> [<em>L</em>("nb"), <em>C</em>("NO"), <em>V</em>("POSIX")]</li>
2720          * <li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("POSIX")]</li>
2721          * <li> [<em>L</em>("nb"), <em>C</em>("NO")]</li>
2722          * <li> [<em>L</em>("no"), <em>C</em>("NO")]</li>
2723          * <li> [<em>L</em>("nb")]</li>
2724          * <li> [<em>L</em>("no")]</li>
2725          * <li> <code>Locale.ROOT</code></li>
2726          * </ul>
2727          *
2728          * <code>Locale("no", "NO", "POSIX")</code> would generate the same list
2729          * except that locales with "no" would appear before the corresponding
2730          * locales with "nb".</li>
2731          * </ol>
2732          *
2733          * <p>The default implementation uses an {@link ArrayList} that
2734          * overriding implementations may modify before returning it to the
2735          * caller. However, a subclass must not modify it after it has
2736          * been returned by <code>getCandidateLocales</code>.
2737          *
2738          * <p>For example, if the given <code>baseName</code> is "Messages"
2739          * and the given <code>locale</code> is
2740          * <code>Locale("ja",&nbsp;"",&nbsp;"XX")</code>, then a
2741          * <code>List</code> of <code>Locale</code>s:
2742          * <pre>
2743          *     Locale("ja", "", "XX")
2744          *     Locale("ja")
2745          *     Locale.ROOT
2746          * </pre>
2747          * is returned. And if the resource bundles for the "ja" and
2748          * "" <code>Locale</code>s are found, then the runtime resource
2749          * lookup path (parent chain) is:
2750          * <pre>{@code
2751          *     Messages_ja -> Messages
2752          * }</pre>
2753          *
2754          * @param baseName
2755          *        the base name of the resource bundle, a fully
2756          *        qualified class name
2757          * @param locale
2758          *        the locale for which a resource bundle is desired
2759          * @return a <code>List</code> of candidate
2760          *        <code>Locale</code>s for the given <code>locale</code>
2761          * @exception NullPointerException
2762          *        if <code>baseName</code> or <code>locale</code> is
2763          *        <code>null</code>
2764          */
2765         public List<Locale> getCandidateLocales(String baseName, Locale locale) {
2766             if (baseName == null) {
2767                 throw new NullPointerException();
2768             }
2769             return new ArrayList<>(CANDIDATES_CACHE.get(locale.getBaseLocale()));
2770         }
2771 
2772         private static final CandidateListCache CANDIDATES_CACHE = new CandidateListCache();
2773 
2774         private static class CandidateListCache extends LocaleObjectCache<BaseLocale, List<Locale>> {
2775             protected List<Locale> createObject(BaseLocale base) {
2776                 String language = base.getLanguage();
2777                 String script = base.getScript();
2778                 String region = base.getRegion();
2779                 String variant = base.getVariant();
2780 
2781                 // Special handling for Norwegian
2782                 boolean isNorwegianBokmal = false;
2783                 boolean isNorwegianNynorsk = false;
2784                 if (language.equals("no")) {
2785                     if (region.equals("NO") && variant.equals("NY")) {
2786                         variant = "";
2787                         isNorwegianNynorsk = true;
2788                     } else {
2789                         isNorwegianBokmal = true;
2790                     }
2791                 }
2792                 if (language.equals("nb") || isNorwegianBokmal) {
2793                     List<Locale> tmpList = getDefaultList("nb", script, region, variant);
2794                     // Insert a locale replacing "nb" with "no" for every list entry
2795                     List<Locale> bokmalList = new LinkedList<>();
2796                     for (Locale l : tmpList) {
2797                         bokmalList.add(l);
2798                         if (l.getLanguage().length() == 0) {
2799                             break;
2800                         }
2801                         bokmalList.add(Locale.getInstance("no", l.getScript(), l.getCountry(),
2802                                 l.getVariant(), null));
2803                     }
2804                     return bokmalList;
2805                 } else if (language.equals("nn") || isNorwegianNynorsk) {
2806                     // Insert no_NO_NY, no_NO, no after nn
2807                     List<Locale> nynorskList = getDefaultList("nn", script, region, variant);
2808                     int idx = nynorskList.size() - 1;
2809                     nynorskList.add(idx++, Locale.getInstance("no", "NO", "NY"));
2810                     nynorskList.add(idx++, Locale.getInstance("no", "NO", ""));
2811                     nynorskList.add(idx++, Locale.getInstance("no", "", ""));
2812                     return nynorskList;
2813                 }
2814                 // Special handling for Chinese
2815                 else if (language.equals("zh")) {
2816                     if (script.length() == 0 && region.length() > 0) {
2817                         // Supply script for users who want to use zh_Hans/zh_Hant
2818                         // as bundle names (recommended for Java7+)
2819                         switch (region) {
2820                         case "TW":
2821                         case "HK":
2822                         case "MO":
2823                             script = "Hant";
2824                             break;
2825                         case "CN":
2826                         case "SG":
2827                             script = "Hans";
2828                             break;
2829                         }
2830                     }
2831                 }
2832 
2833                 return getDefaultList(language, script, region, variant);
2834             }
2835 
2836             private static List<Locale> getDefaultList(String language, String script, String region, String variant) {
2837                 List<String> variants = null;
2838 
2839                 if (variant.length() > 0) {
2840                     variants = new LinkedList<>();
2841                     int idx = variant.length();
2842                     while (idx != -1) {
2843                         variants.add(variant.substring(0, idx));
2844                         idx = variant.lastIndexOf('_', --idx);
2845                     }
2846                 }
2847 
2848                 List<Locale> list = new LinkedList<>();
2849 
2850                 if (variants != null) {
2851                     for (String v : variants) {
2852                         list.add(Locale.getInstance(language, script, region, v, null));
2853                     }
2854                 }
2855                 if (region.length() > 0) {
2856                     list.add(Locale.getInstance(language, script, region, "", null));
2857                 }
2858                 if (script.length() > 0) {
2859                     list.add(Locale.getInstance(language, script, "", "", null));
2860                     // Special handling for Chinese
2861                     if (language.equals("zh")) {
2862                         if (region.length() == 0) {
2863                             // Supply region(country) for users who still package Chinese
2864                             // bundles using old convension.
2865                             switch (script) {
2866                                 case "Hans":
2867                                     region = "CN";
2868                                     break;
2869                                 case "Hant":
2870                                     region = "TW";
2871                                     break;
2872                             }
2873                         }
2874                     }
2875 
2876                     // With script, after truncating variant, region and script,
2877                     // start over without script.
2878                     if (variants != null) {
2879                         for (String v : variants) {
2880                             list.add(Locale.getInstance(language, "", region, v, null));
2881                         }
2882                     }
2883                     if (region.length() > 0) {
2884                         list.add(Locale.getInstance(language, "", region, "", null));
2885                     }
2886                 }
2887                 if (language.length() > 0) {
2888                     list.add(Locale.getInstance(language, "", "", "", null));
2889                 }
2890                 // Add root locale at the end
2891                 list.add(Locale.ROOT);
2892 
2893                 return list;
2894             }
2895         }
2896 
2897         /**
2898          * Returns a <code>Locale</code> to be used as a fallback locale for
2899          * further resource bundle searches by the
2900          * <code>ResourceBundle.getBundle</code> factory method. This method
2901          * is called from the factory method every time when no resulting
2902          * resource bundle has been found for <code>baseName</code> and
2903          * <code>locale</code>, where locale is either the parameter for
2904          * <code>ResourceBundle.getBundle</code> or the previous fallback
2905          * locale returned by this method.
2906          *
2907          * <p>The method returns <code>null</code> if no further fallback
2908          * search is desired.
2909          *
2910          * <p>The default implementation returns the {@linkplain
2911          * Locale#getDefault() default <code>Locale</code>} if the given
2912          * <code>locale</code> isn't the default one.  Otherwise,
2913          * <code>null</code> is returned.
2914          *
2915          * @param baseName
2916          *        the base name of the resource bundle, a fully
2917          *        qualified class name for which
2918          *        <code>ResourceBundle.getBundle</code> has been
2919          *        unable to find any resource bundles (except for the
2920          *        base bundle)
2921          * @param locale
2922          *        the <code>Locale</code> for which
2923          *        <code>ResourceBundle.getBundle</code> has been
2924          *        unable to find any resource bundles (except for the
2925          *        base bundle)
2926          * @return a <code>Locale</code> for the fallback search,
2927          *        or <code>null</code> if no further fallback search
2928          *        is desired.
2929          * @exception NullPointerException
2930          *        if <code>baseName</code> or <code>locale</code>
2931          *        is <code>null</code>
2932          */
2933         public Locale getFallbackLocale(String baseName, Locale locale) {
2934             if (baseName == null) {
2935                 throw new NullPointerException();
2936             }
2937             Locale defaultLocale = Locale.getDefault();
2938             return locale.equals(defaultLocale) ? null : defaultLocale;
2939         }
2940 
2941         /**
2942          * Instantiates a resource bundle for the given bundle name of the
2943          * given format and locale, using the given class loader if
2944          * necessary. This method returns <code>null</code> if there is no
2945          * resource bundle available for the given parameters. If a resource
2946          * bundle can't be instantiated due to an unexpected error, the
2947          * error must be reported by throwing an <code>Error</code> or
2948          * <code>Exception</code> rather than simply returning
2949          * <code>null</code>.
2950          *
2951          * <p>If the <code>reload</code> flag is <code>true</code>, it
2952          * indicates that this method is being called because the previously
2953          * loaded resource bundle has expired.
2954          *
2955          * @implSpec
2956          *
2957          * Resource bundles in named modules are subject to the encapsulation
2958          * rules specified by {@link Module#getResourceAsStream Module.getResourceAsStream}.
2959          * A resource bundle in a named module visible to the given class loader
2960          * is accessible when the package of the resource file corresponding
2961          * to the resource bundle is open unconditionally.
2962          *
2963          * <p>The default implementation instantiates a
2964          * <code>ResourceBundle</code> as follows.
2965          *
2966          * <ul>
2967          *
2968          * <li>The bundle name is obtained by calling {@link
2969          * #toBundleName(String, Locale) toBundleName(baseName,
2970          * locale)}.</li>
2971          *
2972          * <li>If <code>format</code> is <code>"java.class"</code>, the
2973          * {@link Class} specified by the bundle name is loaded with the
2974          * given class loader. If the {@code Class} is found and accessible
2975          * then the <code>ResourceBundle</code> is instantiated.  The
2976          * resource bundle is accessible if the package of the bundle class file
2977          * is open unconditionally; otherwise, {@code IllegalAccessException}
2978          * will be thrown.
2979          * Note that the <code>reload</code> flag is ignored for loading
2980          * class-based resource bundles in this default implementation.
2981          * </li>
2982          *
2983          * <li>If <code>format</code> is <code>"java.properties"</code>,
2984          * {@link #toResourceName(String, String) toResourceName(bundlename,
2985          * "properties")} is called to get the resource name.
2986          * If <code>reload</code> is <code>true</code>, {@link
2987          * ClassLoader#getResource(String) load.getResource} is called
2988          * to get a {@link URL} for creating a {@link
2989          * URLConnection}. This <code>URLConnection</code> is used to
2990          * {@linkplain URLConnection#setUseCaches(boolean) disable the
2991          * caches} of the underlying resource loading layers,
2992          * and to {@linkplain URLConnection#getInputStream() get an
2993          * <code>InputStream</code>}.
2994          * Otherwise, {@link ClassLoader#getResourceAsStream(String)
2995          * loader.getResourceAsStream} is called to get an {@link
2996          * InputStream}. Then, a {@link
2997          * PropertyResourceBundle} is constructed with the
2998          * <code>InputStream</code>.</li>
2999          *
3000          * <li>If <code>format</code> is neither <code>"java.class"</code>
3001          * nor <code>"java.properties"</code>, an
3002          * <code>IllegalArgumentException</code> is thrown.</li>
3003          *
3004          * </ul>
3005          *
3006          * @param baseName
3007          *        the base bundle name of the resource bundle, a fully
3008          *        qualified class name
3009          * @param locale
3010          *        the locale for which the resource bundle should be
3011          *        instantiated
3012          * @param format
3013          *        the resource bundle format to be loaded
3014          * @param loader
3015          *        the <code>ClassLoader</code> to use to load the bundle
3016          * @param reload
3017          *        the flag to indicate bundle reloading; <code>true</code>
3018          *        if reloading an expired resource bundle,
3019          *        <code>false</code> otherwise
3020          * @return the resource bundle instance,
3021          *        or <code>null</code> if none could be found.
3022          * @exception NullPointerException
3023          *        if <code>bundleName</code>, <code>locale</code>,
3024          *        <code>format</code>, or <code>loader</code> is
3025          *        <code>null</code>, or if <code>null</code> is returned by
3026          *        {@link #toBundleName(String, Locale) toBundleName}
3027          * @exception IllegalArgumentException
3028          *        if <code>format</code> is unknown, or if the resource
3029          *        found for the given parameters contains malformed data.
3030          * @exception ClassCastException
3031          *        if the loaded class cannot be cast to <code>ResourceBundle</code>
3032          * @exception IllegalAccessException
3033          *        if the class or its nullary constructor is not
3034          *        accessible.
3035          * @exception InstantiationException
3036          *        if the instantiation of a class fails for some other
3037          *        reason.
3038          * @exception ExceptionInInitializerError
3039          *        if the initialization provoked by this method fails.
3040          * @exception SecurityException
3041          *        If a security manager is present and creation of new
3042          *        instances is denied. See {@link Class#newInstance()}
3043          *        for details.
3044          * @exception IOException
3045          *        if an error occurred when reading resources using
3046          *        any I/O operations
3047          * @see java.util.spi.ResourceBundleProvider#getBundle(String, Locale)
3048          */
3049         public ResourceBundle newBundle(String baseName, Locale locale, String format,
3050                                         ClassLoader loader, boolean reload)
3051                     throws IllegalAccessException, InstantiationException, IOException {
3052             /*
3053              * Legacy mechanism to locate resource bundle in unnamed module only
3054              * that is visible to the given loader and accessible to the given caller.
3055              */
3056             String bundleName = toBundleName(baseName, locale);
3057             ResourceBundle bundle = null;
3058             if (format.equals("java.class")) {
3059                 try {
3060                     Class<?> c = loader.loadClass(bundleName);
3061                     // If the class isn't a ResourceBundle subclass, throw a
3062                     // ClassCastException.
3063                     if (ResourceBundle.class.isAssignableFrom(c)) {
3064                         @SuppressWarnings("unchecked")
3065                         Class<ResourceBundle> bundleClass = (Class<ResourceBundle>)c;
3066                         Module m = bundleClass.getModule();
3067 
3068                         // To access a resource bundle in a named module,
3069                         // either class-based or properties-based, the resource
3070                         // bundle must be opened unconditionally,
3071                         // same rule as accessing a resource file.
3072                         if (m.isNamed() && !m.isOpen(bundleClass.getPackageName())) {
3073                             throw new IllegalAccessException("unnamed module can't load " +
3074                                 bundleClass.getName() + " in " + m.toString());
3075                         }
3076                         try {
3077                             // bundle in a unnamed module
3078                             Constructor<ResourceBundle> ctor = bundleClass.getConstructor();
3079                             if (!Modifier.isPublic(ctor.getModifiers())) {
3080                                 return null;
3081                             }
3082 
3083                             // java.base may not be able to read the bundleClass's module.
3084                             PrivilegedAction<Void> pa1 = () -> { ctor.setAccessible(true); return null; };
3085                             AccessController.doPrivileged(pa1);
3086                             bundle = ctor.newInstance((Object[]) null);
3087                         } catch (InvocationTargetException e) {
3088                             uncheckedThrow(e);
3089                         }
3090                     } else {
3091                         throw new ClassCastException(c.getName()
3092                                 + " cannot be cast to ResourceBundle");
3093                     }
3094                 } catch (ClassNotFoundException|NoSuchMethodException e) {
3095                 }
3096             } else if (format.equals("java.properties")) {
3097                 final String resourceName = toResourceName0(bundleName, "properties");
3098                 if (resourceName == null) {
3099                     return bundle;
3100                 }
3101 
3102                 final boolean reloadFlag = reload;
3103                 InputStream stream = null;
3104                 try {
3105                     stream = AccessController.doPrivileged(
3106                         new PrivilegedExceptionAction<>() {
3107                             public InputStream run() throws IOException {
3108                                 URL url = loader.getResource(resourceName);
3109                                 if (url == null) return null;
3110 
3111                                 URLConnection connection = url.openConnection();
3112                                 if (reloadFlag) {
3113                                     // Disable caches to get fresh data for
3114                                     // reloading.
3115                                     connection.setUseCaches(false);
3116                                 }
3117                                 return connection.getInputStream();
3118                             }
3119                         });
3120                 } catch (PrivilegedActionException e) {
3121                     throw (IOException) e.getException();
3122                 }
3123                 if (stream != null) {
3124                     try {
3125                         bundle = new PropertyResourceBundle(stream);
3126                     } finally {
3127                         stream.close();
3128                     }
3129                 }
3130             } else {
3131                 throw new IllegalArgumentException("unknown format: " + format);
3132             }
3133             return bundle;
3134         }
3135 
3136         /**
3137          * Returns the time-to-live (TTL) value for resource bundles that
3138          * are loaded under this
3139          * <code>ResourceBundle.Control</code>. Positive time-to-live values
3140          * specify the number of milliseconds a bundle can remain in the
3141          * cache without being validated against the source data from which
3142          * it was constructed. The value 0 indicates that a bundle must be
3143          * validated each time it is retrieved from the cache. {@link
3144          * #TTL_DONT_CACHE} specifies that loaded resource bundles are not
3145          * put in the cache. {@link #TTL_NO_EXPIRATION_CONTROL} specifies
3146          * that loaded resource bundles are put in the cache with no
3147          * expiration control.
3148          *
3149          * <p>The expiration affects only the bundle loading process by the
3150          * <code>ResourceBundle.getBundle</code> factory method.  That is,
3151          * if the factory method finds a resource bundle in the cache that
3152          * has expired, the factory method calls the {@link
3153          * #needsReload(String, Locale, String, ClassLoader, ResourceBundle,
3154          * long) needsReload} method to determine whether the resource
3155          * bundle needs to be reloaded. If <code>needsReload</code> returns
3156          * <code>true</code>, the cached resource bundle instance is removed
3157          * from the cache. Otherwise, the instance stays in the cache,
3158          * updated with the new TTL value returned by this method.
3159          *
3160          * <p>All cached resource bundles are subject to removal from the
3161          * cache due to memory constraints of the runtime environment.
3162          * Returning a large positive value doesn't mean to lock loaded
3163          * resource bundles in the cache.
3164          *
3165          * <p>The default implementation returns {@link #TTL_NO_EXPIRATION_CONTROL}.
3166          *
3167          * @param baseName
3168          *        the base name of the resource bundle for which the
3169          *        expiration value is specified.
3170          * @param locale
3171          *        the locale of the resource bundle for which the
3172          *        expiration value is specified.
3173          * @return the time (0 or a positive millisecond offset from the
3174          *        cached time) to get loaded bundles expired in the cache,
3175          *        {@link #TTL_NO_EXPIRATION_CONTROL} to disable the
3176          *        expiration control, or {@link #TTL_DONT_CACHE} to disable
3177          *        caching.
3178          * @exception NullPointerException
3179          *        if <code>baseName</code> or <code>locale</code> is
3180          *        <code>null</code>
3181          */
3182         public long getTimeToLive(String baseName, Locale locale) {
3183             if (baseName == null || locale == null) {
3184                 throw new NullPointerException();
3185             }
3186             return TTL_NO_EXPIRATION_CONTROL;
3187         }
3188 
3189         /**
3190          * Determines if the expired <code>bundle</code> in the cache needs
3191          * to be reloaded based on the loading time given by
3192          * <code>loadTime</code> or some other criteria. The method returns
3193          * <code>true</code> if reloading is required; <code>false</code>
3194          * otherwise. <code>loadTime</code> is a millisecond offset since
3195          * the <a href="Calendar.html#Epoch"> <code>Calendar</code>
3196          * Epoch</a>.
3197          *
3198          * <p>
3199          * The calling <code>ResourceBundle.getBundle</code> factory method
3200          * calls this method on the <code>ResourceBundle.Control</code>
3201          * instance used for its current invocation, not on the instance
3202          * used in the invocation that originally loaded the resource
3203          * bundle.
3204          *
3205          * <p>The default implementation compares <code>loadTime</code> and
3206          * the last modified time of the source data of the resource
3207          * bundle. If it's determined that the source data has been modified
3208          * since <code>loadTime</code>, <code>true</code> is
3209          * returned. Otherwise, <code>false</code> is returned. This
3210          * implementation assumes that the given <code>format</code> is the
3211          * same string as its file suffix if it's not one of the default
3212          * formats, <code>"java.class"</code> or
3213          * <code>"java.properties"</code>.
3214          *
3215          * @param baseName
3216          *        the base bundle name of the resource bundle, a
3217          *        fully qualified class name
3218          * @param locale
3219          *        the locale for which the resource bundle
3220          *        should be instantiated
3221          * @param format
3222          *        the resource bundle format to be loaded
3223          * @param loader
3224          *        the <code>ClassLoader</code> to use to load the bundle
3225          * @param bundle
3226          *        the resource bundle instance that has been expired
3227          *        in the cache
3228          * @param loadTime
3229          *        the time when <code>bundle</code> was loaded and put
3230          *        in the cache
3231          * @return <code>true</code> if the expired bundle needs to be
3232          *        reloaded; <code>false</code> otherwise.
3233          * @exception NullPointerException
3234          *        if <code>baseName</code>, <code>locale</code>,
3235          *        <code>format</code>, <code>loader</code>, or
3236          *        <code>bundle</code> is <code>null</code>
3237          */
3238         public boolean needsReload(String baseName, Locale locale,
3239                                    String format, ClassLoader loader,
3240                                    ResourceBundle bundle, long loadTime) {
3241             if (bundle == null) {
3242                 throw new NullPointerException();
3243             }
3244             if (format.equals("java.class") || format.equals("java.properties")) {
3245                 format = format.substring(5);
3246             }
3247             boolean result = false;
3248             try {
3249                 String resourceName = toResourceName0(toBundleName(baseName, locale), format);
3250                 if (resourceName == null) {
3251                     return result;
3252                 }
3253                 URL url = loader.getResource(resourceName);
3254                 if (url != null) {
3255                     long lastModified = 0;
3256                     URLConnection connection = url.openConnection();
3257                     if (connection != null) {
3258                         // disable caches to get the correct data
3259                         connection.setUseCaches(false);
3260                         if (connection instanceof JarURLConnection) {
3261                             JarEntry ent = ((JarURLConnection)connection).getJarEntry();
3262                             if (ent != null) {
3263                                 lastModified = ent.getTime();
3264                                 if (lastModified == -1) {
3265                                     lastModified = 0;
3266                                 }
3267                             }
3268                         } else {
3269                             lastModified = connection.getLastModified();
3270                         }
3271                     }
3272                     result = lastModified >= loadTime;
3273                 }
3274             } catch (NullPointerException npe) {
3275                 throw npe;
3276             } catch (Exception e) {
3277                 // ignore other exceptions
3278             }
3279             return result;
3280         }
3281 
3282         /**
3283          * Converts the given <code>baseName</code> and <code>locale</code>
3284          * to the bundle name. This method is called from the default
3285          * implementation of the {@link #newBundle(String, Locale, String,
3286          * ClassLoader, boolean) newBundle} and {@link #needsReload(String,
3287          * Locale, String, ClassLoader, ResourceBundle, long) needsReload}
3288          * methods.
3289          *
3290          * <p>This implementation returns the following value:
3291          * <pre>
3292          *     baseName + "_" + language + "_" + script + "_" + country + "_" + variant
3293          * </pre>
3294          * where <code>language</code>, <code>script</code>, <code>country</code>,
3295          * and <code>variant</code> are the language, script, country, and variant
3296          * values of <code>locale</code>, respectively. Final component values that
3297          * are empty Strings are omitted along with the preceding '_'.  When the
3298          * script is empty, the script value is omitted along with the preceding '_'.
3299          * If all of the values are empty strings, then <code>baseName</code>
3300          * is returned.
3301          *
3302          * <p>For example, if <code>baseName</code> is
3303          * <code>"baseName"</code> and <code>locale</code> is
3304          * <code>Locale("ja",&nbsp;"",&nbsp;"XX")</code>, then
3305          * <code>"baseName_ja_&thinsp;_XX"</code> is returned. If the given
3306          * locale is <code>Locale("en")</code>, then
3307          * <code>"baseName_en"</code> is returned.
3308          *
3309          * <p>Overriding this method allows applications to use different
3310          * conventions in the organization and packaging of localized
3311          * resources.
3312          *
3313          * @param baseName
3314          *        the base name of the resource bundle, a fully
3315          *        qualified class name
3316          * @param locale
3317          *        the locale for which a resource bundle should be
3318          *        loaded
3319          * @return the bundle name for the resource bundle
3320          * @exception NullPointerException
3321          *        if <code>baseName</code> or <code>locale</code>
3322          *        is <code>null</code>
3323          * @see java.util.spi.AbstractResourceBundleProvider#toBundleName(String, Locale)
3324          */
3325         public String toBundleName(String baseName, Locale locale) {
3326             if (locale == Locale.ROOT) {
3327                 return baseName;
3328             }
3329 
3330             String language = locale.getLanguage();
3331             String script = locale.getScript();
3332             String country = locale.getCountry();
3333             String variant = locale.getVariant();
3334 
3335             if (language == "" && country == "" && variant == "") {
3336                 return baseName;
3337             }
3338 
3339             StringBuilder sb = new StringBuilder(baseName);
3340             sb.append('_');
3341             if (script != "") {
3342                 if (variant != "") {
3343                     sb.append(language).append('_').append(script).append('_').append(country).append('_').append(variant);
3344                 } else if (country != "") {
3345                     sb.append(language).append('_').append(script).append('_').append(country);
3346                 } else {
3347                     sb.append(language).append('_').append(script);
3348                 }
3349             } else {
3350                 if (variant != "") {
3351                     sb.append(language).append('_').append(country).append('_').append(variant);
3352                 } else if (country != "") {
3353                     sb.append(language).append('_').append(country);
3354                 } else {
3355                     sb.append(language);
3356                 }
3357             }
3358             return sb.toString();
3359 
3360         }
3361 
3362         /**
3363          * Converts the given <code>bundleName</code> to the form required
3364          * by the {@link ClassLoader#getResource ClassLoader.getResource}
3365          * method by replacing all occurrences of <code>'.'</code> in
3366          * <code>bundleName</code> with <code>'/'</code> and appending a
3367          * <code>'.'</code> and the given file <code>suffix</code>. For
3368          * example, if <code>bundleName</code> is
3369          * <code>"foo.bar.MyResources_ja_JP"</code> and <code>suffix</code>
3370          * is <code>"properties"</code>, then
3371          * <code>"foo/bar/MyResources_ja_JP.properties"</code> is returned.
3372          *
3373          * @param bundleName
3374          *        the bundle name
3375          * @param suffix
3376          *        the file type suffix
3377          * @return the converted resource name
3378          * @exception NullPointerException
3379          *         if <code>bundleName</code> or <code>suffix</code>
3380          *         is <code>null</code>
3381          */
3382         public final String toResourceName(String bundleName, String suffix) {
3383             StringBuilder sb = new StringBuilder(bundleName.length() + 1 + suffix.length());
3384             sb.append(bundleName.replace('.', '/')).append('.').append(suffix);
3385             return sb.toString();
3386         }
3387 
3388         private String toResourceName0(String bundleName, String suffix) {
3389             // application protocol check
3390             if (bundleName.contains("://")) {
3391                 return null;
3392             } else {
3393                 return toResourceName(bundleName, suffix);
3394             }
3395         }
3396     }
3397 
3398     @SuppressWarnings("unchecked")
3399     private static <T extends Throwable> void uncheckedThrow(Throwable t) throws T {
3400         if (t != null)
3401             throw (T)t;
3402         else
3403             throw new Error("Unknown Exception");
3404     }
3405 
3406     private static class SingleFormatControl extends Control {
3407         private static final Control PROPERTIES_ONLY
3408             = new SingleFormatControl(FORMAT_PROPERTIES);
3409 
3410         private static final Control CLASS_ONLY
3411             = new SingleFormatControl(FORMAT_CLASS);
3412 
3413         private final List<String> formats;
3414 
3415         protected SingleFormatControl(List<String> formats) {
3416             this.formats = formats;
3417         }
3418 
3419         public List<String> getFormats(String baseName) {
3420             if (baseName == null) {
3421                 throw new NullPointerException();
3422             }
3423             return formats;
3424         }
3425     }
3426 
3427     private static final class NoFallbackControl extends SingleFormatControl {
3428         private static final Control NO_FALLBACK
3429             = new NoFallbackControl(FORMAT_DEFAULT);
3430 
3431         private static final Control PROPERTIES_ONLY_NO_FALLBACK
3432             = new NoFallbackControl(FORMAT_PROPERTIES);
3433 
3434         private static final Control CLASS_ONLY_NO_FALLBACK
3435             = new NoFallbackControl(FORMAT_CLASS);
3436 
3437         protected NoFallbackControl(List<String> formats) {
3438             super(formats);
3439         }
3440 
3441         public Locale getFallbackLocale(String baseName, Locale locale) {
3442             if (baseName == null || locale == null) {
3443                 throw new NullPointerException();
3444             }
3445             return null;
3446         }
3447     }
3448 
3449     private static class ResourceBundleProviderHelper {
3450         /**
3451          * Returns a new ResourceBundle instance of the given bundleClass
3452          */
3453         static ResourceBundle newResourceBundle(Class<? extends ResourceBundle> bundleClass) {
3454             try {
3455                 @SuppressWarnings("unchecked")
3456                 Constructor<? extends ResourceBundle> ctor =
3457                     bundleClass.getConstructor();
3458                 if (!Modifier.isPublic(ctor.getModifiers())) {
3459                     return null;
3460                 }
3461                 // java.base may not be able to read the bundleClass's module.
3462                 PrivilegedAction<Void> pa = () -> { ctor.setAccessible(true); return null;};
3463                 AccessController.doPrivileged(pa);
3464                 try {
3465                     return ctor.newInstance((Object[]) null);
3466                 } catch (InvocationTargetException e) {
3467                     uncheckedThrow(e);
3468                 } catch (InstantiationException | IllegalAccessException e) {
3469                     throw new InternalError(e);
3470                 }
3471             } catch (NoSuchMethodException e) {
3472                 throw new InternalError(e);
3473             }
3474             return null;
3475         }
3476 
3477         /**
3478          * Loads a {@code ResourceBundle} of the given {@code bundleName} local to
3479          * the given {@code module}. If not found, search the bundle class
3480          * that is visible from the module's class loader.
3481          *
3482          * The caller module is used for access check only.
3483          */
3484         static ResourceBundle loadResourceBundle(Module callerModule,
3485                                                  Module module,
3486                                                  String baseName,
3487                                                  Locale locale)
3488         {
3489             String bundleName = Control.INSTANCE.toBundleName(baseName, locale);
3490             try {
3491                 PrivilegedAction<Class<?>> pa = () -> Class.forName(module, bundleName);
3492                 Class<?> c = AccessController.doPrivileged(pa, null, GET_CLASSLOADER_PERMISSION);
3493                 trace("local in %s %s caller %s: %s%n", module, bundleName, callerModule, c);
3494 
3495                 if (c == null) {
3496                     // if not found from the given module, locate resource bundle
3497                     // that is visible to the module's class loader
3498                     ClassLoader loader = getLoader(module);
3499                     if (loader != null) {
3500                         c = Class.forName(bundleName, false, loader);
3501                     } else {
3502                         c = BootLoader.loadClassOrNull(bundleName);
3503                     }
3504                     trace("loader for %s %s caller %s: %s%n", module, bundleName, callerModule, c);
3505                 }
3506 
3507                 if (c != null && ResourceBundle.class.isAssignableFrom(c)) {
3508                     @SuppressWarnings("unchecked")
3509                     Class<ResourceBundle> bundleClass = (Class<ResourceBundle>) c;
3510                     Module m = bundleClass.getModule();
3511                     if (!isAccessible(callerModule, m, bundleClass.getPackageName())) {
3512                         trace("   %s does not have access to %s/%s%n", callerModule,
3513                               m.getName(), bundleClass.getPackageName());
3514                         return null;
3515                     }
3516 
3517                     return newResourceBundle(bundleClass);
3518                 }
3519             } catch (ClassNotFoundException e) {}
3520             return null;
3521         }
3522 
3523         /**
3524          * Tests if resources of the given package name from the given module are
3525          * open to the caller module.
3526          */
3527         static boolean isAccessible(Module callerModule, Module module, String pn) {
3528             if (!module.isNamed() || callerModule == module)
3529                 return true;
3530 
3531             return module.isOpen(pn, callerModule);
3532         }
3533 
3534         /**
3535          * Loads properties of the given {@code bundleName} local in the given
3536          * {@code module}.  If the .properties is not found or not open
3537          * to the caller module to access, it will find the resource that
3538          * is visible to the module's class loader.
3539          *
3540          * The caller module is used for access check only.
3541          */
3542         static ResourceBundle loadPropertyResourceBundle(Module callerModule,
3543                                                          Module module,
3544                                                          String baseName,
3545                                                          Locale locale)
3546             throws IOException
3547         {
3548             String bundleName = Control.INSTANCE.toBundleName(baseName, locale);
3549 
3550             PrivilegedAction<InputStream> pa = () -> {
3551                 try {
3552                     String resourceName = Control.INSTANCE
3553                         .toResourceName0(bundleName, "properties");
3554                     if (resourceName == null) {
3555                         return null;
3556                     }
3557                     trace("local in %s %s caller %s%n", module, resourceName, callerModule);
3558 
3559                     // if the package is in the given module but not opened
3560                     // locate it from the given module first.
3561                     String pn = toPackageName(bundleName);
3562                     trace("   %s/%s is accessible to %s : %s%n",
3563                             module.getName(), pn, callerModule,
3564                             isAccessible(callerModule, module, pn));
3565                     if (isAccessible(callerModule, module, pn)) {
3566                         InputStream in = module.getResourceAsStream(resourceName);
3567                         if (in != null) {
3568                             return in;
3569                         }
3570                     }
3571 
3572                     ClassLoader loader = module.getClassLoader();
3573                     trace("loader for %s %s caller %s%n", module, resourceName, callerModule);
3574 
3575                     try {
3576                         if (loader != null) {
3577                             return loader.getResourceAsStream(resourceName);
3578                         } else {
3579                             URL url = BootLoader.findResource(resourceName);
3580                             if (url != null) {
3581                                 return url.openStream();
3582                             }
3583                         }
3584                     } catch (Exception e) {}
3585                     return null;
3586 
3587                 } catch (IOException e) {
3588                     throw new UncheckedIOException(e);
3589                 }
3590             };
3591 
3592             try (InputStream stream = AccessController.doPrivileged(pa)) {
3593                 if (stream != null) {
3594                     return new PropertyResourceBundle(stream);
3595                 } else {
3596                     return null;
3597                 }
3598             } catch (UncheckedIOException e) {
3599                 throw e.getCause();
3600             }
3601         }
3602 
3603         private static String toPackageName(String bundleName) {
3604             int i = bundleName.lastIndexOf('.');
3605             return i != -1 ? bundleName.substring(0, i) : "";
3606         }
3607 
3608     }
3609 
3610     private static final boolean TRACE_ON = Boolean.valueOf(
3611         GetPropertyAction.privilegedGetProperty("resource.bundle.debug", "false"));
3612 
3613     private static void trace(String format, Object... params) {
3614         if (TRACE_ON)
3615             System.out.format(format, params);
3616     }
3617 }
--- EOF ---