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 class="borderless"> 1226 * <caption style="display:none">getBundle() locale to resource bundle mapping</caption> 1227 * <tbody> 1228 * <tr><td>Locale("fr", "CH")</td><td>MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class</td></tr> 1229 * <tr><td>Locale("fr", "FR")</td><td>MyResources_fr.properties, parent MyResources.class</td></tr> 1230 * <tr><td>Locale("de", "DE")</td><td>MyResources_en.properties, parent MyResources.class</td></tr> 1231 * <tr><td>Locale("en", "US")</td><td>MyResources_en.properties, parent MyResources.class</td></tr> 1232 * <tr><td>Locale("es", "ES")</td><td>MyResources_es_ES.class, parent MyResources.class</td></tr> 1233 * </tbody> 1234 * </table> 1235 * 1236 * <p>The file MyResources_fr_CH.properties is never used because it is 1237 * hidden by the MyResources_fr_CH.class. Likewise, MyResources.properties 1238 * is also hidden by MyResources.class. 1239 * 1240 * @apiNote If the caller module is a named module and the given 1241 * {@code loader} is the caller module's class loader, this method is 1242 * equivalent to {@code getBundle(baseName, locale)}; otherwise, it will not 1243 * find resource bundles from named modules. 1244 * Use {@link #getBundle(String, Locale, Module)} to load resource bundles 1245 * on behalf on a specific module instead. 1246 * 1247 * @param baseName the base name of the resource bundle, a fully qualified class name 1248 * @param locale the locale for which a resource bundle is desired 1249 * @param loader the class loader from which to load the resource bundle 1250 * @return a resource bundle for the given base name and locale 1251 * @exception java.lang.NullPointerException 1252 * if <code>baseName</code>, <code>locale</code>, or <code>loader</code> is <code>null</code> 1253 * @exception MissingResourceException 1254 * if no resource bundle for the specified base name can be found 1255 * @since 1.2 1256 * @revised 9 1257 * @spec JPMS 1258 */ 1259 @CallerSensitive 1260 public static ResourceBundle getBundle(String baseName, Locale locale, 1261 ClassLoader loader) 1262 { 1263 if (loader == null) { 1264 throw new NullPointerException(); 1265 } 1266 Class<?> caller = Reflection.getCallerClass(); 1267 return getBundleImpl(baseName, locale, caller, loader, getDefaultControl(caller, baseName)); 1268 } 1269 1270 /** 1271 * Returns a resource bundle using the specified base name, target 1272 * locale, class loader and control. Unlike the {@linkplain 1273 * #getBundle(String, Locale, ClassLoader) <code>getBundle</code> 1274 * factory methods with no <code>control</code> argument}, the given 1275 * <code>control</code> specifies how to locate and instantiate resource 1276 * bundles. Conceptually, the bundle loading process with the given 1277 * <code>control</code> is performed in the following steps. 1278 * 1279 * <ol> 1280 * <li>This factory method looks up the resource bundle in the cache for 1281 * the specified <code>baseName</code>, <code>targetLocale</code> and 1282 * <code>loader</code>. If the requested resource bundle instance is 1283 * found in the cache and the time-to-live periods of the instance and 1284 * all of its parent instances have not expired, the instance is returned 1285 * to the caller. Otherwise, this factory method proceeds with the 1286 * loading process below.</li> 1287 * 1288 * <li>The {@link ResourceBundle.Control#getFormats(String) 1289 * control.getFormats} method is called to get resource bundle formats 1290 * to produce bundle or resource names. The strings 1291 * <code>"java.class"</code> and <code>"java.properties"</code> 1292 * designate class-based and {@linkplain PropertyResourceBundle 1293 * property}-based resource bundles, respectively. Other strings 1294 * starting with <code>"java."</code> are reserved for future extensions 1295 * and must not be used for application-defined formats. Other strings 1296 * designate application-defined formats.</li> 1297 * 1298 * <li>The {@link ResourceBundle.Control#getCandidateLocales(String, 1299 * Locale) control.getCandidateLocales} method is called with the target 1300 * locale to get a list of <em>candidate <code>Locale</code>s</em> for 1301 * which resource bundles are searched.</li> 1302 * 1303 * <li>The {@link ResourceBundle.Control#newBundle(String, Locale, 1304 * String, ClassLoader, boolean) control.newBundle} method is called to 1305 * instantiate a <code>ResourceBundle</code> for the base bundle name, a 1306 * candidate locale, and a format. (Refer to the note on the cache 1307 * lookup below.) This step is iterated over all combinations of the 1308 * candidate locales and formats until the <code>newBundle</code> method 1309 * returns a <code>ResourceBundle</code> instance or the iteration has 1310 * used up all the combinations. For example, if the candidate locales 1311 * are <code>Locale("de", "DE")</code>, <code>Locale("de")</code> and 1312 * <code>Locale("")</code> and the formats are <code>"java.class"</code> 1313 * and <code>"java.properties"</code>, then the following is the 1314 * sequence of locale-format combinations to be used to call 1315 * <code>control.newBundle</code>. 1316 * 1317 * <table class=striped style="width: 50%; text-align: left; margin-left: 40px;"> 1318 * <caption style="display:none">locale-format combinations for newBundle</caption> 1319 * <thead> 1320 * <tr> 1321 * <td 1322 * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;"><code>Locale</code><br> 1323 * </td> 1324 * <td 1325 * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;"><code>format</code><br> 1326 * </td> 1327 * </tr> 1328 * </thead> 1329 * <tbody> 1330 * <tr> 1331 * <td style="vertical-align: top; width: 50%;"><code>Locale("de", "DE")</code><br> 1332 * </td> 1333 * <td style="vertical-align: top; width: 50%;"><code>java.class</code><br> 1334 * </td> 1335 * </tr> 1336 * <tr> 1337 * <td style="vertical-align: top; width: 50%;"><code>Locale("de", "DE")</code></td> 1338 * <td style="vertical-align: top; width: 50%;"><code>java.properties</code><br> 1339 * </td> 1340 * </tr> 1341 * <tr> 1342 * <td style="vertical-align: top; width: 50%;"><code>Locale("de")</code></td> 1343 * <td style="vertical-align: top; width: 50%;"><code>java.class</code></td> 1344 * </tr> 1345 * <tr> 1346 * <td style="vertical-align: top; width: 50%;"><code>Locale("de")</code></td> 1347 * <td style="vertical-align: top; width: 50%;"><code>java.properties</code></td> 1348 * </tr> 1349 * <tr> 1350 * <td style="vertical-align: top; width: 50%;"><code>Locale("")</code><br> 1351 * </td> 1352 * <td style="vertical-align: top; width: 50%;"><code>java.class</code></td> 1353 * </tr> 1354 * <tr> 1355 * <td style="vertical-align: top; width: 50%;"><code>Locale("")</code></td> 1356 * <td style="vertical-align: top; width: 50%;"><code>java.properties</code></td> 1357 * </tr> 1358 * </tbody> 1359 * </table> 1360 * </li> 1361 * 1362 * <li>If the previous step has found no resource bundle, proceed to 1363 * Step 6. If a bundle has been found that is a base bundle (a bundle 1364 * for <code>Locale("")</code>), and the candidate locale list only contained 1365 * <code>Locale("")</code>, return the bundle to the caller. If a bundle 1366 * has been found that is a base bundle, but the candidate locale list 1367 * contained locales other than Locale(""), put the bundle on hold and 1368 * proceed to Step 6. If a bundle has been found that is not a base 1369 * bundle, proceed to Step 7.</li> 1370 * 1371 * <li>The {@link ResourceBundle.Control#getFallbackLocale(String, 1372 * Locale) control.getFallbackLocale} method is called to get a fallback 1373 * locale (alternative to the current target locale) to try further 1374 * finding a resource bundle. If the method returns a non-null locale, 1375 * it becomes the next target locale and the loading process starts over 1376 * from Step 3. Otherwise, if a base bundle was found and put on hold in 1377 * a previous Step 5, it is returned to the caller now. Otherwise, a 1378 * MissingResourceException is thrown.</li> 1379 * 1380 * <li>At this point, we have found a resource bundle that's not the 1381 * base bundle. If this bundle set its parent during its instantiation, 1382 * it is returned to the caller. Otherwise, its <a 1383 * href="./ResourceBundle.html#parent_chain">parent chain</a> is 1384 * instantiated based on the list of candidate locales from which it was 1385 * found. Finally, the bundle is returned to the caller.</li> 1386 * </ol> 1387 * 1388 * <p>During the resource bundle loading process above, this factory 1389 * method looks up the cache before calling the {@link 1390 * Control#newBundle(String, Locale, String, ClassLoader, boolean) 1391 * control.newBundle} method. If the time-to-live period of the 1392 * resource bundle found in the cache has expired, the factory method 1393 * calls the {@link ResourceBundle.Control#needsReload(String, Locale, 1394 * String, ClassLoader, ResourceBundle, long) control.needsReload} 1395 * method to determine whether the resource bundle needs to be reloaded. 1396 * If reloading is required, the factory method calls 1397 * <code>control.newBundle</code> to reload the resource bundle. If 1398 * <code>control.newBundle</code> returns <code>null</code>, the factory 1399 * method puts a dummy resource bundle in the cache as a mark of 1400 * nonexistent resource bundles in order to avoid lookup overhead for 1401 * subsequent requests. Such dummy resource bundles are under the same 1402 * expiration control as specified by <code>control</code>. 1403 * 1404 * <p>All resource bundles loaded are cached by default. Refer to 1405 * {@link Control#getTimeToLive(String,Locale) 1406 * control.getTimeToLive} for details. 1407 * 1408 * <p>The following is an example of the bundle loading process with the 1409 * default <code>ResourceBundle.Control</code> implementation. 1410 * 1411 * <p>Conditions: 1412 * <ul> 1413 * <li>Base bundle name: <code>foo.bar.Messages</code> 1414 * <li>Requested <code>Locale</code>: {@link Locale#ITALY}</li> 1415 * <li>Default <code>Locale</code>: {@link Locale#FRENCH}</li> 1416 * <li>Available resource bundles: 1417 * <code>foo/bar/Messages_fr.properties</code> and 1418 * <code>foo/bar/Messages.properties</code></li> 1419 * </ul> 1420 * 1421 * <p>First, <code>getBundle</code> tries loading a resource bundle in 1422 * the following sequence. 1423 * 1424 * <ul> 1425 * <li>class <code>foo.bar.Messages_it_IT</code> 1426 * <li>file <code>foo/bar/Messages_it_IT.properties</code> 1427 * <li>class <code>foo.bar.Messages_it</code></li> 1428 * <li>file <code>foo/bar/Messages_it.properties</code></li> 1429 * <li>class <code>foo.bar.Messages</code></li> 1430 * <li>file <code>foo/bar/Messages.properties</code></li> 1431 * </ul> 1432 * 1433 * <p>At this point, <code>getBundle</code> finds 1434 * <code>foo/bar/Messages.properties</code>, which is put on hold 1435 * because it's the base bundle. <code>getBundle</code> calls {@link 1436 * Control#getFallbackLocale(String, Locale) 1437 * control.getFallbackLocale("foo.bar.Messages", Locale.ITALY)} which 1438 * returns <code>Locale.FRENCH</code>. Next, <code>getBundle</code> 1439 * tries loading a bundle in the following sequence. 1440 * 1441 * <ul> 1442 * <li>class <code>foo.bar.Messages_fr</code></li> 1443 * <li>file <code>foo/bar/Messages_fr.properties</code></li> 1444 * <li>class <code>foo.bar.Messages</code></li> 1445 * <li>file <code>foo/bar/Messages.properties</code></li> 1446 * </ul> 1447 * 1448 * <p><code>getBundle</code> finds 1449 * <code>foo/bar/Messages_fr.properties</code> and creates a 1450 * <code>ResourceBundle</code> instance. Then, <code>getBundle</code> 1451 * sets up its parent chain from the list of the candidate locales. Only 1452 * <code>foo/bar/Messages.properties</code> is found in the list and 1453 * <code>getBundle</code> creates a <code>ResourceBundle</code> instance 1454 * that becomes the parent of the instance for 1455 * <code>foo/bar/Messages_fr.properties</code>. 1456 * 1457 * @param baseName 1458 * the base name of the resource bundle, a fully qualified 1459 * class name 1460 * @param targetLocale 1461 * the locale for which a resource bundle is desired 1462 * @param loader 1463 * the class loader from which to load the resource bundle 1464 * @param control 1465 * the control which gives information for the resource 1466 * bundle loading process 1467 * @return a resource bundle for the given base name and locale 1468 * @throws NullPointerException 1469 * if <code>baseName</code>, <code>targetLocale</code>, 1470 * <code>loader</code>, or <code>control</code> is 1471 * <code>null</code> 1472 * @throws MissingResourceException 1473 * if no resource bundle for the specified base name can be found 1474 * @throws IllegalArgumentException 1475 * if the given <code>control</code> doesn't perform properly 1476 * (e.g., <code>control.getCandidateLocales</code> returns null.) 1477 * Note that validation of <code>control</code> is performed as 1478 * needed. 1479 * @throws UnsupportedOperationException 1480 * if this method is called in a named module 1481 * @since 1.6 1482 * @revised 9 1483 * @spec JPMS 1484 */ 1485 @CallerSensitive 1486 public static ResourceBundle getBundle(String baseName, Locale targetLocale, 1487 ClassLoader loader, Control control) { 1488 if (loader == null || control == null) { 1489 throw new NullPointerException(); 1490 } 1491 Class<?> caller = Reflection.getCallerClass(); 1492 checkNamedModule(caller); 1493 return getBundleImpl(baseName, targetLocale, caller, loader, control); 1494 } 1495 1496 private static Control getDefaultControl(Class<?> caller, String baseName) { 1497 return getDefaultControl(caller.getModule(), baseName); 1498 } 1499 1500 private static Control getDefaultControl(Module targetModule, String baseName) { 1501 return targetModule.isNamed() ? 1502 Control.INSTANCE : 1503 ResourceBundleControlProviderHolder.getControl(baseName); 1504 } 1505 1506 private static class ResourceBundleControlProviderHolder { 1507 private static final PrivilegedAction<List<ResourceBundleControlProvider>> pa = 1508 () -> { 1509 return Collections.unmodifiableList( 1510 ServiceLoader.load(ResourceBundleControlProvider.class, 1511 ClassLoader.getSystemClassLoader()).stream() 1512 .map(ServiceLoader.Provider::get) 1513 .collect(Collectors.toList())); 1514 }; 1515 1516 private static final List<ResourceBundleControlProvider> CONTROL_PROVIDERS = 1517 AccessController.doPrivileged(pa); 1518 1519 private static Control getControl(String baseName) { 1520 return CONTROL_PROVIDERS.isEmpty() ? 1521 Control.INSTANCE : 1522 CONTROL_PROVIDERS.stream() 1523 .flatMap(provider -> Stream.ofNullable(provider.getControl(baseName))) 1524 .findFirst() 1525 .orElse(Control.INSTANCE); 1526 } 1527 } 1528 1529 private static void checkNamedModule(Class<?> caller) { 1530 if (caller.getModule().isNamed()) { 1531 throw new UnsupportedOperationException( 1532 "ResourceBundle.Control not supported in named modules"); 1533 } 1534 } 1535 1536 private static ResourceBundle getBundleImpl(String baseName, 1537 Locale locale, 1538 Class<?> caller, 1539 Control control) { 1540 return getBundleImpl(baseName, locale, caller, caller.getClassLoader(), control); 1541 } 1542 1543 /** 1544 * This method will find resource bundles using the legacy mechanism 1545 * if the caller is unnamed module or the given class loader is 1546 * not the class loader of the caller module getting the resource 1547 * bundle, i.e. find the class that is visible to the class loader 1548 * and properties from unnamed module. 1549 * 1550 * The module-aware resource bundle lookup mechanism will load 1551 * the service providers using the service loader mechanism 1552 * as well as properties local in the caller module. 1553 */ 1554 private static ResourceBundle getBundleImpl(String baseName, 1555 Locale locale, 1556 Class<?> caller, 1557 ClassLoader loader, 1558 Control control) { 1559 if (caller == null) { 1560 throw new InternalError("null caller"); 1561 } 1562 Module callerModule = caller.getModule(); 1563 1564 // get resource bundles for a named module only if loader is the module's class loader 1565 if (callerModule.isNamed() && loader == getLoader(callerModule)) { 1566 return getBundleImpl(callerModule, callerModule, baseName, locale, control); 1567 } 1568 1569 // find resource bundles from unnamed module of given class loader 1570 // Java agent can add to the bootclasspath e.g. via 1571 // java.lang.instrument.Instrumentation and load classes in unnamed module. 1572 // It may call RB::getBundle that will end up here with loader == null. 1573 Module unnamedModule = loader != null 1574 ? loader.getUnnamedModule() 1575 : BootLoader.getUnnamedModule(); 1576 1577 return getBundleImpl(callerModule, unnamedModule, baseName, locale, control); 1578 } 1579 1580 private static ResourceBundle getBundleFromModule(Class<?> caller, 1581 Module module, 1582 String baseName, 1583 Locale locale, 1584 Control control) { 1585 Objects.requireNonNull(module); 1586 Module callerModule = caller.getModule(); 1587 if (callerModule != module) { 1588 SecurityManager sm = System.getSecurityManager(); 1589 if (sm != null) { 1590 sm.checkPermission(GET_CLASSLOADER_PERMISSION); 1591 } 1592 } 1593 return getBundleImpl(callerModule, module, baseName, locale, control); 1594 } 1595 1596 private static ResourceBundle getBundleImpl(Module callerModule, 1597 Module module, 1598 String baseName, 1599 Locale locale, 1600 Control control) { 1601 if (locale == null || control == null) { 1602 throw new NullPointerException(); 1603 } 1604 1605 // We create a CacheKey here for use by this call. The base name 1606 // and modules will never change during the bundle loading 1607 // process. We have to make sure that the locale is set before 1608 // using it as a cache key. 1609 CacheKey cacheKey = new CacheKey(baseName, locale, module, callerModule); 1610 ResourceBundle bundle = null; 1611 1612 // Quick lookup of the cache. 1613 BundleReference bundleRef = cacheList.get(cacheKey); 1614 if (bundleRef != null) { 1615 bundle = bundleRef.get(); 1616 bundleRef = null; 1617 } 1618 1619 // If this bundle and all of its parents are valid (not expired), 1620 // then return this bundle. If any of the bundles is expired, we 1621 // don't call control.needsReload here but instead drop into the 1622 // complete loading process below. 1623 if (isValidBundle(bundle) && hasValidParentChain(bundle)) { 1624 return bundle; 1625 } 1626 1627 // No valid bundle was found in the cache, so we need to load the 1628 // resource bundle and its parents. 1629 1630 boolean isKnownControl = (control == Control.INSTANCE) || 1631 (control instanceof SingleFormatControl); 1632 List<String> formats = control.getFormats(baseName); 1633 if (!isKnownControl && !checkList(formats)) { 1634 throw new IllegalArgumentException("Invalid Control: getFormats"); 1635 } 1636 1637 ResourceBundle baseBundle = null; 1638 for (Locale targetLocale = locale; 1639 targetLocale != null; 1640 targetLocale = control.getFallbackLocale(baseName, targetLocale)) { 1641 List<Locale> candidateLocales = control.getCandidateLocales(baseName, targetLocale); 1642 if (!isKnownControl && !checkList(candidateLocales)) { 1643 throw new IllegalArgumentException("Invalid Control: getCandidateLocales"); 1644 } 1645 1646 bundle = findBundle(callerModule, module, cacheKey, 1647 candidateLocales, formats, 0, control, baseBundle); 1648 1649 // If the loaded bundle is the base bundle and exactly for the 1650 // requested locale or the only candidate locale, then take the 1651 // bundle as the resulting one. If the loaded bundle is the base 1652 // bundle, it's put on hold until we finish processing all 1653 // fallback locales. 1654 if (isValidBundle(bundle)) { 1655 boolean isBaseBundle = Locale.ROOT.equals(bundle.locale); 1656 if (!isBaseBundle || bundle.locale.equals(locale) 1657 || (candidateLocales.size() == 1 1658 && bundle.locale.equals(candidateLocales.get(0)))) { 1659 break; 1660 } 1661 1662 // If the base bundle has been loaded, keep the reference in 1663 // baseBundle so that we can avoid any redundant loading in case 1664 // the control specify not to cache bundles. 1665 if (isBaseBundle && baseBundle == null) { 1666 baseBundle = bundle; 1667 } 1668 } 1669 } 1670 1671 if (bundle == null) { 1672 if (baseBundle == null) { 1673 throwMissingResourceException(baseName, locale, cacheKey.getCause()); 1674 } 1675 bundle = baseBundle; 1676 } 1677 1678 // keep callerModule and module reachable for as long as we are operating 1679 // with WeakReference(s) to them (in CacheKey)... 1680 Reference.reachabilityFence(callerModule); 1681 Reference.reachabilityFence(module); 1682 1683 return bundle; 1684 } 1685 1686 /** 1687 * Checks if the given <code>List</code> is not null, not empty, 1688 * not having null in its elements. 1689 */ 1690 private static boolean checkList(List<?> a) { 1691 boolean valid = (a != null && !a.isEmpty()); 1692 if (valid) { 1693 int size = a.size(); 1694 for (int i = 0; valid && i < size; i++) { 1695 valid = (a.get(i) != null); 1696 } 1697 } 1698 return valid; 1699 } 1700 1701 private static ResourceBundle findBundle(Module callerModule, 1702 Module module, 1703 CacheKey cacheKey, 1704 List<Locale> candidateLocales, 1705 List<String> formats, 1706 int index, 1707 Control control, 1708 ResourceBundle baseBundle) { 1709 Locale targetLocale = candidateLocales.get(index); 1710 ResourceBundle parent = null; 1711 if (index != candidateLocales.size() - 1) { 1712 parent = findBundle(callerModule, module, cacheKey, 1713 candidateLocales, formats, index + 1, 1714 control, baseBundle); 1715 } else if (baseBundle != null && Locale.ROOT.equals(targetLocale)) { 1716 return baseBundle; 1717 } 1718 1719 // Before we do the real loading work, see whether we need to 1720 // do some housekeeping: If references to modules or 1721 // resource bundles have been nulled out, remove all related 1722 // information from the cache. 1723 Object ref; 1724 while ((ref = referenceQueue.poll()) != null) { 1725 cacheList.remove(((CacheKeyReference)ref).getCacheKey()); 1726 } 1727 1728 // flag indicating the resource bundle has expired in the cache 1729 boolean expiredBundle = false; 1730 1731 // First, look up the cache to see if it's in the cache, without 1732 // attempting to load bundle. 1733 cacheKey.setLocale(targetLocale); 1734 ResourceBundle bundle = findBundleInCache(cacheKey, control); 1735 if (isValidBundle(bundle)) { 1736 expiredBundle = bundle.expired; 1737 if (!expiredBundle) { 1738 // If its parent is the one asked for by the candidate 1739 // locales (the runtime lookup path), we can take the cached 1740 // one. (If it's not identical, then we'd have to check the 1741 // parent's parents to be consistent with what's been 1742 // requested.) 1743 if (bundle.parent == parent) { 1744 return bundle; 1745 } 1746 // Otherwise, remove the cached one since we can't keep 1747 // the same bundles having different parents. 1748 BundleReference bundleRef = cacheList.get(cacheKey); 1749 if (bundleRef != null && bundleRef.get() == bundle) { 1750 cacheList.remove(cacheKey, bundleRef); 1751 } 1752 } 1753 } 1754 1755 if (bundle != NONEXISTENT_BUNDLE) { 1756 trace("findBundle: %d %s %s formats: %s%n", index, candidateLocales, cacheKey, formats); 1757 if (module.isNamed()) { 1758 bundle = loadBundle(cacheKey, formats, control, module, callerModule); 1759 } else { 1760 bundle = loadBundle(cacheKey, formats, control, expiredBundle); 1761 } 1762 if (bundle != null) { 1763 if (bundle.parent == null) { 1764 bundle.setParent(parent); 1765 } 1766 bundle.locale = targetLocale; 1767 bundle = putBundleInCache(cacheKey, bundle, control); 1768 return bundle; 1769 } 1770 1771 // Put NONEXISTENT_BUNDLE in the cache as a mark that there's no bundle 1772 // instance for the locale. 1773 putBundleInCache(cacheKey, NONEXISTENT_BUNDLE, control); 1774 } 1775 return parent; 1776 } 1777 1778 private static final String UNKNOWN_FORMAT = ""; 1779 1780 1781 /* 1782 * Loads a ResourceBundle in named modules 1783 */ 1784 private static ResourceBundle loadBundle(CacheKey cacheKey, 1785 List<String> formats, 1786 Control control, 1787 Module module, 1788 Module callerModule) { 1789 String baseName = cacheKey.getName(); 1790 Locale targetLocale = cacheKey.getLocale(); 1791 1792 ResourceBundle bundle = null; 1793 if (cacheKey.hasProviders()) { 1794 if (callerModule == module) { 1795 bundle = loadBundleFromProviders(baseName, 1796 targetLocale, 1797 cacheKey.getProviders(), 1798 cacheKey); 1799 } else { 1800 // load from provider if the caller module has access to the 1801 // service type and also declares `uses` 1802 ClassLoader loader = getLoader(module); 1803 Class<ResourceBundleProvider> svc = 1804 getResourceBundleProviderType(baseName, loader); 1805 if (svc != null 1806 && Reflection.verifyModuleAccess(callerModule, svc) 1807 && callerModule.canUse(svc)) { 1808 bundle = loadBundleFromProviders(baseName, 1809 targetLocale, 1810 cacheKey.getProviders(), 1811 cacheKey); 1812 } 1813 } 1814 1815 if (bundle != null) { 1816 cacheKey.setFormat(UNKNOWN_FORMAT); 1817 } 1818 } 1819 1820 // If none of providers returned a bundle and the caller has no provider, 1821 // look up module-local bundles or from the class path 1822 if (bundle == null && !cacheKey.callerHasProvider()) { 1823 for (String format : formats) { 1824 try { 1825 switch (format) { 1826 case "java.class": 1827 bundle = ResourceBundleProviderHelper 1828 .loadResourceBundle(callerModule, module, baseName, targetLocale); 1829 1830 break; 1831 case "java.properties": 1832 bundle = ResourceBundleProviderHelper 1833 .loadPropertyResourceBundle(callerModule, module, baseName, targetLocale); 1834 break; 1835 default: 1836 throw new InternalError("unexpected format: " + format); 1837 } 1838 1839 if (bundle != null) { 1840 cacheKey.setFormat(format); 1841 break; 1842 } 1843 } catch (LinkageError|Exception e) { 1844 cacheKey.setCause(e); 1845 } 1846 } 1847 } 1848 return bundle; 1849 } 1850 1851 /** 1852 * Returns a ServiceLoader that will find providers that are bound to 1853 * a given named module. 1854 */ 1855 private static ServiceLoader<ResourceBundleProvider> getServiceLoader(Module module, 1856 String baseName) 1857 { 1858 if (!module.isNamed()) { 1859 return null; 1860 } 1861 1862 ClassLoader loader = getLoader(module); 1863 Class<ResourceBundleProvider> service = 1864 getResourceBundleProviderType(baseName, loader); 1865 if (service != null && Reflection.verifyModuleAccess(module, service)) { 1866 try { 1867 // locate providers that are visible to the class loader 1868 // ServiceConfigurationError will be thrown if the module 1869 // does not declare `uses` the service type 1870 return ServiceLoader.load(service, loader, module); 1871 } catch (ServiceConfigurationError e) { 1872 // "uses" not declared 1873 return null; 1874 } 1875 } 1876 return null; 1877 } 1878 1879 /** 1880 * Returns the service type of the given baseName that is visible 1881 * to the given class loader 1882 */ 1883 private static Class<ResourceBundleProvider> 1884 getResourceBundleProviderType(String baseName, ClassLoader loader) 1885 { 1886 // Look up <baseName> + "Provider" 1887 String providerName = baseName + "Provider"; 1888 // Use the class loader of the getBundle caller so that the caller's 1889 // visibility of the provider type is checked. 1890 return AccessController.doPrivileged( 1891 new PrivilegedAction<>() { 1892 @Override 1893 public Class<ResourceBundleProvider> run() { 1894 try { 1895 Class<?> c = Class.forName(providerName, false, loader); 1896 if (ResourceBundleProvider.class.isAssignableFrom(c)) { 1897 @SuppressWarnings("unchecked") 1898 Class<ResourceBundleProvider> s = (Class<ResourceBundleProvider>) c; 1899 return s; 1900 } 1901 } catch (ClassNotFoundException e) {} 1902 return null; 1903 } 1904 }); 1905 } 1906 1907 /** 1908 * Loads ResourceBundle from service providers. 1909 */ 1910 private static ResourceBundle loadBundleFromProviders(String baseName, 1911 Locale locale, 1912 ServiceLoader<ResourceBundleProvider> providers, 1913 CacheKey cacheKey) 1914 { 1915 if (providers == null) return null; 1916 1917 return AccessController.doPrivileged( 1918 new PrivilegedAction<>() { 1919 public ResourceBundle run() { 1920 for (Iterator<ResourceBundleProvider> itr = providers.iterator(); itr.hasNext(); ) { 1921 try { 1922 ResourceBundleProvider provider = itr.next(); 1923 if (cacheKey != null && cacheKey.callerHasProvider == null 1924 && cacheKey.getModule() == provider.getClass().getModule()) { 1925 cacheKey.callerHasProvider = Boolean.TRUE; 1926 } 1927 ResourceBundle bundle = provider.getBundle(baseName, locale); 1928 trace("provider %s %s locale: %s bundle: %s%n", provider, baseName, locale, bundle); 1929 if (bundle != null) { 1930 return bundle; 1931 } 1932 } catch (ServiceConfigurationError | SecurityException e) { 1933 if (cacheKey != null) { 1934 cacheKey.setCause(e); 1935 } 1936 } 1937 } 1938 if (cacheKey != null && cacheKey.callerHasProvider == null) { 1939 cacheKey.callerHasProvider = Boolean.FALSE; 1940 } 1941 return null; 1942 } 1943 }); 1944 1945 } 1946 1947 /* 1948 * Legacy mechanism to load resource bundles 1949 */ 1950 private static ResourceBundle loadBundle(CacheKey cacheKey, 1951 List<String> formats, 1952 Control control, 1953 boolean reload) { 1954 1955 // Here we actually load the bundle in the order of formats 1956 // specified by the getFormats() value. 1957 Locale targetLocale = cacheKey.getLocale(); 1958 1959 Module module = cacheKey.getModule(); 1960 if (module == null) { 1961 // should not happen 1962 throw new InternalError( 1963 "Module for cache key: " + cacheKey + " has been GCed."); 1964 } 1965 ClassLoader loader = getLoaderForControl(module); 1966 1967 ResourceBundle bundle = null; 1968 for (String format : formats) { 1969 try { 1970 // ResourceBundle.Control.newBundle may be overridden 1971 bundle = control.newBundle(cacheKey.getName(), targetLocale, format, 1972 loader, reload); 1973 } catch (LinkageError | Exception error) { 1974 // We need to handle the LinkageError case due to 1975 // inconsistent case-sensitivity in ClassLoader. 1976 // See 6572242 for details. 1977 cacheKey.setCause(error); 1978 } 1979 if (bundle != null) { 1980 // Set the format in the cache key so that it can be 1981 // used when calling needsReload later. 1982 cacheKey.setFormat(format); 1983 bundle.name = cacheKey.getName(); 1984 bundle.locale = targetLocale; 1985 // Bundle provider might reuse instances. So we should make 1986 // sure to clear the expired flag here. 1987 bundle.expired = false; 1988 break; 1989 } 1990 } 1991 1992 return bundle; 1993 } 1994 1995 private static boolean isValidBundle(ResourceBundle bundle) { 1996 return bundle != null && bundle != NONEXISTENT_BUNDLE; 1997 } 1998 1999 /** 2000 * Determines whether any of resource bundles in the parent chain, 2001 * including the leaf, have expired. 2002 */ 2003 private static boolean hasValidParentChain(ResourceBundle bundle) { 2004 long now = System.currentTimeMillis(); 2005 while (bundle != null) { 2006 if (bundle.expired) { 2007 return false; 2008 } 2009 CacheKey key = bundle.cacheKey; 2010 if (key != null) { 2011 long expirationTime = key.expirationTime; 2012 if (expirationTime >= 0 && expirationTime <= now) { 2013 return false; 2014 } 2015 } 2016 bundle = bundle.parent; 2017 } 2018 return true; 2019 } 2020 2021 /** 2022 * Throw a MissingResourceException with proper message 2023 */ 2024 private static void throwMissingResourceException(String baseName, 2025 Locale locale, 2026 Throwable cause) { 2027 // If the cause is a MissingResourceException, avoid creating 2028 // a long chain. (6355009) 2029 if (cause instanceof MissingResourceException) { 2030 cause = null; 2031 } 2032 throw new MissingResourceException("Can't find bundle for base name " 2033 + baseName + ", locale " + locale, 2034 baseName + "_" + locale, // className 2035 "", // key 2036 cause); 2037 } 2038 2039 /** 2040 * Finds a bundle in the cache. Any expired bundles are marked as 2041 * `expired' and removed from the cache upon return. 2042 * 2043 * @param cacheKey the key to look up the cache 2044 * @param control the Control to be used for the expiration control 2045 * @return the cached bundle, or null if the bundle is not found in the 2046 * cache or its parent has expired. <code>bundle.expire</code> is true 2047 * upon return if the bundle in the cache has expired. 2048 */ 2049 private static ResourceBundle findBundleInCache(CacheKey cacheKey, 2050 Control control) { 2051 BundleReference bundleRef = cacheList.get(cacheKey); 2052 if (bundleRef == null) { 2053 return null; 2054 } 2055 ResourceBundle bundle = bundleRef.get(); 2056 if (bundle == null) { 2057 return null; 2058 } 2059 ResourceBundle p = bundle.parent; 2060 assert p != NONEXISTENT_BUNDLE; 2061 // If the parent has expired, then this one must also expire. We 2062 // check only the immediate parent because the actual loading is 2063 // done from the root (base) to leaf (child) and the purpose of 2064 // checking is to propagate expiration towards the leaf. For 2065 // example, if the requested locale is ja_JP_JP and there are 2066 // bundles for all of the candidates in the cache, we have a list, 2067 // 2068 // base <- ja <- ja_JP <- ja_JP_JP 2069 // 2070 // If ja has expired, then it will reload ja and the list becomes a 2071 // tree. 2072 // 2073 // base <- ja (new) 2074 // " <- ja (expired) <- ja_JP <- ja_JP_JP 2075 // 2076 // When looking up ja_JP in the cache, it finds ja_JP in the cache 2077 // which references to the expired ja. Then, ja_JP is marked as 2078 // expired and removed from the cache. This will be propagated to 2079 // ja_JP_JP. 2080 // 2081 // Now, it's possible, for example, that while loading new ja_JP, 2082 // someone else has started loading the same bundle and finds the 2083 // base bundle has expired. Then, what we get from the first 2084 // getBundle call includes the expired base bundle. However, if 2085 // someone else didn't start its loading, we wouldn't know if the 2086 // base bundle has expired at the end of the loading process. The 2087 // expiration control doesn't guarantee that the returned bundle and 2088 // its parents haven't expired. 2089 // 2090 // We could check the entire parent chain to see if there's any in 2091 // the chain that has expired. But this process may never end. An 2092 // extreme case would be that getTimeToLive returns 0 and 2093 // needsReload always returns true. 2094 if (p != null && p.expired) { 2095 assert bundle != NONEXISTENT_BUNDLE; 2096 bundle.expired = true; 2097 bundle.cacheKey = null; 2098 cacheList.remove(cacheKey, bundleRef); 2099 bundle = null; 2100 } else { 2101 CacheKey key = bundleRef.getCacheKey(); 2102 long expirationTime = key.expirationTime; 2103 if (!bundle.expired && expirationTime >= 0 && 2104 expirationTime <= System.currentTimeMillis()) { 2105 // its TTL period has expired. 2106 if (bundle != NONEXISTENT_BUNDLE) { 2107 // Synchronize here to call needsReload to avoid 2108 // redundant concurrent calls for the same bundle. 2109 synchronized (bundle) { 2110 expirationTime = key.expirationTime; 2111 if (!bundle.expired && expirationTime >= 0 && 2112 expirationTime <= System.currentTimeMillis()) { 2113 try { 2114 Module module = cacheKey.getModule(); 2115 bundle.expired = 2116 module == null || // already GCed 2117 control.needsReload(key.getName(), 2118 key.getLocale(), 2119 key.getFormat(), 2120 getLoaderForControl(module), 2121 bundle, 2122 key.loadTime); 2123 } catch (Exception e) { 2124 cacheKey.setCause(e); 2125 } 2126 if (bundle.expired) { 2127 // If the bundle needs to be reloaded, then 2128 // remove the bundle from the cache, but 2129 // return the bundle with the expired flag 2130 // on. 2131 bundle.cacheKey = null; 2132 cacheList.remove(cacheKey, bundleRef); 2133 } else { 2134 // Update the expiration control info. and reuse 2135 // the same bundle instance 2136 setExpirationTime(key, control); 2137 } 2138 } 2139 } 2140 } else { 2141 // We just remove NONEXISTENT_BUNDLE from the cache. 2142 cacheList.remove(cacheKey, bundleRef); 2143 bundle = null; 2144 } 2145 } 2146 } 2147 return bundle; 2148 } 2149 2150 /** 2151 * Put a new bundle in the cache. 2152 * 2153 * @param cacheKey the key for the resource bundle 2154 * @param bundle the resource bundle to be put in the cache 2155 * @return the ResourceBundle for the cacheKey; if someone has put 2156 * the bundle before this call, the one found in the cache is 2157 * returned. 2158 */ 2159 private static ResourceBundle putBundleInCache(CacheKey cacheKey, 2160 ResourceBundle bundle, 2161 Control control) { 2162 setExpirationTime(cacheKey, control); 2163 if (cacheKey.expirationTime != Control.TTL_DONT_CACHE) { 2164 CacheKey key = new CacheKey(cacheKey); 2165 BundleReference bundleRef = new BundleReference(bundle, referenceQueue, key); 2166 bundle.cacheKey = key; 2167 2168 // Put the bundle in the cache if it's not been in the cache. 2169 BundleReference result = cacheList.putIfAbsent(key, bundleRef); 2170 2171 // If someone else has put the same bundle in the cache before 2172 // us and it has not expired, we should use the one in the cache. 2173 if (result != null) { 2174 ResourceBundle rb = result.get(); 2175 if (rb != null && !rb.expired) { 2176 // Clear the back link to the cache key 2177 bundle.cacheKey = null; 2178 bundle = rb; 2179 // Clear the reference in the BundleReference so that 2180 // it won't be enqueued. 2181 bundleRef.clear(); 2182 } else { 2183 // Replace the invalid (garbage collected or expired) 2184 // instance with the valid one. 2185 cacheList.put(key, bundleRef); 2186 } 2187 } 2188 } 2189 return bundle; 2190 } 2191 2192 private static void setExpirationTime(CacheKey cacheKey, Control control) { 2193 long ttl = control.getTimeToLive(cacheKey.getName(), 2194 cacheKey.getLocale()); 2195 if (ttl >= 0) { 2196 // If any expiration time is specified, set the time to be 2197 // expired in the cache. 2198 long now = System.currentTimeMillis(); 2199 cacheKey.loadTime = now; 2200 cacheKey.expirationTime = now + ttl; 2201 } else if (ttl >= Control.TTL_NO_EXPIRATION_CONTROL) { 2202 cacheKey.expirationTime = ttl; 2203 } else { 2204 throw new IllegalArgumentException("Invalid Control: TTL=" + ttl); 2205 } 2206 } 2207 2208 /** 2209 * Removes all resource bundles from the cache that have been loaded 2210 * by the caller's module. 2211 * 2212 * @since 1.6 2213 * @revised 9 2214 * @spec JPMS 2215 * @see ResourceBundle.Control#getTimeToLive(String,Locale) 2216 */ 2217 @CallerSensitive 2218 public static final void clearCache() { 2219 Class<?> caller = Reflection.getCallerClass(); 2220 cacheList.keySet().removeIf( 2221 key -> key.getCallerModule() == caller.getModule() 2222 ); 2223 } 2224 2225 /** 2226 * Removes all resource bundles from the cache that have been loaded 2227 * by the given class loader. 2228 * 2229 * @param loader the class loader 2230 * @exception NullPointerException if <code>loader</code> is null 2231 * @since 1.6 2232 * @see ResourceBundle.Control#getTimeToLive(String,Locale) 2233 */ 2234 public static final void clearCache(ClassLoader loader) { 2235 Objects.requireNonNull(loader); 2236 cacheList.keySet().removeIf( 2237 key -> { 2238 Module m; 2239 return (m = key.getModule()) != null && 2240 getLoader(m) == loader; 2241 } 2242 ); 2243 } 2244 2245 /** 2246 * Gets an object for the given key from this resource bundle. 2247 * Returns null if this resource bundle does not contain an 2248 * object for the given key. 2249 * 2250 * @param key the key for the desired object 2251 * @exception NullPointerException if <code>key</code> is <code>null</code> 2252 * @return the object for the given key, or null 2253 */ 2254 protected abstract Object handleGetObject(String key); 2255 2256 /** 2257 * Returns an enumeration of the keys. 2258 * 2259 * @return an <code>Enumeration</code> of the keys contained in 2260 * this <code>ResourceBundle</code> and its parent bundles. 2261 */ 2262 public abstract Enumeration<String> getKeys(); 2263 2264 /** 2265 * Determines whether the given <code>key</code> is contained in 2266 * this <code>ResourceBundle</code> or its parent bundles. 2267 * 2268 * @param key 2269 * the resource <code>key</code> 2270 * @return <code>true</code> if the given <code>key</code> is 2271 * contained in this <code>ResourceBundle</code> or its 2272 * parent bundles; <code>false</code> otherwise. 2273 * @exception NullPointerException 2274 * if <code>key</code> is <code>null</code> 2275 * @since 1.6 2276 */ 2277 public boolean containsKey(String key) { 2278 if (key == null) { 2279 throw new NullPointerException(); 2280 } 2281 for (ResourceBundle rb = this; rb != null; rb = rb.parent) { 2282 if (rb.handleKeySet().contains(key)) { 2283 return true; 2284 } 2285 } 2286 return false; 2287 } 2288 2289 /** 2290 * Returns a <code>Set</code> of all keys contained in this 2291 * <code>ResourceBundle</code> and its parent bundles. 2292 * 2293 * @return a <code>Set</code> of all keys contained in this 2294 * <code>ResourceBundle</code> and its parent bundles. 2295 * @since 1.6 2296 */ 2297 public Set<String> keySet() { 2298 Set<String> keys = new HashSet<>(); 2299 for (ResourceBundle rb = this; rb != null; rb = rb.parent) { 2300 keys.addAll(rb.handleKeySet()); 2301 } 2302 return keys; 2303 } 2304 2305 /** 2306 * Returns a <code>Set</code> of the keys contained <em>only</em> 2307 * in this <code>ResourceBundle</code>. 2308 * 2309 * <p>The default implementation returns a <code>Set</code> of the 2310 * keys returned by the {@link #getKeys() getKeys} method except 2311 * for the ones for which the {@link #handleGetObject(String) 2312 * handleGetObject} method returns <code>null</code>. Once the 2313 * <code>Set</code> has been created, the value is kept in this 2314 * <code>ResourceBundle</code> in order to avoid producing the 2315 * same <code>Set</code> in subsequent calls. Subclasses can 2316 * override this method for faster handling. 2317 * 2318 * @return a <code>Set</code> of the keys contained only in this 2319 * <code>ResourceBundle</code> 2320 * @since 1.6 2321 */ 2322 protected Set<String> handleKeySet() { 2323 if (keySet == null) { 2324 synchronized (this) { 2325 if (keySet == null) { 2326 Set<String> keys = new HashSet<>(); 2327 Enumeration<String> enumKeys = getKeys(); 2328 while (enumKeys.hasMoreElements()) { 2329 String key = enumKeys.nextElement(); 2330 if (handleGetObject(key) != null) { 2331 keys.add(key); 2332 } 2333 } 2334 keySet = keys; 2335 } 2336 } 2337 } 2338 return keySet; 2339 } 2340 2341 2342 2343 /** 2344 * <code>ResourceBundle.Control</code> defines a set of callback methods 2345 * that are invoked by the {@link ResourceBundle#getBundle(String, 2346 * Locale, ClassLoader, Control) ResourceBundle.getBundle} factory 2347 * methods during the bundle loading process. In other words, a 2348 * <code>ResourceBundle.Control</code> collaborates with the factory 2349 * methods for loading resource bundles. The default implementation of 2350 * the callback methods provides the information necessary for the 2351 * factory methods to perform the <a 2352 * href="./ResourceBundle.html#default_behavior">default behavior</a>. 2353 * <a href="#note">Note that this class is not supported in named modules.</a> 2354 * 2355 * <p>In addition to the callback methods, the {@link 2356 * #toBundleName(String, Locale) toBundleName} and {@link 2357 * #toResourceName(String, String) toResourceName} methods are defined 2358 * primarily for convenience in implementing the callback 2359 * methods. However, the <code>toBundleName</code> method could be 2360 * overridden to provide different conventions in the organization and 2361 * packaging of localized resources. The <code>toResourceName</code> 2362 * method is <code>final</code> to avoid use of wrong resource and class 2363 * name separators. 2364 * 2365 * <p>Two factory methods, {@link #getControl(List)} and {@link 2366 * #getNoFallbackControl(List)}, provide 2367 * <code>ResourceBundle.Control</code> instances that implement common 2368 * variations of the default bundle loading process. 2369 * 2370 * <p>The formats returned by the {@link Control#getFormats(String) 2371 * getFormats} method and candidate locales returned by the {@link 2372 * ResourceBundle.Control#getCandidateLocales(String, Locale) 2373 * getCandidateLocales} method must be consistent in all 2374 * <code>ResourceBundle.getBundle</code> invocations for the same base 2375 * bundle. Otherwise, the <code>ResourceBundle.getBundle</code> methods 2376 * may return unintended bundles. For example, if only 2377 * <code>"java.class"</code> is returned by the <code>getFormats</code> 2378 * method for the first call to <code>ResourceBundle.getBundle</code> 2379 * and only <code>"java.properties"</code> for the second call, then the 2380 * second call will return the class-based one that has been cached 2381 * during the first call. 2382 * 2383 * <p>A <code>ResourceBundle.Control</code> instance must be thread-safe 2384 * if it's simultaneously used by multiple threads. 2385 * <code>ResourceBundle.getBundle</code> does not synchronize to call 2386 * the <code>ResourceBundle.Control</code> methods. The default 2387 * implementations of the methods are thread-safe. 2388 * 2389 * <p>Applications can specify <code>ResourceBundle.Control</code> 2390 * instances returned by the <code>getControl</code> factory methods or 2391 * created from a subclass of <code>ResourceBundle.Control</code> to 2392 * customize the bundle loading process. The following are examples of 2393 * changing the default bundle loading process. 2394 * 2395 * <p><b>Example 1</b> 2396 * 2397 * <p>The following code lets <code>ResourceBundle.getBundle</code> look 2398 * up only properties-based resources. 2399 * 2400 * <pre> 2401 * import java.util.*; 2402 * import static java.util.ResourceBundle.Control.*; 2403 * ... 2404 * ResourceBundle bundle = 2405 * ResourceBundle.getBundle("MyResources", new Locale("fr", "CH"), 2406 * ResourceBundle.Control.getControl(FORMAT_PROPERTIES)); 2407 * </pre> 2408 * 2409 * Given the resource bundles in the <a 2410 * href="./ResourceBundle.html#default_behavior_example">example</a> in 2411 * the <code>ResourceBundle.getBundle</code> description, this 2412 * <code>ResourceBundle.getBundle</code> call loads 2413 * <code>MyResources_fr_CH.properties</code> whose parent is 2414 * <code>MyResources_fr.properties</code> whose parent is 2415 * <code>MyResources.properties</code>. (<code>MyResources_fr_CH.properties</code> 2416 * is not hidden, but <code>MyResources_fr_CH.class</code> is.) 2417 * 2418 * <p><b>Example 2</b> 2419 * 2420 * <p>The following is an example of loading XML-based bundles 2421 * using {@link Properties#loadFromXML(java.io.InputStream) 2422 * Properties.loadFromXML}. 2423 * 2424 * <pre> 2425 * ResourceBundle rb = ResourceBundle.getBundle("Messages", 2426 * new ResourceBundle.Control() { 2427 * public List<String> getFormats(String baseName) { 2428 * if (baseName == null) 2429 * throw new NullPointerException(); 2430 * return Arrays.asList("xml"); 2431 * } 2432 * public ResourceBundle newBundle(String baseName, 2433 * Locale locale, 2434 * String format, 2435 * ClassLoader loader, 2436 * boolean reload) 2437 * throws IllegalAccessException, 2438 * InstantiationException, 2439 * IOException { 2440 * if (baseName == null || locale == null 2441 * || format == null || loader == null) 2442 * throw new NullPointerException(); 2443 * ResourceBundle bundle = null; 2444 * if (format.equals("xml")) { 2445 * String bundleName = toBundleName(baseName, locale); 2446 * String resourceName = toResourceName(bundleName, format); 2447 * InputStream stream = null; 2448 * if (reload) { 2449 * URL url = loader.getResource(resourceName); 2450 * if (url != null) { 2451 * URLConnection connection = url.openConnection(); 2452 * if (connection != null) { 2453 * // Disable caches to get fresh data for 2454 * // reloading. 2455 * connection.setUseCaches(false); 2456 * stream = connection.getInputStream(); 2457 * } 2458 * } 2459 * } else { 2460 * stream = loader.getResourceAsStream(resourceName); 2461 * } 2462 * if (stream != null) { 2463 * BufferedInputStream bis = new BufferedInputStream(stream); 2464 * bundle = new XMLResourceBundle(bis); 2465 * bis.close(); 2466 * } 2467 * } 2468 * return bundle; 2469 * } 2470 * }); 2471 * 2472 * ... 2473 * 2474 * private static class XMLResourceBundle extends ResourceBundle { 2475 * private Properties props; 2476 * XMLResourceBundle(InputStream stream) throws IOException { 2477 * props = new Properties(); 2478 * props.loadFromXML(stream); 2479 * } 2480 * protected Object handleGetObject(String key) { 2481 * return props.getProperty(key); 2482 * } 2483 * public Enumeration<String> getKeys() { 2484 * ... 2485 * } 2486 * } 2487 * </pre> 2488 * 2489 * @apiNote <a id="note">{@code ResourceBundle.Control} is not supported 2490 * in named modules.</a> If the {@code ResourceBundle.getBundle} method with 2491 * a {@code ResourceBundle.Control} is called in a named module, the method 2492 * will throw an {@link UnsupportedOperationException}. Any service providers 2493 * of {@link ResourceBundleControlProvider} are ignored in named modules. 2494 * 2495 * @since 1.6 2496 * @revised 9 2497 * @spec JPMS 2498 * @see java.util.spi.ResourceBundleProvider 2499 */ 2500 public static class Control { 2501 /** 2502 * The default format <code>List</code>, which contains the strings 2503 * <code>"java.class"</code> and <code>"java.properties"</code>, in 2504 * this order. This <code>List</code> is unmodifiable. 2505 * 2506 * @see #getFormats(String) 2507 */ 2508 public static final List<String> FORMAT_DEFAULT 2509 = List.of("java.class", "java.properties"); 2510 2511 /** 2512 * The class-only format <code>List</code> containing 2513 * <code>"java.class"</code>. This <code>List</code> is unmodifiable. 2514 * 2515 * @see #getFormats(String) 2516 */ 2517 public static final List<String> FORMAT_CLASS = List.of("java.class"); 2518 2519 /** 2520 * The properties-only format <code>List</code> containing 2521 * <code>"java.properties"</code>. This <code>List</code> is unmodifiable. 2522 * 2523 * @see #getFormats(String) 2524 */ 2525 public static final List<String> FORMAT_PROPERTIES 2526 = List.of("java.properties"); 2527 2528 /** 2529 * The time-to-live constant for not caching loaded resource bundle 2530 * instances. 2531 * 2532 * @see #getTimeToLive(String, Locale) 2533 */ 2534 public static final long TTL_DONT_CACHE = -1; 2535 2536 /** 2537 * The time-to-live constant for disabling the expiration control 2538 * for loaded resource bundle instances in the cache. 2539 * 2540 * @see #getTimeToLive(String, Locale) 2541 */ 2542 public static final long TTL_NO_EXPIRATION_CONTROL = -2; 2543 2544 private static final Control INSTANCE = new Control(); 2545 2546 /** 2547 * Sole constructor. (For invocation by subclass constructors, 2548 * typically implicit.) 2549 */ 2550 protected Control() { 2551 } 2552 2553 /** 2554 * Returns a <code>ResourceBundle.Control</code> in which the {@link 2555 * #getFormats(String) getFormats} method returns the specified 2556 * <code>formats</code>. The <code>formats</code> must be equal to 2557 * one of {@link Control#FORMAT_PROPERTIES}, {@link 2558 * Control#FORMAT_CLASS} or {@link 2559 * Control#FORMAT_DEFAULT}. <code>ResourceBundle.Control</code> 2560 * instances returned by this method are singletons and thread-safe. 2561 * 2562 * <p>Specifying {@link Control#FORMAT_DEFAULT} is equivalent to 2563 * instantiating the <code>ResourceBundle.Control</code> class, 2564 * except that this method returns a singleton. 2565 * 2566 * @param formats 2567 * the formats to be returned by the 2568 * <code>ResourceBundle.Control.getFormats</code> method 2569 * @return a <code>ResourceBundle.Control</code> supporting the 2570 * specified <code>formats</code> 2571 * @exception NullPointerException 2572 * if <code>formats</code> is <code>null</code> 2573 * @exception IllegalArgumentException 2574 * if <code>formats</code> is unknown 2575 */ 2576 public static final Control getControl(List<String> formats) { 2577 if (formats.equals(Control.FORMAT_PROPERTIES)) { 2578 return SingleFormatControl.PROPERTIES_ONLY; 2579 } 2580 if (formats.equals(Control.FORMAT_CLASS)) { 2581 return SingleFormatControl.CLASS_ONLY; 2582 } 2583 if (formats.equals(Control.FORMAT_DEFAULT)) { 2584 return Control.INSTANCE; 2585 } 2586 throw new IllegalArgumentException(); 2587 } 2588 2589 /** 2590 * Returns a <code>ResourceBundle.Control</code> in which the {@link 2591 * #getFormats(String) getFormats} method returns the specified 2592 * <code>formats</code> and the {@link 2593 * Control#getFallbackLocale(String, Locale) getFallbackLocale} 2594 * method returns <code>null</code>. The <code>formats</code> must 2595 * be equal to one of {@link Control#FORMAT_PROPERTIES}, {@link 2596 * Control#FORMAT_CLASS} or {@link Control#FORMAT_DEFAULT}. 2597 * <code>ResourceBundle.Control</code> instances returned by this 2598 * method are singletons and thread-safe. 2599 * 2600 * @param formats 2601 * the formats to be returned by the 2602 * <code>ResourceBundle.Control.getFormats</code> method 2603 * @return a <code>ResourceBundle.Control</code> supporting the 2604 * specified <code>formats</code> with no fallback 2605 * <code>Locale</code> support 2606 * @exception NullPointerException 2607 * if <code>formats</code> is <code>null</code> 2608 * @exception IllegalArgumentException 2609 * if <code>formats</code> is unknown 2610 */ 2611 public static final Control getNoFallbackControl(List<String> formats) { 2612 if (formats.equals(Control.FORMAT_DEFAULT)) { 2613 return NoFallbackControl.NO_FALLBACK; 2614 } 2615 if (formats.equals(Control.FORMAT_PROPERTIES)) { 2616 return NoFallbackControl.PROPERTIES_ONLY_NO_FALLBACK; 2617 } 2618 if (formats.equals(Control.FORMAT_CLASS)) { 2619 return NoFallbackControl.CLASS_ONLY_NO_FALLBACK; 2620 } 2621 throw new IllegalArgumentException(); 2622 } 2623 2624 /** 2625 * Returns a <code>List</code> of <code>String</code>s containing 2626 * formats to be used to load resource bundles for the given 2627 * <code>baseName</code>. The <code>ResourceBundle.getBundle</code> 2628 * factory method tries to load resource bundles with formats in the 2629 * order specified by the list. The list returned by this method 2630 * must have at least one <code>String</code>. The predefined 2631 * formats are <code>"java.class"</code> for class-based resource 2632 * bundles and <code>"java.properties"</code> for {@linkplain 2633 * PropertyResourceBundle properties-based} ones. Strings starting 2634 * with <code>"java."</code> are reserved for future extensions and 2635 * must not be used by application-defined formats. 2636 * 2637 * <p>It is not a requirement to return an immutable (unmodifiable) 2638 * <code>List</code>. However, the returned <code>List</code> must 2639 * not be mutated after it has been returned by 2640 * <code>getFormats</code>. 2641 * 2642 * <p>The default implementation returns {@link #FORMAT_DEFAULT} so 2643 * that the <code>ResourceBundle.getBundle</code> factory method 2644 * looks up first class-based resource bundles, then 2645 * properties-based ones. 2646 * 2647 * @param baseName 2648 * the base name of the resource bundle, a fully qualified class 2649 * name 2650 * @return a <code>List</code> of <code>String</code>s containing 2651 * formats for loading resource bundles. 2652 * @exception NullPointerException 2653 * if <code>baseName</code> is null 2654 * @see #FORMAT_DEFAULT 2655 * @see #FORMAT_CLASS 2656 * @see #FORMAT_PROPERTIES 2657 */ 2658 public List<String> getFormats(String baseName) { 2659 if (baseName == null) { 2660 throw new NullPointerException(); 2661 } 2662 return FORMAT_DEFAULT; 2663 } 2664 2665 /** 2666 * Returns a <code>List</code> of <code>Locale</code>s as candidate 2667 * locales for <code>baseName</code> and <code>locale</code>. This 2668 * method is called by the <code>ResourceBundle.getBundle</code> 2669 * factory method each time the factory method tries finding a 2670 * resource bundle for a target <code>Locale</code>. 2671 * 2672 * <p>The sequence of the candidate locales also corresponds to the 2673 * runtime resource lookup path (also known as the <I>parent 2674 * chain</I>), if the corresponding resource bundles for the 2675 * candidate locales exist and their parents are not defined by 2676 * loaded resource bundles themselves. The last element of the list 2677 * must be a {@linkplain Locale#ROOT root locale} if it is desired to 2678 * have the base bundle as the terminal of the parent chain. 2679 * 2680 * <p>If the given locale is equal to <code>Locale.ROOT</code> (the 2681 * root locale), a <code>List</code> containing only the root 2682 * <code>Locale</code> must be returned. In this case, the 2683 * <code>ResourceBundle.getBundle</code> factory method loads only 2684 * the base bundle as the resulting resource bundle. 2685 * 2686 * <p>It is not a requirement to return an immutable (unmodifiable) 2687 * <code>List</code>. However, the returned <code>List</code> must not 2688 * be mutated after it has been returned by 2689 * <code>getCandidateLocales</code>. 2690 * 2691 * <p>The default implementation returns a <code>List</code> containing 2692 * <code>Locale</code>s using the rules described below. In the 2693 * description below, <em>L</em>, <em>S</em>, <em>C</em> and <em>V</em> 2694 * respectively represent non-empty language, script, country, and 2695 * variant. For example, [<em>L</em>, <em>C</em>] represents a 2696 * <code>Locale</code> that has non-empty values only for language and 2697 * country. The form <em>L</em>("xx") represents the (non-empty) 2698 * language value is "xx". For all cases, <code>Locale</code>s whose 2699 * final component values are empty strings are omitted. 2700 * 2701 * <ol><li>For an input <code>Locale</code> with an empty script value, 2702 * append candidate <code>Locale</code>s by omitting the final component 2703 * one by one as below: 2704 * 2705 * <ul> 2706 * <li> [<em>L</em>, <em>C</em>, <em>V</em>] </li> 2707 * <li> [<em>L</em>, <em>C</em>] </li> 2708 * <li> [<em>L</em>] </li> 2709 * <li> <code>Locale.ROOT</code> </li> 2710 * </ul></li> 2711 * 2712 * <li>For an input <code>Locale</code> with a non-empty script value, 2713 * append candidate <code>Locale</code>s by omitting the final component 2714 * up to language, then append candidates generated from the 2715 * <code>Locale</code> with country and variant restored: 2716 * 2717 * <ul> 2718 * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V</em>]</li> 2719 * <li> [<em>L</em>, <em>S</em>, <em>C</em>]</li> 2720 * <li> [<em>L</em>, <em>S</em>]</li> 2721 * <li> [<em>L</em>, <em>C</em>, <em>V</em>]</li> 2722 * <li> [<em>L</em>, <em>C</em>]</li> 2723 * <li> [<em>L</em>]</li> 2724 * <li> <code>Locale.ROOT</code></li> 2725 * </ul></li> 2726 * 2727 * <li>For an input <code>Locale</code> with a variant value consisting 2728 * of multiple subtags separated by underscore, generate candidate 2729 * <code>Locale</code>s by omitting the variant subtags one by one, then 2730 * insert them after every occurrence of <code> Locale</code>s with the 2731 * full variant value in the original list. For example, if the 2732 * the variant consists of two subtags <em>V1</em> and <em>V2</em>: 2733 * 2734 * <ul> 2735 * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]</li> 2736 * <li> [<em>L</em>, <em>S</em>, <em>C</em>, <em>V1</em>]</li> 2737 * <li> [<em>L</em>, <em>S</em>, <em>C</em>]</li> 2738 * <li> [<em>L</em>, <em>S</em>]</li> 2739 * <li> [<em>L</em>, <em>C</em>, <em>V1</em>, <em>V2</em>]</li> 2740 * <li> [<em>L</em>, <em>C</em>, <em>V1</em>]</li> 2741 * <li> [<em>L</em>, <em>C</em>]</li> 2742 * <li> [<em>L</em>]</li> 2743 * <li> <code>Locale.ROOT</code></li> 2744 * </ul></li> 2745 * 2746 * <li>Special cases for Chinese. When an input <code>Locale</code> has the 2747 * language "zh" (Chinese) and an empty script value, either "Hans" (Simplified) or 2748 * "Hant" (Traditional) might be supplied, depending on the country. 2749 * When the country is "CN" (China) or "SG" (Singapore), "Hans" is supplied. 2750 * When the country is "HK" (Hong Kong SAR China), "MO" (Macau SAR China), 2751 * or "TW" (Taiwan), "Hant" is supplied. For all other countries or when the country 2752 * is empty, no script is supplied. For example, for <code>Locale("zh", "CN") 2753 * </code>, the candidate list will be: 2754 * <ul> 2755 * <li> [<em>L</em>("zh"), <em>S</em>("Hans"), <em>C</em>("CN")]</li> 2756 * <li> [<em>L</em>("zh"), <em>S</em>("Hans")]</li> 2757 * <li> [<em>L</em>("zh"), <em>C</em>("CN")]</li> 2758 * <li> [<em>L</em>("zh")]</li> 2759 * <li> <code>Locale.ROOT</code></li> 2760 * </ul> 2761 * 2762 * For <code>Locale("zh", "TW")</code>, the candidate list will be: 2763 * <ul> 2764 * <li> [<em>L</em>("zh"), <em>S</em>("Hant"), <em>C</em>("TW")]</li> 2765 * <li> [<em>L</em>("zh"), <em>S</em>("Hant")]</li> 2766 * <li> [<em>L</em>("zh"), <em>C</em>("TW")]</li> 2767 * <li> [<em>L</em>("zh")]</li> 2768 * <li> <code>Locale.ROOT</code></li> 2769 * </ul></li> 2770 * 2771 * <li>Special cases for Norwegian. Both <code>Locale("no", "NO", 2772 * "NY")</code> and <code>Locale("nn", "NO")</code> represent Norwegian 2773 * Nynorsk. When a locale's language is "nn", the standard candidate 2774 * list is generated up to [<em>L</em>("nn")], and then the following 2775 * candidates are added: 2776 * 2777 * <ul><li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("NY")]</li> 2778 * <li> [<em>L</em>("no"), <em>C</em>("NO")]</li> 2779 * <li> [<em>L</em>("no")]</li> 2780 * <li> <code>Locale.ROOT</code></li> 2781 * </ul> 2782 * 2783 * If the locale is exactly <code>Locale("no", "NO", "NY")</code>, it is first 2784 * converted to <code>Locale("nn", "NO")</code> and then the above procedure is 2785 * followed. 2786 * 2787 * <p>Also, Java treats the language "no" as a synonym of Norwegian 2788 * Bokmål "nb". Except for the single case <code>Locale("no", 2789 * "NO", "NY")</code> (handled above), when an input <code>Locale</code> 2790 * has language "no" or "nb", candidate <code>Locale</code>s with 2791 * language code "no" and "nb" are interleaved, first using the 2792 * requested language, then using its synonym. For example, 2793 * <code>Locale("nb", "NO", "POSIX")</code> generates the following 2794 * candidate list: 2795 * 2796 * <ul> 2797 * <li> [<em>L</em>("nb"), <em>C</em>("NO"), <em>V</em>("POSIX")]</li> 2798 * <li> [<em>L</em>("no"), <em>C</em>("NO"), <em>V</em>("POSIX")]</li> 2799 * <li> [<em>L</em>("nb"), <em>C</em>("NO")]</li> 2800 * <li> [<em>L</em>("no"), <em>C</em>("NO")]</li> 2801 * <li> [<em>L</em>("nb")]</li> 2802 * <li> [<em>L</em>("no")]</li> 2803 * <li> <code>Locale.ROOT</code></li> 2804 * </ul> 2805 * 2806 * <code>Locale("no", "NO", "POSIX")</code> would generate the same list 2807 * except that locales with "no" would appear before the corresponding 2808 * locales with "nb".</li> 2809 * </ol> 2810 * 2811 * <p>The default implementation uses an {@link ArrayList} that 2812 * overriding implementations may modify before returning it to the 2813 * caller. However, a subclass must not modify it after it has 2814 * been returned by <code>getCandidateLocales</code>. 2815 * 2816 * <p>For example, if the given <code>baseName</code> is "Messages" 2817 * and the given <code>locale</code> is 2818 * <code>Locale("ja", "", "XX")</code>, then a 2819 * <code>List</code> of <code>Locale</code>s: 2820 * <pre> 2821 * Locale("ja", "", "XX") 2822 * Locale("ja") 2823 * Locale.ROOT 2824 * </pre> 2825 * is returned. And if the resource bundles for the "ja" and 2826 * "" <code>Locale</code>s are found, then the runtime resource 2827 * lookup path (parent chain) is: 2828 * <pre>{@code 2829 * Messages_ja -> Messages 2830 * }</pre> 2831 * 2832 * @param baseName 2833 * the base name of the resource bundle, a fully 2834 * qualified class name 2835 * @param locale 2836 * the locale for which a resource bundle is desired 2837 * @return a <code>List</code> of candidate 2838 * <code>Locale</code>s for the given <code>locale</code> 2839 * @exception NullPointerException 2840 * if <code>baseName</code> or <code>locale</code> is 2841 * <code>null</code> 2842 */ 2843 public List<Locale> getCandidateLocales(String baseName, Locale locale) { 2844 if (baseName == null) { 2845 throw new NullPointerException(); 2846 } 2847 return new ArrayList<>(CANDIDATES_CACHE.get(locale.getBaseLocale())); 2848 } 2849 2850 private static final CandidateListCache CANDIDATES_CACHE = new CandidateListCache(); 2851 2852 private static class CandidateListCache extends LocaleObjectCache<BaseLocale, List<Locale>> { 2853 protected List<Locale> createObject(BaseLocale base) { 2854 String language = base.getLanguage(); 2855 String script = base.getScript(); 2856 String region = base.getRegion(); 2857 String variant = base.getVariant(); 2858 2859 // Special handling for Norwegian 2860 boolean isNorwegianBokmal = false; 2861 boolean isNorwegianNynorsk = false; 2862 if (language.equals("no")) { 2863 if (region.equals("NO") && variant.equals("NY")) { 2864 variant = ""; 2865 isNorwegianNynorsk = true; 2866 } else { 2867 isNorwegianBokmal = true; 2868 } 2869 } 2870 if (language.equals("nb") || isNorwegianBokmal) { 2871 List<Locale> tmpList = getDefaultList("nb", script, region, variant); 2872 // Insert a locale replacing "nb" with "no" for every list entry 2873 List<Locale> bokmalList = new LinkedList<>(); 2874 for (Locale l : tmpList) { 2875 bokmalList.add(l); 2876 if (l.getLanguage().length() == 0) { 2877 break; 2878 } 2879 bokmalList.add(Locale.getInstance("no", l.getScript(), l.getCountry(), 2880 l.getVariant(), null)); 2881 } 2882 return bokmalList; 2883 } else if (language.equals("nn") || isNorwegianNynorsk) { 2884 // Insert no_NO_NY, no_NO, no after nn 2885 List<Locale> nynorskList = getDefaultList("nn", script, region, variant); 2886 int idx = nynorskList.size() - 1; 2887 nynorskList.add(idx++, Locale.getInstance("no", "NO", "NY")); 2888 nynorskList.add(idx++, Locale.getInstance("no", "NO", "")); 2889 nynorskList.add(idx++, Locale.getInstance("no", "", "")); 2890 return nynorskList; 2891 } 2892 // Special handling for Chinese 2893 else if (language.equals("zh")) { 2894 if (script.length() == 0 && region.length() > 0) { 2895 // Supply script for users who want to use zh_Hans/zh_Hant 2896 // as bundle names (recommended for Java7+) 2897 switch (region) { 2898 case "TW": 2899 case "HK": 2900 case "MO": 2901 script = "Hant"; 2902 break; 2903 case "CN": 2904 case "SG": 2905 script = "Hans"; 2906 break; 2907 } 2908 } 2909 } 2910 2911 return getDefaultList(language, script, region, variant); 2912 } 2913 2914 private static List<Locale> getDefaultList(String language, String script, String region, String variant) { 2915 List<String> variants = null; 2916 2917 if (variant.length() > 0) { 2918 variants = new LinkedList<>(); 2919 int idx = variant.length(); 2920 while (idx != -1) { 2921 variants.add(variant.substring(0, idx)); 2922 idx = variant.lastIndexOf('_', --idx); 2923 } 2924 } 2925 2926 List<Locale> list = new LinkedList<>(); 2927 2928 if (variants != null) { 2929 for (String v : variants) { 2930 list.add(Locale.getInstance(language, script, region, v, null)); 2931 } 2932 } 2933 if (region.length() > 0) { 2934 list.add(Locale.getInstance(language, script, region, "", null)); 2935 } 2936 if (script.length() > 0) { 2937 list.add(Locale.getInstance(language, script, "", "", null)); 2938 // Special handling for Chinese 2939 if (language.equals("zh")) { 2940 if (region.length() == 0) { 2941 // Supply region(country) for users who still package Chinese 2942 // bundles using old convension. 2943 switch (script) { 2944 case "Hans": 2945 region = "CN"; 2946 break; 2947 case "Hant": 2948 region = "TW"; 2949 break; 2950 } 2951 } 2952 } 2953 2954 // With script, after truncating variant, region and script, 2955 // start over without script. 2956 if (variants != null) { 2957 for (String v : variants) { 2958 list.add(Locale.getInstance(language, "", region, v, null)); 2959 } 2960 } 2961 if (region.length() > 0) { 2962 list.add(Locale.getInstance(language, "", region, "", null)); 2963 } 2964 } 2965 if (language.length() > 0) { 2966 list.add(Locale.getInstance(language, "", "", "", null)); 2967 } 2968 // Add root locale at the end 2969 list.add(Locale.ROOT); 2970 2971 return list; 2972 } 2973 } 2974 2975 /** 2976 * Returns a <code>Locale</code> to be used as a fallback locale for 2977 * further resource bundle searches by the 2978 * <code>ResourceBundle.getBundle</code> factory method. This method 2979 * is called from the factory method every time when no resulting 2980 * resource bundle has been found for <code>baseName</code> and 2981 * <code>locale</code>, where locale is either the parameter for 2982 * <code>ResourceBundle.getBundle</code> or the previous fallback 2983 * locale returned by this method. 2984 * 2985 * <p>The method returns <code>null</code> if no further fallback 2986 * search is desired. 2987 * 2988 * <p>The default implementation returns the {@linkplain 2989 * Locale#getDefault() default <code>Locale</code>} if the given 2990 * <code>locale</code> isn't the default one. Otherwise, 2991 * <code>null</code> is returned. 2992 * 2993 * @param baseName 2994 * the base name of the resource bundle, a fully 2995 * qualified class name for which 2996 * <code>ResourceBundle.getBundle</code> has been 2997 * unable to find any resource bundles (except for the 2998 * base bundle) 2999 * @param locale 3000 * the <code>Locale</code> for which 3001 * <code>ResourceBundle.getBundle</code> has been 3002 * unable to find any resource bundles (except for the 3003 * base bundle) 3004 * @return a <code>Locale</code> for the fallback search, 3005 * or <code>null</code> if no further fallback search 3006 * is desired. 3007 * @exception NullPointerException 3008 * if <code>baseName</code> or <code>locale</code> 3009 * is <code>null</code> 3010 */ 3011 public Locale getFallbackLocale(String baseName, Locale locale) { 3012 if (baseName == null) { 3013 throw new NullPointerException(); 3014 } 3015 Locale defaultLocale = Locale.getDefault(); 3016 return locale.equals(defaultLocale) ? null : defaultLocale; 3017 } 3018 3019 /** 3020 * Instantiates a resource bundle for the given bundle name of the 3021 * given format and locale, using the given class loader if 3022 * necessary. This method returns <code>null</code> if there is no 3023 * resource bundle available for the given parameters. If a resource 3024 * bundle can't be instantiated due to an unexpected error, the 3025 * error must be reported by throwing an <code>Error</code> or 3026 * <code>Exception</code> rather than simply returning 3027 * <code>null</code>. 3028 * 3029 * <p>If the <code>reload</code> flag is <code>true</code>, it 3030 * indicates that this method is being called because the previously 3031 * loaded resource bundle has expired. 3032 * 3033 * @implSpec 3034 * 3035 * Resource bundles in named modules are subject to the encapsulation 3036 * rules specified by {@link Module#getResourceAsStream Module.getResourceAsStream}. 3037 * A resource bundle in a named module visible to the given class loader 3038 * is accessible when the package of the resource file corresponding 3039 * to the resource bundle is open unconditionally. 3040 * 3041 * <p>The default implementation instantiates a 3042 * <code>ResourceBundle</code> as follows. 3043 * 3044 * <ul> 3045 * 3046 * <li>The bundle name is obtained by calling {@link 3047 * #toBundleName(String, Locale) toBundleName(baseName, 3048 * locale)}.</li> 3049 * 3050 * <li>If <code>format</code> is <code>"java.class"</code>, the 3051 * {@link Class} specified by the bundle name is loaded with the 3052 * given class loader. If the {@code Class} is found and accessible 3053 * then the <code>ResourceBundle</code> is instantiated. The 3054 * resource bundle is accessible if the package of the bundle class file 3055 * is open unconditionally; otherwise, {@code IllegalAccessException} 3056 * will be thrown. 3057 * Note that the <code>reload</code> flag is ignored for loading 3058 * class-based resource bundles in this default implementation. 3059 * </li> 3060 * 3061 * <li>If <code>format</code> is <code>"java.properties"</code>, 3062 * {@link #toResourceName(String, String) toResourceName(bundlename, 3063 * "properties")} is called to get the resource name. 3064 * If <code>reload</code> is <code>true</code>, {@link 3065 * ClassLoader#getResource(String) load.getResource} is called 3066 * to get a {@link URL} for creating a {@link 3067 * URLConnection}. This <code>URLConnection</code> is used to 3068 * {@linkplain URLConnection#setUseCaches(boolean) disable the 3069 * caches} of the underlying resource loading layers, 3070 * and to {@linkplain URLConnection#getInputStream() get an 3071 * <code>InputStream</code>}. 3072 * Otherwise, {@link ClassLoader#getResourceAsStream(String) 3073 * loader.getResourceAsStream} is called to get an {@link 3074 * InputStream}. Then, a {@link 3075 * PropertyResourceBundle} is constructed with the 3076 * <code>InputStream</code>.</li> 3077 * 3078 * <li>If <code>format</code> is neither <code>"java.class"</code> 3079 * nor <code>"java.properties"</code>, an 3080 * <code>IllegalArgumentException</code> is thrown.</li> 3081 * 3082 * </ul> 3083 * 3084 * @param baseName 3085 * the base bundle name of the resource bundle, a fully 3086 * qualified class name 3087 * @param locale 3088 * the locale for which the resource bundle should be 3089 * instantiated 3090 * @param format 3091 * the resource bundle format to be loaded 3092 * @param loader 3093 * the <code>ClassLoader</code> to use to load the bundle 3094 * @param reload 3095 * the flag to indicate bundle reloading; <code>true</code> 3096 * if reloading an expired resource bundle, 3097 * <code>false</code> otherwise 3098 * @return the resource bundle instance, 3099 * or <code>null</code> if none could be found. 3100 * @exception NullPointerException 3101 * if <code>bundleName</code>, <code>locale</code>, 3102 * <code>format</code>, or <code>loader</code> is 3103 * <code>null</code>, or if <code>null</code> is returned by 3104 * {@link #toBundleName(String, Locale) toBundleName} 3105 * @exception IllegalArgumentException 3106 * if <code>format</code> is unknown, or if the resource 3107 * found for the given parameters contains malformed data. 3108 * @exception ClassCastException 3109 * if the loaded class cannot be cast to <code>ResourceBundle</code> 3110 * @exception IllegalAccessException 3111 * if the class or its nullary constructor is not 3112 * accessible. 3113 * @exception InstantiationException 3114 * if the instantiation of a class fails for some other 3115 * reason. 3116 * @exception ExceptionInInitializerError 3117 * if the initialization provoked by this method fails. 3118 * @exception SecurityException 3119 * If a security manager is present and creation of new 3120 * instances is denied. See {@link Class#newInstance()} 3121 * for details. 3122 * @exception IOException 3123 * if an error occurred when reading resources using 3124 * any I/O operations 3125 * @see java.util.spi.ResourceBundleProvider#getBundle(String, Locale) 3126 * @revised 9 3127 * @spec JPMS 3128 */ 3129 public ResourceBundle newBundle(String baseName, Locale locale, String format, 3130 ClassLoader loader, boolean reload) 3131 throws IllegalAccessException, InstantiationException, IOException { 3132 /* 3133 * Legacy mechanism to locate resource bundle in unnamed module only 3134 * that is visible to the given loader and accessible to the given caller. 3135 */ 3136 String bundleName = toBundleName(baseName, locale); 3137 ResourceBundle bundle = null; 3138 if (format.equals("java.class")) { 3139 try { 3140 Class<?> c = loader.loadClass(bundleName); 3141 // If the class isn't a ResourceBundle subclass, throw a 3142 // ClassCastException. 3143 if (ResourceBundle.class.isAssignableFrom(c)) { 3144 @SuppressWarnings("unchecked") 3145 Class<ResourceBundle> bundleClass = (Class<ResourceBundle>)c; 3146 Module m = bundleClass.getModule(); 3147 3148 // To access a resource bundle in a named module, 3149 // either class-based or properties-based, the resource 3150 // bundle must be opened unconditionally, 3151 // same rule as accessing a resource file. 3152 if (m.isNamed() && !m.isOpen(bundleClass.getPackageName())) { 3153 throw new IllegalAccessException("unnamed module can't load " + 3154 bundleClass.getName() + " in " + m.toString()); 3155 } 3156 try { 3157 // bundle in a unnamed module 3158 Constructor<ResourceBundle> ctor = bundleClass.getConstructor(); 3159 if (!Modifier.isPublic(ctor.getModifiers())) { 3160 return null; 3161 } 3162 3163 // java.base may not be able to read the bundleClass's module. 3164 PrivilegedAction<Void> pa1 = () -> { ctor.setAccessible(true); return null; }; 3165 AccessController.doPrivileged(pa1); 3166 bundle = ctor.newInstance((Object[]) null); 3167 } catch (InvocationTargetException e) { 3168 uncheckedThrow(e); 3169 } 3170 } else { 3171 throw new ClassCastException(c.getName() 3172 + " cannot be cast to ResourceBundle"); 3173 } 3174 } catch (ClassNotFoundException|NoSuchMethodException e) { 3175 } 3176 } else if (format.equals("java.properties")) { 3177 final String resourceName = toResourceName0(bundleName, "properties"); 3178 if (resourceName == null) { 3179 return bundle; 3180 } 3181 3182 final boolean reloadFlag = reload; 3183 InputStream stream = null; 3184 try { 3185 stream = AccessController.doPrivileged( 3186 new PrivilegedExceptionAction<>() { 3187 public InputStream run() throws IOException { 3188 URL url = loader.getResource(resourceName); 3189 if (url == null) return null; 3190 3191 URLConnection connection = url.openConnection(); 3192 if (reloadFlag) { 3193 // Disable caches to get fresh data for 3194 // reloading. 3195 connection.setUseCaches(false); 3196 } 3197 return connection.getInputStream(); 3198 } 3199 }); 3200 } catch (PrivilegedActionException e) { 3201 throw (IOException) e.getException(); 3202 } 3203 if (stream != null) { 3204 try { 3205 bundle = new PropertyResourceBundle(stream); 3206 } finally { 3207 stream.close(); 3208 } 3209 } 3210 } else { 3211 throw new IllegalArgumentException("unknown format: " + format); 3212 } 3213 return bundle; 3214 } 3215 3216 /** 3217 * Returns the time-to-live (TTL) value for resource bundles that 3218 * are loaded under this 3219 * <code>ResourceBundle.Control</code>. Positive time-to-live values 3220 * specify the number of milliseconds a bundle can remain in the 3221 * cache without being validated against the source data from which 3222 * it was constructed. The value 0 indicates that a bundle must be 3223 * validated each time it is retrieved from the cache. {@link 3224 * #TTL_DONT_CACHE} specifies that loaded resource bundles are not 3225 * put in the cache. {@link #TTL_NO_EXPIRATION_CONTROL} specifies 3226 * that loaded resource bundles are put in the cache with no 3227 * expiration control. 3228 * 3229 * <p>The expiration affects only the bundle loading process by the 3230 * <code>ResourceBundle.getBundle</code> factory method. That is, 3231 * if the factory method finds a resource bundle in the cache that 3232 * has expired, the factory method calls the {@link 3233 * #needsReload(String, Locale, String, ClassLoader, ResourceBundle, 3234 * long) needsReload} method to determine whether the resource 3235 * bundle needs to be reloaded. If <code>needsReload</code> returns 3236 * <code>true</code>, the cached resource bundle instance is removed 3237 * from the cache. Otherwise, the instance stays in the cache, 3238 * updated with the new TTL value returned by this method. 3239 * 3240 * <p>All cached resource bundles are subject to removal from the 3241 * cache due to memory constraints of the runtime environment. 3242 * Returning a large positive value doesn't mean to lock loaded 3243 * resource bundles in the cache. 3244 * 3245 * <p>The default implementation returns {@link #TTL_NO_EXPIRATION_CONTROL}. 3246 * 3247 * @param baseName 3248 * the base name of the resource bundle for which the 3249 * expiration value is specified. 3250 * @param locale 3251 * the locale of the resource bundle for which the 3252 * expiration value is specified. 3253 * @return the time (0 or a positive millisecond offset from the 3254 * cached time) to get loaded bundles expired in the cache, 3255 * {@link #TTL_NO_EXPIRATION_CONTROL} to disable the 3256 * expiration control, or {@link #TTL_DONT_CACHE} to disable 3257 * caching. 3258 * @exception NullPointerException 3259 * if <code>baseName</code> or <code>locale</code> is 3260 * <code>null</code> 3261 */ 3262 public long getTimeToLive(String baseName, Locale locale) { 3263 if (baseName == null || locale == null) { 3264 throw new NullPointerException(); 3265 } 3266 return TTL_NO_EXPIRATION_CONTROL; 3267 } 3268 3269 /** 3270 * Determines if the expired <code>bundle</code> in the cache needs 3271 * to be reloaded based on the loading time given by 3272 * <code>loadTime</code> or some other criteria. The method returns 3273 * <code>true</code> if reloading is required; <code>false</code> 3274 * otherwise. <code>loadTime</code> is a millisecond offset since 3275 * the <a href="Calendar.html#Epoch"> <code>Calendar</code> 3276 * Epoch</a>. 3277 * 3278 * <p> 3279 * The calling <code>ResourceBundle.getBundle</code> factory method 3280 * calls this method on the <code>ResourceBundle.Control</code> 3281 * instance used for its current invocation, not on the instance 3282 * used in the invocation that originally loaded the resource 3283 * bundle. 3284 * 3285 * <p>The default implementation compares <code>loadTime</code> and 3286 * the last modified time of the source data of the resource 3287 * bundle. If it's determined that the source data has been modified 3288 * since <code>loadTime</code>, <code>true</code> is 3289 * returned. Otherwise, <code>false</code> is returned. This 3290 * implementation assumes that the given <code>format</code> is the 3291 * same string as its file suffix if it's not one of the default 3292 * formats, <code>"java.class"</code> or 3293 * <code>"java.properties"</code>. 3294 * 3295 * @param baseName 3296 * the base bundle name of the resource bundle, a 3297 * fully qualified class name 3298 * @param locale 3299 * the locale for which the resource bundle 3300 * should be instantiated 3301 * @param format 3302 * the resource bundle format to be loaded 3303 * @param loader 3304 * the <code>ClassLoader</code> to use to load the bundle 3305 * @param bundle 3306 * the resource bundle instance that has been expired 3307 * in the cache 3308 * @param loadTime 3309 * the time when <code>bundle</code> was loaded and put 3310 * in the cache 3311 * @return <code>true</code> if the expired bundle needs to be 3312 * reloaded; <code>false</code> otherwise. 3313 * @exception NullPointerException 3314 * if <code>baseName</code>, <code>locale</code>, 3315 * <code>format</code>, <code>loader</code>, or 3316 * <code>bundle</code> is <code>null</code> 3317 */ 3318 public boolean needsReload(String baseName, Locale locale, 3319 String format, ClassLoader loader, 3320 ResourceBundle bundle, long loadTime) { 3321 if (bundle == null) { 3322 throw new NullPointerException(); 3323 } 3324 if (format.equals("java.class") || format.equals("java.properties")) { 3325 format = format.substring(5); 3326 } 3327 boolean result = false; 3328 try { 3329 String resourceName = toResourceName0(toBundleName(baseName, locale), format); 3330 if (resourceName == null) { 3331 return result; 3332 } 3333 URL url = loader.getResource(resourceName); 3334 if (url != null) { 3335 long lastModified = 0; 3336 URLConnection connection = url.openConnection(); 3337 if (connection != null) { 3338 // disable caches to get the correct data 3339 connection.setUseCaches(false); 3340 if (connection instanceof JarURLConnection) { 3341 JarEntry ent = ((JarURLConnection)connection).getJarEntry(); 3342 if (ent != null) { 3343 lastModified = ent.getTime(); 3344 if (lastModified == -1) { 3345 lastModified = 0; 3346 } 3347 } 3348 } else { 3349 lastModified = connection.getLastModified(); 3350 } 3351 } 3352 result = lastModified >= loadTime; 3353 } 3354 } catch (NullPointerException npe) { 3355 throw npe; 3356 } catch (Exception e) { 3357 // ignore other exceptions 3358 } 3359 return result; 3360 } 3361 3362 /** 3363 * Converts the given <code>baseName</code> and <code>locale</code> 3364 * to the bundle name. This method is called from the default 3365 * implementation of the {@link #newBundle(String, Locale, String, 3366 * ClassLoader, boolean) newBundle} and {@link #needsReload(String, 3367 * Locale, String, ClassLoader, ResourceBundle, long) needsReload} 3368 * methods. 3369 * 3370 * <p>This implementation returns the following value: 3371 * <pre> 3372 * baseName + "_" + language + "_" + script + "_" + country + "_" + variant 3373 * </pre> 3374 * where <code>language</code>, <code>script</code>, <code>country</code>, 3375 * and <code>variant</code> are the language, script, country, and variant 3376 * values of <code>locale</code>, respectively. Final component values that 3377 * are empty Strings are omitted along with the preceding '_'. When the 3378 * script is empty, the script value is omitted along with the preceding '_'. 3379 * If all of the values are empty strings, then <code>baseName</code> 3380 * is returned. 3381 * 3382 * <p>For example, if <code>baseName</code> is 3383 * <code>"baseName"</code> and <code>locale</code> is 3384 * <code>Locale("ja", "", "XX")</code>, then 3385 * <code>"baseName_ja_ _XX"</code> is returned. If the given 3386 * locale is <code>Locale("en")</code>, then 3387 * <code>"baseName_en"</code> is returned. 3388 * 3389 * <p>Overriding this method allows applications to use different 3390 * conventions in the organization and packaging of localized 3391 * resources. 3392 * 3393 * @param baseName 3394 * the base name of the resource bundle, a fully 3395 * qualified class name 3396 * @param locale 3397 * the locale for which a resource bundle should be 3398 * loaded 3399 * @return the bundle name for the resource bundle 3400 * @exception NullPointerException 3401 * if <code>baseName</code> or <code>locale</code> 3402 * is <code>null</code> 3403 * @see java.util.spi.AbstractResourceBundleProvider#toBundleName(String, Locale) 3404 */ 3405 public String toBundleName(String baseName, Locale locale) { 3406 if (locale == Locale.ROOT) { 3407 return baseName; 3408 } 3409 3410 String language = locale.getLanguage(); 3411 String script = locale.getScript(); 3412 String country = locale.getCountry(); 3413 String variant = locale.getVariant(); 3414 3415 if (language == "" && country == "" && variant == "") { 3416 return baseName; 3417 } 3418 3419 StringBuilder sb = new StringBuilder(baseName); 3420 sb.append('_'); 3421 if (script != "") { 3422 if (variant != "") { 3423 sb.append(language).append('_').append(script).append('_').append(country).append('_').append(variant); 3424 } else if (country != "") { 3425 sb.append(language).append('_').append(script).append('_').append(country); 3426 } else { 3427 sb.append(language).append('_').append(script); 3428 } 3429 } else { 3430 if (variant != "") { 3431 sb.append(language).append('_').append(country).append('_').append(variant); 3432 } else if (country != "") { 3433 sb.append(language).append('_').append(country); 3434 } else { 3435 sb.append(language); 3436 } 3437 } 3438 return sb.toString(); 3439 3440 } 3441 3442 /** 3443 * Converts the given <code>bundleName</code> to the form required 3444 * by the {@link ClassLoader#getResource ClassLoader.getResource} 3445 * method by replacing all occurrences of <code>'.'</code> in 3446 * <code>bundleName</code> with <code>'/'</code> and appending a 3447 * <code>'.'</code> and the given file <code>suffix</code>. For 3448 * example, if <code>bundleName</code> is 3449 * <code>"foo.bar.MyResources_ja_JP"</code> and <code>suffix</code> 3450 * is <code>"properties"</code>, then 3451 * <code>"foo/bar/MyResources_ja_JP.properties"</code> is returned. 3452 * 3453 * @param bundleName 3454 * the bundle name 3455 * @param suffix 3456 * the file type suffix 3457 * @return the converted resource name 3458 * @exception NullPointerException 3459 * if <code>bundleName</code> or <code>suffix</code> 3460 * is <code>null</code> 3461 */ 3462 public final String toResourceName(String bundleName, String suffix) { 3463 StringBuilder sb = new StringBuilder(bundleName.length() + 1 + suffix.length()); 3464 sb.append(bundleName.replace('.', '/')).append('.').append(suffix); 3465 return sb.toString(); 3466 } 3467 3468 private String toResourceName0(String bundleName, String suffix) { 3469 // application protocol check 3470 if (bundleName.contains("://")) { 3471 return null; 3472 } else { 3473 return toResourceName(bundleName, suffix); 3474 } 3475 } 3476 } 3477 3478 @SuppressWarnings("unchecked") 3479 private static <T extends Throwable> void uncheckedThrow(Throwable t) throws T { 3480 if (t != null) 3481 throw (T)t; 3482 else 3483 throw new Error("Unknown Exception"); 3484 } 3485 3486 private static class SingleFormatControl extends Control { 3487 private static final Control PROPERTIES_ONLY 3488 = new SingleFormatControl(FORMAT_PROPERTIES); 3489 3490 private static final Control CLASS_ONLY 3491 = new SingleFormatControl(FORMAT_CLASS); 3492 3493 private final List<String> formats; 3494 3495 protected SingleFormatControl(List<String> formats) { 3496 this.formats = formats; 3497 } 3498 3499 public List<String> getFormats(String baseName) { 3500 if (baseName == null) { 3501 throw new NullPointerException(); 3502 } 3503 return formats; 3504 } 3505 } 3506 3507 private static final class NoFallbackControl extends SingleFormatControl { 3508 private static final Control NO_FALLBACK 3509 = new NoFallbackControl(FORMAT_DEFAULT); 3510 3511 private static final Control PROPERTIES_ONLY_NO_FALLBACK 3512 = new NoFallbackControl(FORMAT_PROPERTIES); 3513 3514 private static final Control CLASS_ONLY_NO_FALLBACK 3515 = new NoFallbackControl(FORMAT_CLASS); 3516 3517 protected NoFallbackControl(List<String> formats) { 3518 super(formats); 3519 } 3520 3521 public Locale getFallbackLocale(String baseName, Locale locale) { 3522 if (baseName == null || locale == null) { 3523 throw new NullPointerException(); 3524 } 3525 return null; 3526 } 3527 } 3528 3529 private static class ResourceBundleProviderHelper { 3530 /** 3531 * Returns a new ResourceBundle instance of the given bundleClass 3532 */ 3533 static ResourceBundle newResourceBundle(Class<? extends ResourceBundle> bundleClass) { 3534 try { 3535 @SuppressWarnings("unchecked") 3536 Constructor<? extends ResourceBundle> ctor = 3537 bundleClass.getConstructor(); 3538 if (!Modifier.isPublic(ctor.getModifiers())) { 3539 return null; 3540 } 3541 // java.base may not be able to read the bundleClass's module. 3542 PrivilegedAction<Void> pa = () -> { ctor.setAccessible(true); return null;}; 3543 AccessController.doPrivileged(pa); 3544 try { 3545 return ctor.newInstance((Object[]) null); 3546 } catch (InvocationTargetException e) { 3547 uncheckedThrow(e); 3548 } catch (InstantiationException | IllegalAccessException e) { 3549 throw new InternalError(e); 3550 } 3551 } catch (NoSuchMethodException e) { 3552 throw new InternalError(e); 3553 } 3554 return null; 3555 } 3556 3557 /** 3558 * Loads a {@code ResourceBundle} of the given {@code bundleName} local to 3559 * the given {@code module}. If not found, search the bundle class 3560 * that is visible from the module's class loader. 3561 * 3562 * The caller module is used for access check only. 3563 */ 3564 static ResourceBundle loadResourceBundle(Module callerModule, 3565 Module module, 3566 String baseName, 3567 Locale locale) 3568 { 3569 String bundleName = Control.INSTANCE.toBundleName(baseName, locale); 3570 try { 3571 PrivilegedAction<Class<?>> pa = () -> Class.forName(module, bundleName); 3572 Class<?> c = AccessController.doPrivileged(pa, null, GET_CLASSLOADER_PERMISSION); 3573 trace("local in %s %s caller %s: %s%n", module, bundleName, callerModule, c); 3574 3575 if (c == null) { 3576 // if not found from the given module, locate resource bundle 3577 // that is visible to the module's class loader 3578 ClassLoader loader = getLoader(module); 3579 if (loader != null) { 3580 c = Class.forName(bundleName, false, loader); 3581 } else { 3582 c = BootLoader.loadClassOrNull(bundleName); 3583 } 3584 trace("loader for %s %s caller %s: %s%n", module, bundleName, callerModule, c); 3585 } 3586 3587 if (c != null && ResourceBundle.class.isAssignableFrom(c)) { 3588 @SuppressWarnings("unchecked") 3589 Class<ResourceBundle> bundleClass = (Class<ResourceBundle>) c; 3590 Module m = bundleClass.getModule(); 3591 if (!isAccessible(callerModule, m, bundleClass.getPackageName())) { 3592 trace(" %s does not have access to %s/%s%n", callerModule, 3593 m.getName(), bundleClass.getPackageName()); 3594 return null; 3595 } 3596 3597 return newResourceBundle(bundleClass); 3598 } 3599 } catch (ClassNotFoundException e) {} 3600 return null; 3601 } 3602 3603 /** 3604 * Tests if resources of the given package name from the given module are 3605 * open to the caller module. 3606 */ 3607 static boolean isAccessible(Module callerModule, Module module, String pn) { 3608 if (!module.isNamed() || callerModule == module) 3609 return true; 3610 3611 return module.isOpen(pn, callerModule); 3612 } 3613 3614 /** 3615 * Loads properties of the given {@code bundleName} local in the given 3616 * {@code module}. If the .properties is not found or not open 3617 * to the caller module to access, it will find the resource that 3618 * is visible to the module's class loader. 3619 * 3620 * The caller module is used for access check only. 3621 */ 3622 static ResourceBundle loadPropertyResourceBundle(Module callerModule, 3623 Module module, 3624 String baseName, 3625 Locale locale) 3626 throws IOException 3627 { 3628 String bundleName = Control.INSTANCE.toBundleName(baseName, locale); 3629 3630 PrivilegedAction<InputStream> pa = () -> { 3631 try { 3632 String resourceName = Control.INSTANCE 3633 .toResourceName0(bundleName, "properties"); 3634 if (resourceName == null) { 3635 return null; 3636 } 3637 trace("local in %s %s caller %s%n", module, resourceName, callerModule); 3638 3639 // if the package is in the given module but not opened 3640 // locate it from the given module first. 3641 String pn = toPackageName(bundleName); 3642 trace(" %s/%s is accessible to %s : %s%n", 3643 module.getName(), pn, callerModule, 3644 isAccessible(callerModule, module, pn)); 3645 if (isAccessible(callerModule, module, pn)) { 3646 InputStream in = module.getResourceAsStream(resourceName); 3647 if (in != null) { 3648 return in; 3649 } 3650 } 3651 3652 ClassLoader loader = module.getClassLoader(); 3653 trace("loader for %s %s caller %s%n", module, resourceName, callerModule); 3654 3655 try { 3656 if (loader != null) { 3657 return loader.getResourceAsStream(resourceName); 3658 } else { 3659 URL url = BootLoader.findResource(resourceName); 3660 if (url != null) { 3661 return url.openStream(); 3662 } 3663 } 3664 } catch (Exception e) {} 3665 return null; 3666 3667 } catch (IOException e) { 3668 throw new UncheckedIOException(e); 3669 } 3670 }; 3671 3672 try (InputStream stream = AccessController.doPrivileged(pa)) { 3673 if (stream != null) { 3674 return new PropertyResourceBundle(stream); 3675 } else { 3676 return null; 3677 } 3678 } catch (UncheckedIOException e) { 3679 throw e.getCause(); 3680 } 3681 } 3682 3683 private static String toPackageName(String bundleName) { 3684 int i = bundleName.lastIndexOf('.'); 3685 return i != -1 ? bundleName.substring(0, i) : ""; 3686 } 3687 3688 } 3689 3690 private static final boolean TRACE_ON = Boolean.valueOf( 3691 GetPropertyAction.privilegedGetProperty("resource.bundle.debug", "false")); 3692 3693 private static void trace(String format, Object... params) { 3694 if (TRACE_ON) 3695 System.out.format(format, params); 3696 } 3697 }