1 package ch.qos.cal10n.util;
2
3
4 import java.io.*;
5 import java.net.URL;
6 import java.net.URLConnection;
7 import java.util.Locale;
8
9
10
11
12 public abstract class AbstractCAL10NBundleFinder implements CAL10NBundleFinder {
13
14 public CAL10NBundle getBundle(String baseName, Locale locale, String charset) {
15
16
17
18
19
20
21
22 baseName = baseName.replace('.', '/');
23
24 String languageAndCountryCandidate = computeLanguageAndCountryCandidate(
25 baseName, locale);
26 String languageOnlyCandidate = computeLanguageOnlyCandidate(baseName,
27 locale);
28
29 CAL10NBundle cprbLanguageOnly = makePropertyResourceBundle(languageOnlyCandidate, charset);
30 CAL10NBundle cprbLanguageAndCountry = null;
31
32 if (languageAndCountryCandidate != null) {
33 cprbLanguageAndCountry = makePropertyResourceBundle(languageAndCountryCandidate, charset);
34 }
35
36 if (cprbLanguageAndCountry != null) {
37 cprbLanguageAndCountry.setParent(cprbLanguageOnly);
38 return cprbLanguageAndCountry;
39 }
40 return cprbLanguageOnly;
41 }
42
43 private String computeLanguageAndCountryCandidate(String baseName,
44 Locale locale) {
45 String language = locale.getLanguage();
46 String country = locale.getCountry();
47 if (country != null && country.length() > 0) {
48 return baseName + "_" + language + "_" + country + ".properties";
49 } else {
50 return null;
51 }
52 }
53
54 abstract protected URL getResource(String resourceCandidate);
55
56 private CAL10NBundle makePropertyResourceBundle(String resourceCandidate, String charset) {
57
58 CAL10NBundle prb = null;
59 URL url = getResource(resourceCandidate);
60 if (url != null) {
61 try {
62 InputStream in = openConnectionForUrl(url);
63
64 Reader reader = toReader(in, charset);
65 if (charset == null || charset.length() == 0)
66 reader = new InputStreamReader(in);
67 else
68 reader = new InputStreamReader(in, charset);
69
70 prb = new CAL10NBundle(reader, MiscUtil.urlToFile(url));
71 in.close();
72 } catch (IOException e) {
73 }
74 }
75 return prb;
76 }
77
78 private String computeLanguageOnlyCandidate(String baseName,
79 Locale locale) {
80 String language = locale.getLanguage();
81 return baseName + "_" + language + ".properties";
82 }
83
84 Reader toReader(InputStream in, String charset) {
85 if (charset == null || charset.length() == 0)
86 return new InputStreamReader(in);
87 else {
88 try {
89 return new InputStreamReader(in, charset);
90 } catch (UnsupportedEncodingException e) {
91 throw new IllegalArgumentException("Failed to open reader", e);
92 }
93 }
94 }
95
96 private 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 }