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