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