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