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