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