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