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