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