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
30 public class PropertyResourceBundleFinder {
31
32 public static CAL10NPropertyResourceBundle getBundle(ClassLoader classLoader, String baseName,
33 Locale locale) {
34
35
36
37
38
39
40 baseName = baseName.replace('.', '/');
41
42 String languageAndCountryCandidate = computeLanguageAndCountryCandidate(
43 baseName, locale);
44 String languageOnlyCandidate = computeLanguageOnlyCandidate(baseName,
45 locale);
46
47 CAL10NPropertyResourceBundle cprbLanguageOnly = makePropertyResourceBundle(
48 classLoader, languageOnlyCandidate);
49 CAL10NPropertyResourceBundle cprbLanguageAndCountry = null;
50
51 if (languageAndCountryCandidate != null) {
52 cprbLanguageAndCountry = makePropertyResourceBundle(classLoader,
53 languageAndCountryCandidate);
54 }
55
56 if (cprbLanguageAndCountry != null) {
57 cprbLanguageAndCountry.setParent(cprbLanguageOnly);
58 return cprbLanguageAndCountry;
59 }
60 return cprbLanguageOnly;
61 }
62
63 private static CAL10NPropertyResourceBundle makePropertyResourceBundle(
64 ClassLoader classLoader, String resourceCandiate) {
65
66 CAL10NPropertyResourceBundle prb = null;
67
68 URL url = classLoader.getResource(resourceCandiate);
69 if (url != null) {
70 try {
71 InputStream in = openConnectionForUrl(url);
72 prb = new CAL10NPropertyResourceBundle(in, MiscUtil.urlToFile(url));
73 in.close();
74 } catch (IOException e) {
75 }
76 }
77 return prb;
78 }
79
80 private static String computeLanguageAndCountryCandidate(String baseName,
81 Locale locale) {
82 String language = locale.getLanguage();
83 String country = locale.getCountry();
84 if (country != null && country.length() > 0) {
85 return baseName + "_" + language + "_" + country + ".properties";
86 } else {
87 return null;
88 }
89 }
90
91 private static String computeLanguageOnlyCandidate(String baseName, Locale locale) {
92 String language = locale.getLanguage();
93 return baseName + "_" + language + ".properties";
94 }
95
96 private static InputStream openConnectionForUrl(URL url) throws IOException {
97 URLConnection urlConnection = url.openConnection();
98 urlConnection.setDefaultUseCaches(false);
99 InputStream in = urlConnection.getInputStream();
100 return in;
101 }
102 }