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