forked from openjdk/jdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResourceBundle.java
More file actions
3737 lines (3529 loc) · 162 KB
/
Copy pathResourceBundle.java
File metadata and controls
3737 lines (3529 loc) · 162 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package java.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.jar.JarEntry;
import java.util.spi.ResourceBundleControlProvider;
import java.util.spi.ResourceBundleProvider;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jdk.internal.loader.BootLoader;
import jdk.internal.access.JavaUtilResourceBundleAccess;
import jdk.internal.access.SharedSecrets;
import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.Reflection;
import sun.security.action.GetPropertyAction;
import sun.util.locale.BaseLocale;
import sun.util.locale.LocaleObjectCache;
import static sun.security.util.SecurityConstants.GET_CLASSLOADER_PERMISSION;
/**
*
* Resource bundles contain locale-specific objects. When your program needs a
* locale-specific resource, a {@code String} for example, your program can
* load it from the resource bundle that is appropriate for the current user's
* locale. In this way, you can write program code that is largely independent
* of the user's locale isolating most, if not all, of the locale-specific
* information in resource bundles.
*
* <p>
* This allows you to write programs that can:
* <UL>
* <LI> be easily localized, or translated, into different languages
* <LI> handle multiple locales at once
* <LI> be easily modified later to support even more locales
* </UL>
*
* <P>
* Resource bundles belong to families whose members share a common base
* name, but whose names also have additional components that identify
* their locales. For example, the base name of a family of resource
* bundles might be "MyResources". The family should have a default
* resource bundle which simply has the same name as its family -
* "MyResources" - and will be used as the bundle of last resort if a
* specific locale is not supported. The family can then provide as
* many locale-specific members as needed, for example a German one
* named "MyResources_de".
*
* <P>
* Each resource bundle in a family contains the same items, but the items have
* been translated for the locale represented by that resource bundle.
* For example, both "MyResources" and "MyResources_de" may have a
* {@code String} that's used on a button for canceling operations.
* In "MyResources" the {@code String} may contain "Cancel" and in
* "MyResources_de" it may contain "Abbrechen".
*
* <P>
* If there are different resources for different countries, you
* can make specializations: for example, "MyResources_de_CH" contains objects for
* the German language (de) in Switzerland (CH). If you want to only
* modify some of the resources
* in the specialization, you can do so.
*
* <P>
* When your program needs a locale-specific object, it loads
* the {@code ResourceBundle} class using the
* {@link #getBundle(java.lang.String, java.util.Locale) getBundle}
* method:
* <blockquote>
* <pre>
* ResourceBundle myResources =
* ResourceBundle.getBundle("MyResources", currentLocale);
* </pre>
* </blockquote>
*
* <P>
* Resource bundles contain key/value pairs. The keys uniquely
* identify a locale-specific object in the bundle. Here's an
* example of a {@code ListResourceBundle} that contains
* two key/value pairs:
* <blockquote>
* <pre>
* public class MyResources extends ListResourceBundle {
* protected Object[][] getContents() {
* return new Object[][] {
* // LOCALIZE THE SECOND STRING OF EACH ARRAY (e.g., "OK")
* {"OkKey", "OK"},
* {"CancelKey", "Cancel"},
* // END OF MATERIAL TO LOCALIZE
* };
* }
* }
* </pre>
* </blockquote>
* Keys are always {@code String}s.
* In this example, the keys are "OkKey" and "CancelKey".
* In the above example, the values
* are also {@code String}s--"OK" and "Cancel"--but
* they don't have to be. The values can be any type of object.
*
* <P>
* You retrieve an object from resource bundle using the appropriate
* getter method. Because "OkKey" and "CancelKey"
* are both strings, you would use {@code getString} to retrieve them:
* <blockquote>
* <pre>
* button1 = new Button(myResources.getString("OkKey"));
* button2 = new Button(myResources.getString("CancelKey"));
* </pre>
* </blockquote>
* The getter methods all require the key as an argument and return
* the object if found. If the object is not found, the getter method
* throws a {@code MissingResourceException}.
*
* <P>
* Besides {@code getString}, {@code ResourceBundle} also provides
* a method for getting string arrays, {@code getStringArray},
* as well as a generic {@code getObject} method for any other
* type of object. When using {@code getObject}, you'll
* have to cast the result to the appropriate type. For example:
* <blockquote>
* <pre>
* int[] myIntegers = (int[]) myResources.getObject("intList");
* </pre>
* </blockquote>
*
* <P>
* The Java Platform provides two subclasses of {@code ResourceBundle},
* {@code ListResourceBundle} and {@code PropertyResourceBundle},
* that provide a fairly simple way to create resources.
* As you saw briefly in a previous example, {@code ListResourceBundle}
* manages its resource as a list of key/value pairs.
* {@code PropertyResourceBundle} uses a properties file to manage
* its resources.
*
* <p>
* If {@code ListResourceBundle} or {@code PropertyResourceBundle}
* do not suit your needs, you can write your own {@code ResourceBundle}
* subclass. Your subclasses must override two methods: {@code handleGetObject}
* and {@code getKeys()}.
*
* <p>
* The implementation of a {@code ResourceBundle} subclass must be thread-safe
* if it's simultaneously used by multiple threads. The default implementations
* of the non-abstract methods in this class, and the methods in the direct
* known concrete subclasses {@code ListResourceBundle} and
* {@code PropertyResourceBundle} are thread-safe.
*
* <h2><a id="resource-bundle-modules">Resource Bundles and Named Modules</a></h2>
*
* Resource bundles can be deployed in modules in the following ways:
*
* <h3>Resource bundles together with an application</h3>
*
* Resource bundles can be deployed together with an application in the same
* module. In that case, the resource bundles are loaded
* by code in the module by calling the {@link #getBundle(String)}
* or {@link #getBundle(String, Locale)} method.
*
* <h3><a id="service-providers">Resource bundles as service providers</a></h3>
*
* Resource bundles can be deployed in one or more <em>service provider modules</em>
* and they can be located using {@link ServiceLoader}.
* A {@linkplain ResourceBundleProvider service} interface or class must be
* defined. The caller module declares that it uses the service, the service
* provider modules declare that they provide implementations of the service.
* Refer to {@link ResourceBundleProvider} for developing resource bundle
* services and deploying resource bundle providers.
* The module obtaining the resource bundle can be a resource bundle
* provider itself; in which case this module only locates the resource bundle
* via service provider mechanism.
*
* <p>A {@linkplain ResourceBundleProvider resource bundle provider} can
* provide resource bundles in any format such XML which replaces the need
* of {@link Control ResourceBundle.Control}.
*
* <h3><a id="other-modules">Resource bundles in other modules and class path</a></h3>
*
* Resource bundles in a named module may be <em>encapsulated</em> so that
* it cannot be located by code in other modules. Resource bundles
* in unnamed modules and class path are open for any module to access.
* Resource bundle follows the resource encapsulation rules as specified
* in {@link Module#getResourceAsStream(String)}.
*
* <p>The {@code getBundle} factory methods with no {@code Control} parameter
* locate and load resource bundles from
* {@linkplain ResourceBundleProvider service providers}.
* It may continue the search as if calling {@link Module#getResourceAsStream(String)}
* to find the named resource from a given module and calling
* {@link ClassLoader#getResourceAsStream(String)}; refer to
* the specification of the {@code getBundle} method for details.
* Only non-encapsulated resource bundles of "{@code java.class}"
* or "{@code java.properties}" format are searched.
*
* <p>If the caller module is a
* <a href="{@docRoot}/java.base/java/util/spi/ResourceBundleProvider.html#obtain-resource-bundle">
* resource bundle provider</a>, it does not fall back to the
* class loader search.
*
* <h3>Resource bundles in automatic modules</h3>
*
* A common format of resource bundles is in {@linkplain PropertyResourceBundle
* .properties} file format. Typically {@code .properties} resource bundles
* are packaged in a JAR file. Resource bundle only JAR file can be readily
* deployed as an <a href="{@docRoot}/java.base/java/lang/module/ModuleFinder.html#automatic-modules">
* automatic module</a>. For example, if the JAR file contains the
* entry "{@code p/q/Foo_ja.properties}" and no {@code .class} entry,
* when resolved and defined as an automatic module, no package is derived
* for this module. This allows resource bundles in {@code .properties}
* format packaged in one or more JAR files that may contain entries
* in the same directory and can be resolved successfully as
* automatic modules.
*
* <h3>ResourceBundle.Control</h3>
*
* The {@link ResourceBundle.Control} class provides information necessary
* to perform the bundle loading process by the {@code getBundle}
* factory methods that take a {@code ResourceBundle.Control}
* instance. You can implement your own subclass in order to enable
* non-standard resource bundle formats, change the search strategy, or
* define caching parameters. Refer to the descriptions of the class and the
* {@link #getBundle(String, Locale, ClassLoader, Control) getBundle}
* factory method for details.
*
* <p> {@link ResourceBundle.Control} is designed for an application deployed
* in an unnamed module, for example to support resource bundles in
* non-standard formats or package localized resources in a non-traditional
* convention. {@link ResourceBundleProvider} is the replacement for
* {@code ResourceBundle.Control} when migrating to modules.
* {@code UnsupportedOperationException} will be thrown when a factory
* method that takes the {@code ResourceBundle.Control} parameter is called.
*
* <p><a id="modify_default_behavior">For the {@code getBundle} factory</a>
* methods that take no {@link Control} instance, their <a
* href="#default_behavior"> default behavior</a> of resource bundle loading
* can be modified with custom {@link
* ResourceBundleControlProvider} implementations.
* If any of the
* providers provides a {@link Control} for the given base name, that {@link
* Control} will be used instead of the default {@link Control}. If there is
* more than one service provider for supporting the same base name,
* the first one returned from {@link ServiceLoader} will be used.
* A custom {@link Control} implementation is ignored by named modules.
*
* <h2>Cache Management</h2>
*
* Resource bundle instances created by the {@code getBundle} factory
* methods are cached by default, and the factory methods return the same
* resource bundle instance multiple times if it has been
* cached. {@code getBundle} clients may clear the cache, manage the
* lifetime of cached resource bundle instances using time-to-live values,
* or specify not to cache resource bundle instances. Refer to the
* descriptions of the {@linkplain #getBundle(String, Locale, ClassLoader,
* Control) {@code getBundle} factory method}, {@link
* #clearCache(ClassLoader) clearCache}, {@link
* Control#getTimeToLive(String, Locale)
* ResourceBundle.Control.getTimeToLive}, and {@link
* Control#needsReload(String, Locale, String, ClassLoader, ResourceBundle,
* long) ResourceBundle.Control.needsReload} for details.
*
* <h2>Example</h2>
*
* The following is a very simple example of a {@code ResourceBundle}
* subclass, {@code MyResources}, that manages two resources (for a larger number of
* resources you would probably use a {@code Map}).
* Notice that you don't need to supply a value if
* a "parent-level" {@code ResourceBundle} handles the same
* key with the same value (as for the okKey below).
* <blockquote>
* <pre>
* // default (English language, United States)
* public class MyResources extends ResourceBundle {
* public Object handleGetObject(String key) {
* if (key.equals("okKey")) return "Ok";
* if (key.equals("cancelKey")) return "Cancel";
* return null;
* }
*
* public Enumeration<String> getKeys() {
* return Collections.enumeration(keySet());
* }
*
* // Overrides handleKeySet() so that the getKeys() implementation
* // can rely on the keySet() value.
* protected Set<String> handleKeySet() {
* return new HashSet<String>(Arrays.asList("okKey", "cancelKey"));
* }
* }
*
* // German language
* public class MyResources_de extends MyResources {
* public Object handleGetObject(String key) {
* // don't need okKey, since parent level handles it.
* if (key.equals("cancelKey")) return "Abbrechen";
* return null;
* }
*
* protected Set<String> handleKeySet() {
* return new HashSet<String>(Arrays.asList("cancelKey"));
* }
* }
* </pre>
* </blockquote>
* You do not have to restrict yourself to using a single family of
* {@code ResourceBundle}s. For example, you could have a set of bundles for
* exception messages, {@code ExceptionResources}
* ({@code ExceptionResources_fr}, {@code ExceptionResources_de}, ...),
* and one for widgets, {@code WidgetResource} ({@code WidgetResources_fr},
* {@code WidgetResources_de}, ...); breaking up the resources however you like.
*
* @see ListResourceBundle
* @see PropertyResourceBundle
* @see MissingResourceException
* @see ResourceBundleProvider
* @since 1.1
* @revised 9
* @spec JPMS
*/
public abstract class ResourceBundle {
/** initial size of the bundle cache */
private static final int INITIAL_CACHE_SIZE = 32;
static {
SharedSecrets.setJavaUtilResourceBundleAccess(
new JavaUtilResourceBundleAccess() {
@Override
public void setParent(ResourceBundle bundle,
ResourceBundle parent) {
bundle.setParent(parent);
}
@Override
public ResourceBundle getParent(ResourceBundle bundle) {
return bundle.parent;
}
@Override
public void setLocale(ResourceBundle bundle, Locale locale) {
bundle.locale = locale;
}
@Override
public void setName(ResourceBundle bundle, String name) {
bundle.name = name;
}
@Override
public ResourceBundle getBundle(String baseName, Locale locale, Module module) {
// use the given module as the caller to bypass the access check
return getBundleImpl(module, module,
baseName, locale,
getDefaultControl(module, baseName));
}
@Override
public ResourceBundle newResourceBundle(Class<? extends ResourceBundle> bundleClass) {
return ResourceBundleProviderHelper.newResourceBundle(bundleClass);
}
});
}
/** constant indicating that no resource bundle exists */
private static final ResourceBundle NONEXISTENT_BUNDLE = new ResourceBundle() {
public Enumeration<String> getKeys() { return null; }
protected Object handleGetObject(String key) { return null; }
public String toString() { return "NONEXISTENT_BUNDLE"; }
};
/**
* The cache is a map from cache keys (with bundle base name, locale, and
* class loader) to either a resource bundle or NONEXISTENT_BUNDLE wrapped by a
* BundleReference.
*
* The cache is a ConcurrentMap, allowing the cache to be searched
* concurrently by multiple threads. This will also allow the cache keys
* to be reclaimed along with the ClassLoaders they reference.
*
* This variable would be better named "cache", but we keep the old
* name for compatibility with some workarounds for bug 4212439.
*/
private static final ConcurrentMap<CacheKey, BundleReference> cacheList
= new ConcurrentHashMap<>(INITIAL_CACHE_SIZE);
/**
* Queue for reference objects referring to class loaders or bundles.
*/
private static final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
/**
* Returns the base name of this bundle, if known, or {@code null} if unknown.
*
* If not null, then this is the value of the {@code baseName} parameter
* that was passed to the {@code ResourceBundle.getBundle(...)} method
* when the resource bundle was loaded.
*
* @return The base name of the resource bundle, as provided to and expected
* by the {@code ResourceBundle.getBundle(...)} methods.
*
* @see #getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader)
*
* @since 1.8
*/
public String getBaseBundleName() {
return name;
}
/**
* The parent bundle of this bundle.
* The parent bundle is searched by {@link #getObject getObject}
* when this bundle does not contain a particular resource.
*/
protected ResourceBundle parent = null;
/**
* The locale for this bundle.
*/
private Locale locale = null;
/**
* The base bundle name for this bundle.
*/
private String name;
/**
* The flag indicating this bundle has expired in the cache.
*/
private volatile boolean expired;
/**
* The back link to the cache key. null if this bundle isn't in
* the cache (yet) or has expired.
*/
private volatile CacheKey cacheKey;
/**
* A Set of the keys contained only in this ResourceBundle.
*/
private volatile Set<String> keySet;
/**
* Sole constructor. (For invocation by subclass constructors, typically
* implicit.)
*/
public ResourceBundle() {
}
/**
* Gets a string for the given key from this resource bundle or one of its parents.
* Calling this method is equivalent to calling
* <blockquote>
* <code>(String) {@link #getObject(java.lang.String) getObject}(key)</code>.
* </blockquote>
*
* @param key the key for the desired string
* @throws NullPointerException if {@code key} is {@code null}
* @throws MissingResourceException if no object for the given key can be found
* @throws ClassCastException if the object found for the given key is not a string
* @return the string for the given key
*/
public final String getString(String key) {
return (String) getObject(key);
}
/**
* Gets a string array for the given key from this resource bundle or one of its parents.
* Calling this method is equivalent to calling
* <blockquote>
* <code>(String[]) {@link #getObject(java.lang.String) getObject}(key)</code>.
* </blockquote>
*
* @param key the key for the desired string array
* @throws NullPointerException if {@code key} is {@code null}
* @throws MissingResourceException if no object for the given key can be found
* @throws ClassCastException if the object found for the given key is not a string array
* @return the string array for the given key
*/
public final String[] getStringArray(String key) {
return (String[]) getObject(key);
}
/**
* Gets an object for the given key from this resource bundle or one of its parents.
* This method first tries to obtain the object from this resource bundle using
* {@link #handleGetObject(java.lang.String) handleGetObject}.
* If not successful, and the parent resource bundle is not null,
* it calls the parent's {@code getObject} method.
* If still not successful, it throws a MissingResourceException.
*
* @param key the key for the desired object
* @throws NullPointerException if {@code key} is {@code null}
* @throws MissingResourceException if no object for the given key can be found
* @return the object for the given key
*/
public final Object getObject(String key) {
Object obj = handleGetObject(key);
if (obj == null) {
if (parent != null) {
obj = parent.getObject(key);
}
if (obj == null) {
throw new MissingResourceException("Can't find resource for bundle "
+this.getClass().getName()
+", key "+key,
this.getClass().getName(),
key);
}
}
return obj;
}
/**
* Returns the locale of this resource bundle. This method can be used after a
* call to getBundle() to determine whether the resource bundle returned really
* corresponds to the requested locale or is a fallback.
*
* @return the locale of this resource bundle
*/
public Locale getLocale() {
return locale;
}
private static ClassLoader getLoader(Module module) {
PrivilegedAction<ClassLoader> pa = module::getClassLoader;
return AccessController.doPrivileged(pa);
}
/**
* @param module a non-null-screened module form the {@link CacheKey#getModule()}.
* @return the ClassLoader to use in {@link Control#needsReload}
* and {@link Control#newBundle}
*/
private static ClassLoader getLoaderForControl(Module module) {
ClassLoader loader = getLoader(module);
return loader == null ? ClassLoader.getPlatformClassLoader() : loader;
}
/**
* Sets the parent bundle of this bundle.
* The parent bundle is searched by {@link #getObject getObject}
* when this bundle does not contain a particular resource.
*
* @param parent this bundle's parent bundle.
*/
protected void setParent(ResourceBundle parent) {
assert parent != NONEXISTENT_BUNDLE;
this.parent = parent;
}
/**
* Key used for cached resource bundles. The key checks the base
* name, the locale, the bundle module, and the caller module
* to determine if the resource is a match to the requested one.
* The base name, the locale and both modules must have a non-null value.
*/
private static final class CacheKey {
// These four are the actual keys for lookup in Map.
private final String name;
private volatile Locale locale;
private final KeyElementReference<Module> moduleRef;
private final KeyElementReference<Module> callerRef;
// this is the part of hashCode that pertains to module and callerModule
// which can be GCed..
private final int modulesHash;
// bundle format which is necessary for calling
// Control.needsReload().
private volatile String format;
// These time values are in CacheKey so that NONEXISTENT_BUNDLE
// doesn't need to be cloned for caching.
// The time when the bundle has been loaded
private volatile long loadTime;
// The time when the bundle expires in the cache, or either
// Control.TTL_DONT_CACHE or Control.TTL_NO_EXPIRATION_CONTROL.
private volatile long expirationTime;
// Placeholder for an error report by a Throwable
private volatile Throwable cause;
// ResourceBundleProviders for loading ResourceBundles
private volatile ServiceLoader<ResourceBundleProvider> providers;
private volatile boolean providersChecked;
// Boolean.TRUE if the factory method caller provides a ResourceBundleProvier.
private volatile Boolean callerHasProvider;
CacheKey(String baseName, Locale locale, Module module, Module caller) {
Objects.requireNonNull(module);
Objects.requireNonNull(caller);
this.name = baseName;
this.locale = locale;
this.moduleRef = new KeyElementReference<>(module, referenceQueue, this);
this.callerRef = new KeyElementReference<>(caller, referenceQueue, this);
this.modulesHash = module.hashCode() ^ caller.hashCode();
}
CacheKey(CacheKey src) {
// Create References to src's modules
this.moduleRef = new KeyElementReference<>(
Objects.requireNonNull(src.getModule()), referenceQueue, this);
this.callerRef = new KeyElementReference<>(
Objects.requireNonNull(src.getCallerModule()), referenceQueue, this);
// Copy fields from src. ResourceBundleProviders related fields
// and "cause" should not be copied.
this.name = src.name;
this.locale = src.locale;
this.modulesHash = src.modulesHash;
this.format = src.format;
this.loadTime = src.loadTime;
this.expirationTime = src.expirationTime;
}
String getName() {
return name;
}
Locale getLocale() {
return locale;
}
CacheKey setLocale(Locale locale) {
this.locale = locale;
return this;
}
Module getModule() {
return moduleRef.get();
}
Module getCallerModule() {
return callerRef.get();
}
ServiceLoader<ResourceBundleProvider> getProviders() {
if (!providersChecked) {
providers = getServiceLoader(getModule(), name);
providersChecked = true;
}
return providers;
}
boolean hasProviders() {
return getProviders() != null;
}
boolean callerHasProvider() {
return callerHasProvider == Boolean.TRUE;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
try {
final CacheKey otherEntry = (CacheKey)other;
//quick check to see if they are not equal
if (modulesHash != otherEntry.modulesHash) {
return false;
}
//are the names the same?
if (!name.equals(otherEntry.name)) {
return false;
}
// are the locales the same?
if (!locale.equals(otherEntry.locale)) {
return false;
}
// are modules and callerModules the same and non-null?
Module module = getModule();
Module caller = getCallerModule();
return ((module != null) && (module.equals(otherEntry.getModule())) &&
(caller != null) && (caller.equals(otherEntry.getCallerModule())));
} catch (NullPointerException | ClassCastException e) {
}
return false;
}
@Override
public int hashCode() {
return (name.hashCode() << 3) ^ locale.hashCode() ^ modulesHash;
}
String getFormat() {
return format;
}
void setFormat(String format) {
this.format = format;
}
private void setCause(Throwable cause) {
if (this.cause == null) {
this.cause = cause;
} else {
// Override the cause if the previous one is
// ClassNotFoundException.
if (this.cause instanceof ClassNotFoundException) {
this.cause = cause;
}
}
}
private Throwable getCause() {
return cause;
}
@Override
public String toString() {
String l = locale.toString();
if (l.isEmpty()) {
if (!locale.getVariant().isEmpty()) {
l = "__" + locale.getVariant();
} else {
l = "\"\"";
}
}
return "CacheKey[" + name +
", locale=" + l +
", module=" + getModule() +
", callerModule=" + getCallerModule() +
", format=" + format +
"]";
}
}
/**
* The common interface to get a CacheKey in LoaderReference and
* BundleReference.
*/
private static interface CacheKeyReference {
public CacheKey getCacheKey();
}
/**
* References to a CacheKey element as a WeakReference so that it can be
* garbage collected when nobody else is using it.
*/
private static class KeyElementReference<T> extends WeakReference<T>
implements CacheKeyReference {
private final CacheKey cacheKey;
KeyElementReference(T referent, ReferenceQueue<Object> q, CacheKey key) {
super(referent, q);
cacheKey = key;
}
@Override
public CacheKey getCacheKey() {
return cacheKey;
}
}
/**
* References to bundles are soft references so that they can be garbage
* collected when they have no hard references.
*/
private static class BundleReference extends SoftReference<ResourceBundle>
implements CacheKeyReference {
private final CacheKey cacheKey;
BundleReference(ResourceBundle referent, ReferenceQueue<Object> q, CacheKey key) {
super(referent, q);
cacheKey = key;
}
@Override
public CacheKey getCacheKey() {
return cacheKey;
}
}
/**
* Gets a resource bundle using the specified base name, the default locale,
* and the caller module. Calling this method is equivalent to calling
* <blockquote>
* {@code getBundle(baseName, Locale.getDefault(), callerModule)},
* </blockquote>
*
* @param baseName the base name of the resource bundle, a fully qualified class name
* @throws java.lang.NullPointerException
* if {@code baseName} is {@code null}
* @throws MissingResourceException
* if no resource bundle for the specified base name can be found
* @return a resource bundle for the given base name and the default locale
*
* @see <a href="#default_behavior">Resource Bundle Search and Loading Strategy</a>
* @see <a href="#resource-bundle-modules">Resource Bundles and Named Modules</a>
*/
@CallerSensitive
public static final ResourceBundle getBundle(String baseName)
{
Class<?> caller = Reflection.getCallerClass();
return getBundleImpl(baseName, Locale.getDefault(),
caller, getDefaultControl(caller, baseName));
}
/**
* Returns a resource bundle using the specified base name, the
* default locale and the specified control. Calling this method
* is equivalent to calling
* <pre>
* getBundle(baseName, Locale.getDefault(),
* this.getClass().getClassLoader(), control),
* </pre>
* except that {@code getClassLoader()} is run with the security
* privileges of {@code ResourceBundle}. See {@link
* #getBundle(String, Locale, ClassLoader, Control) getBundle} for the
* complete description of the resource bundle loading process with a
* {@code ResourceBundle.Control}.
*
* @param baseName
* the base name of the resource bundle, a fully qualified class
* name
* @param control
* the control which gives information for the resource bundle
* loading process
* @return a resource bundle for the given base name and the default locale
* @throws NullPointerException
* if {@code baseName} or {@code control} is
* {@code null}
* @throws MissingResourceException
* if no resource bundle for the specified base name can be found
* @throws IllegalArgumentException
* if the given {@code control} doesn't perform properly
* (e.g., {@code control.getCandidateLocales} returns null.)
* Note that validation of {@code control} is performed as
* needed.
* @throws UnsupportedOperationException
* if this method is called in a named module
* @since 1.6
* @revised 9
* @spec JPMS
*/
@CallerSensitive
public static final ResourceBundle getBundle(String baseName,
Control control) {
Class<?> caller = Reflection.getCallerClass();
Locale targetLocale = Locale.getDefault();
checkNamedModule(caller);
return getBundleImpl(baseName, targetLocale, caller, control);
}
/**
* Gets a resource bundle using the specified base name and locale,
* and the caller module. Calling this method is equivalent to calling
* <blockquote>
* {@code getBundle(baseName, locale, callerModule)},
* </blockquote>
*
* @param baseName
* the base name of the resource bundle, a fully qualified class name
* @param locale
* the locale for which a resource bundle is desired
* @throws NullPointerException
* if {@code baseName} or {@code locale} is {@code null}
* @throws MissingResourceException
* if no resource bundle for the specified base name can be found
* @return a resource bundle for the given base name and locale
*
* @see <a href="#default_behavior">Resource Bundle Search and Loading Strategy</a>
* @see <a href="#resource-bundle-modules">Resource Bundles and Named Modules</a>
*/
@CallerSensitive
public static final ResourceBundle getBundle(String baseName,
Locale locale)
{
Class<?> caller = Reflection.getCallerClass();
return getBundleImpl(baseName, locale,
caller, getDefaultControl(caller, baseName));
}
/**
* Gets a resource bundle using the specified base name and the default locale
* on behalf of the specified module. This method is equivalent to calling
* <blockquote>
* {@code getBundle(baseName, Locale.getDefault(), module)}
* </blockquote>
*
* @param baseName the base name of the resource bundle,
* a fully qualified class name
* @param module the module for which the resource bundle is searched
* @throws NullPointerException
* if {@code baseName} or {@code module} is {@code null}
* @throws SecurityException
* if a security manager exists and the caller is not the specified
* module and doesn't have {@code RuntimePermission("getClassLoader")}
* @throws MissingResourceException
* if no resource bundle for the specified base name can be found in the
* specified module
* @return a resource bundle for the given base name and the default locale
* @since 9
* @spec JPMS
* @see ResourceBundleProvider
* @see <a href="#default_behavior">Resource Bundle Search and Loading Strategy</a>
* @see <a href="#resource-bundle-modules">Resource Bundles and Named Modules</a>
*/
@CallerSensitive
public static ResourceBundle getBundle(String baseName, Module module) {
return getBundleFromModule(Reflection.getCallerClass(), module, baseName,
Locale.getDefault(),
getDefaultControl(module, baseName));
}
/**
* Gets a resource bundle using the specified base name and locale
* on behalf of the specified module.
*
* <p> Resource bundles in named modules may be encapsulated. When
* the resource bundle is loaded from a
* {@linkplain ResourceBundleProvider service provider}, the caller module
* must have an appropriate <i>uses</i> clause in its <i>module descriptor</i>
* to declare that the module uses of {@link ResourceBundleProvider}
* for the named resource bundle.
* Otherwise, it will load the resource bundles that are local in the
* given module as if calling {@link Module#getResourceAsStream(String)}
* or that are visible to the class loader of the given module
* as if calling {@link ClassLoader#getResourceAsStream(String)}.
* When the resource bundle is loaded from the specified module, it is
* subject to the encapsulation rules specified by
* {@link Module#getResourceAsStream Module.getResourceAsStream}.
*
* <p>
* If the given {@code module} is an unnamed module, then this method is
* equivalent to calling {@link #getBundle(String, Locale, ClassLoader)
* getBundle(baseName, targetLocale, module.getClassLoader()} to load
* resource bundles that are visible to the class loader of the given
* unnamed module. Custom {@link java.util.spi.ResourceBundleControlProvider}
* implementations, if present, will only be invoked if the specified
* module is an unnamed module.
*
* @param baseName the base name of the resource bundle,
* a fully qualified class name
* @param targetLocale the locale for which a resource bundle is desired
* @param module the module for which the resource bundle is searched
* @throws NullPointerException
* if {@code baseName}, {@code targetLocale}, or {@code module} is