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