1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package ch.qos.cal10n.util;
23
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.net.URL;
27 import java.net.URLConnection;
28 import java.util.Locale;
29 import java.util.ResourceBundle;
30
31 public class PropertyResourceBundleFinder {
32
33 public static ResourceBundle getBundle(ClassLoader classLoader, String baseName,
34 Locale locale) {
35
36
37
38
39
40
41 baseName = baseName.replace('.', '/');
42
43 String languageAndCountryCandidate = computeLanguageAndCountryCandidate(
44 baseName, locale);
45 String languageOnlyCandidate = computeLanguageOnlyCandidate(baseName,
46 locale);
47
48 CAL10NPropertyResourceBundle cprbLanguageOnly = makePropertyResourceBundle(
49 classLoader, languageOnlyCandidate);
50 CAL10NPropertyResourceBundle cprbLanguageAndCountry = null;
51
52 if (languageAndCountryCandidate != null) {
53 cprbLanguageAndCountry = makePropertyResourceBundle(classLoader,
54 languageAndCountryCandidate);
55 }
56
57 if (cprbLanguageAndCountry != null) {
58 cprbLanguageAndCountry.setParent(cprbLanguageOnly);
59 return cprbLanguageAndCountry;
60 }
61 return cprbLanguageOnly;
62 }
63
64 private static CAL10NPropertyResourceBundle makePropertyResourceBundle(
65 ClassLoader classLoader, String resourceCandiate) {
66
67 CAL10NPropertyResourceBundle prb = null;
68
69 URL url = classLoader.getResource(resourceCandiate);
70 if (url != null) {
71 try {
72 InputStream in = openConnectionForUrl(url);
73 prb = new CAL10NPropertyResourceBundle(in);
74 in.close();
75 } catch (IOException e) {
76 }
77 }
78 return prb;
79 }
80
81 private static String computeLanguageAndCountryCandidate(String baseName,
82 Locale locale) {
83 String language = locale.getLanguage();
84 String country = locale.getCountry();
85 if (country != null && country.length() > 0) {
86 return baseName + "_" + language + "_" + country + ".properties";
87 } else {
88 return null;
89 }
90 }
91
92 private static String computeLanguageOnlyCandidate(String baseName, Locale locale) {
93 String language = locale.getLanguage();
94 return baseName + "_" + language + ".properties";
95 }
96
97 private static InputStream openConnectionForUrl(URL url) throws IOException {
98 URLConnection urlConnection = url.openConnection();
99 urlConnection.setDefaultUseCaches(false);
100 InputStream in = urlConnection.getInputStream();
101 return in;
102 }
103 }