1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.cli2.resource;
18
19 import java.text.MessageFormat;
20
21 import java.util.Locale;
22 import java.util.MissingResourceException;
23 import java.util.ResourceBundle;
24
25
26
27
28
29
30 public class ResourceHelper {
31
32 private static final String PROP_LOCALE = "org.apache.commons.cli2.resource.bundle";
33
34
35 private static final String DEFAULT_BUNDLE =
36 "org.apache.commons.cli2.resource.CLIMessageBundle_en_US";
37 private static ResourceHelper helper;
38
39
40 private ResourceBundle bundle;
41
42 private String prop;
43
44
45
46
47 private ResourceHelper() {
48 String bundleName = System.getProperty(PROP_LOCALE);
49
50 if (bundleName == null) {
51 bundleName = DEFAULT_BUNDLE;
52 }
53
54 this.prop = bundleName;
55
56 int firstUnderscore = bundleName.indexOf('_');
57 int secondUnderscore = bundleName.indexOf('_', firstUnderscore + 1);
58
59 Locale locale;
60 if (firstUnderscore != -1) {
61 String language = bundleName.substring(firstUnderscore + 1, secondUnderscore);
62 String country = bundleName.substring(secondUnderscore + 1);
63 locale = new Locale(language, country);
64 }
65 else {
66 locale = Locale.getDefault();
67 }
68
69 try {
70 bundle = ResourceBundle.getBundle(bundleName, locale);
71 } catch (MissingResourceException exp) {
72 bundle = ResourceBundle.getBundle(DEFAULT_BUNDLE, locale);
73 }
74 }
75
76 public String getBundleName() {
77 return this.prop;
78 }
79
80
81
82
83
84 public static ResourceHelper getResourceHelper() {
85 String bundleName = System.getProperty(PROP_LOCALE);
86 if (helper == null || !helper.getBundleName().equals(bundleName)) {
87 helper = new ResourceHelper();
88 }
89
90 return helper;
91 }
92
93
94
95
96
97
98
99 public String getMessage(final String key) {
100 return getMessage(key, new Object[] { });
101 }
102
103
104
105
106
107
108
109
110 public String getMessage(final String key,
111 final Object value) {
112 return getMessage(key, new Object[] { value });
113 }
114
115
116
117
118
119
120
121
122
123 public String getMessage(final String key,
124 final Object value1,
125 final Object value2) {
126 return getMessage(key, new Object[] { value1, value2 });
127 }
128
129
130
131
132
133
134
135
136
137
138
139 public String getMessage(final String key,
140 final Object value1,
141 final Object value2,
142 final Object value3) {
143 return getMessage(key, new Object[] { value1, value2, value3 });
144 }
145
146
147
148
149
150
151
152
153 public String getMessage(final String key,
154 final Object[] values) {
155 final String msgFormatStr = bundle.getString(key);
156 final MessageFormat msgFormat = new MessageFormat(msgFormatStr);
157
158 return msgFormat.format(values);
159 }
160 }