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