1 package be
.nikiroo
.utils
.resources
;
4 import java
.io
.BufferedWriter
;
6 import java
.io
.FileInputStream
;
7 import java
.io
.FileOutputStream
;
8 import java
.io
.IOException
;
9 import java
.io
.InputStreamReader
;
10 import java
.io
.OutputStreamWriter
;
11 import java
.io
.Reader
;
12 import java
.io
.Writer
;
13 import java
.lang
.reflect
.Field
;
14 import java
.util
.ArrayList
;
15 import java
.util
.HashMap
;
16 import java
.util
.List
;
17 import java
.util
.Locale
;
19 import java
.util
.MissingResourceException
;
20 import java
.util
.PropertyResourceBundle
;
21 import java
.util
.ResourceBundle
;
24 * This class encapsulate a {@link ResourceBundle} in UTF-8. It allows to
25 * retrieve values associated to an enumeration, and allows some additional
28 * It also sports a writable change map, and you can save back the
29 * {@link Bundle} to file with {@link Bundle#updateFile(String)}.
34 * the enum to use to get values out of this class
36 public class Bundle
<E
extends Enum
<E
>> {
37 protected Class
<E
> type
;
38 protected Enum
<?
> name
;
39 private ResourceBundle map
;
40 private Map
<String
, String
> changeMap
;
43 * Create a new {@link Bundles} of the given name.
46 * a runtime instance of the class of E
49 * the name of the {@link Bundles}
51 protected Bundle(Class
<E
> type
, Enum
<?
> name
) {
54 this.changeMap
= new HashMap
<String
, String
>();
55 setBundle(name
, Locale
.getDefault());
59 * Return the value associated to the given id as a {@link String}.
62 * the id of the value to get
64 * @return the associated value, or NULL if not found (not present in the
67 public String
getString(E id
) {
68 return getStringX(id
, null);
72 * Set the value associated to the given id as a {@link String}.
75 * the id of the value to get
80 public void setString(E id
, String value
) {
81 setStringX(id
, null, value
);
85 * Return the value associated to the given id as a {@link String} suffixed
86 * with the runtime value "_suffix" (that is, "_" and suffix).
89 * the id of the value to get
93 * @return the associated value, or NULL if not found (not present in the
96 public String
getStringX(E id
, String suffix
) {
97 String key
= id
.name()
98 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
100 if (containsKey(key
)) {
101 return getString(key
).trim();
108 * Set the value associated to the given id as a {@link String} suffixed
109 * with the runtime value "_suffix" (that is, "_" and suffix).
112 * the id of the value to get
118 public void setStringX(E id
, String suffix
, String value
) {
119 String key
= id
.name()
120 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
122 setString(key
, value
);
126 * Return the value associated to the given id as a {@link Boolean}.
129 * the id of the value to get
131 * @return the associated value
133 public Boolean
getBoolean(E id
) {
134 String str
= getString(id
);
135 if (str
!= null && str
.length() > 0) {
136 if (str
.equalsIgnoreCase("true") || str
.equalsIgnoreCase("on")
137 || str
.equalsIgnoreCase("yes"))
139 if (str
.equalsIgnoreCase("false") || str
.equalsIgnoreCase("off")
140 || str
.equalsIgnoreCase("no"))
149 * Return the value associated to the given id as a {@link Boolean}.
152 * the id of the value to get
154 * the default value when it is not present in the config file or
155 * if it is not a boolean value
157 * @return the associated value
159 public boolean getBoolean(E id
, boolean def
) {
160 Boolean b
= getBoolean(id
);
168 * Return the value associated to the given id as an {@link Integer}.
171 * the id of the value to get
173 * @return the associated value
175 public Integer
getInteger(E id
) {
177 return Integer
.parseInt(getString(id
));
178 } catch (Exception e
) {
185 * Return the value associated to the given id as a {@link int}.
188 * the id of the value to get
190 * the default value when it is not present in the config file or
191 * if it is not a int value
193 * @return the associated value
195 public int getInteger(E id
, int def
) {
196 Integer i
= getInteger(id
);
204 * Return the value associated to the given id as a {@link Character}.
207 * the id of the value to get
209 * @return the associated value
211 public Character
getCharacter(E id
) {
212 String s
= getString(id
).trim();
213 if (s
.length() > 0) {
221 * Return the value associated to the given id as a {@link Character}.
224 * the id of the value to get
226 * the default value when it is not present in the config file or
227 * if it is not a char value
229 * @return the associated value
231 public char getCharacter(E id
, char def
) {
232 String s
= getString(id
).trim();
233 if (s
.length() > 0) {
241 * Return the value associated to the given id as a {@link Color}.
244 * id of the value to get
246 * @return the associated value
248 public Color
getColor(E id
) {
251 String bg
= getString(id
).trim();
252 if (bg
.startsWith("#") && (bg
.length() == 7 || bg
.length() == 9)) {
254 int r
= Integer
.parseInt(bg
.substring(1, 3), 16);
255 int g
= Integer
.parseInt(bg
.substring(3, 5), 16);
256 int b
= Integer
.parseInt(bg
.substring(5, 7), 16);
258 if (bg
.length() == 9) {
259 a
= Integer
.parseInt(bg
.substring(7, 9), 16);
261 color
= new Color(r
, g
, b
, a
);
262 } catch (NumberFormatException e
) {
263 color
= null; // no changes
271 * Set the value associated to the given id as a {@link Color}.
274 * id of the value to get
276 * @return the associated value
278 public void setColor(E id
, Color color
) {
279 String r
= Integer
.toString(color
.getRed(), 16);
280 String g
= Integer
.toString(color
.getGreen(), 16);
281 String b
= Integer
.toString(color
.getBlue(), 16);
283 if (color
.getAlpha() < 255) {
284 a
= Integer
.toString(color
.getAlpha(), 16);
287 setString(id
, "#" + r
+ g
+ b
+ a
);
291 * Create/update the .properties file.
293 * Will use the most likely candidate as base if the file does not already
294 * exists and this resource is translatable (for instance, "en_US" will use
295 * "en" as a base if the resource is a translation file).
298 * the path where the .properties files are
300 * @throws IOException
301 * in case of IO errors
303 public void updateFile(String path
) throws IOException
{
304 File file
= getUpdateFile(path
);
306 BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(
307 new FileOutputStream(file
), "UTF-8"));
313 for (Field field
: type
.getDeclaredFields()) {
314 Meta meta
= field
.getAnnotation(Meta
.class);
316 E id
= E
.valueOf(type
, field
.getName());
317 String info
= getMetaInfo(meta
);
324 writeValue(writer
, id
);
332 * Reload the {@link Bundle} data files.
334 public void reload() {
335 setBundle(name
, null);
339 * Check if the internal map contains the given key.
342 * the key to check for
344 * @return true if it does
346 protected boolean containsKey(String key
) {
347 if (changeMap
.containsKey(key
)) {
354 } catch (MissingResourceException e
) {
360 * Get the value for the given key if it exists in the internal map, or NULL
364 * the key to check for
366 * @return the value, or NULL
368 protected String
getString(String key
) {
369 if (changeMap
.containsKey(key
)) {
370 return changeMap
.get(key
);
373 if (containsKey(key
)) {
374 return map
.getString(key
);
381 * Set the value for this key, in the change map (it is kept in memory, not
387 * the associated value
389 protected void setString(String key
, String value
) {
390 changeMap
.put(key
, value
);
394 * Return formated, display-able information from the {@link Meta} field
395 * given. Each line will always starts with a "#" character.
398 * the {@link Meta} field
400 * @return the information to display or NULL if none
402 protected String
getMetaInfo(Meta meta
) {
403 String what
= meta
.what();
404 String where
= meta
.where();
405 String format
= meta
.format();
406 String info
= meta
.info();
408 int opt
= what
.length() + where
.length() + format
.length();
409 if (opt
+ info
.length() == 0)
412 StringBuilder builder
= new StringBuilder();
413 builder
.append("# ");
417 if (what
.length() > 0) {
418 builder
.append("WHAT: " + what
);
419 if (where
.length() + format
.length() > 0)
420 builder
.append(", ");
423 if (where
.length() > 0) {
424 builder
.append("WHERE: " + where
);
425 if (format
.length() > 0)
426 builder
.append(", ");
429 if (format
.length() > 0) {
430 builder
.append("FORMAT: " + format
);
434 if (info
.length() > 0) {
435 builder
.append("\n# ");
439 builder
.append(info
);
441 return builder
.toString();
445 * The display name used in the <tt>.properties file</tt>.
449 protected String
getBundleDisplayName() {
450 return name
.toString();
454 * Write the header found in the configuration <tt>.properties</tt> file of
455 * this {@link Bundles}.
458 * the {@link Writer} to write the header in
460 * @throws IOException
461 * in case of IO error
463 protected void writeHeader(Writer writer
) throws IOException
{
464 writer
.write("# " + getBundleDisplayName() + "\n");
469 * Write the given id to the config file, i.e., "MY_ID = my_curent_value"
470 * followed by a new line
473 * the {@link Writer} to write into
477 * @throws IOException
478 * in case of IO error
480 protected void writeValue(Writer writer
, E id
) throws IOException
{
481 writeValue(writer
, id
.name(), getString(id
));
485 * Write the given data to the config file, i.e., "MY_ID = my_curent_value"
486 * followed by a new line
489 * the {@link Writer} to write into
495 * @throws IOException
496 * in case of IO error
498 protected void writeValue(Writer writer
, String id
, String value
)
507 String
[] lines
= value
.replaceAll("\t", "\\\\\\t").split("\n");
508 for (int i
= 0; i
< lines
.length
; i
++) {
509 writer
.write(lines
[i
]);
510 if (i
< lines
.length
- 1) {
511 writer
.write("\\n\\");
518 * Return the source file for this {@link Bundles} from the given path.
521 * the path where the .properties files are
523 * @return the source {@link File}
525 * @throws IOException
526 * in case of IO errors
528 protected File
getUpdateFile(String path
) {
529 return new File(path
, name
.name() + ".properties");
533 * Change the currently used bundle, and reset all changes.
536 * the name of the bundle to load
538 * the {@link Locale} to use
540 protected void setBundle(Enum
<?
> name
, Locale locale
) {
543 String dir
= Bundles
.getDirectory();
547 File file
= getPropertyFile(dir
, name
.name(), locale
);
549 Reader reader
= new InputStreamReader(new FileInputStream(
551 map
= new PropertyResourceBundle(reader
);
553 } catch (IOException e
) {
559 map
= ResourceBundle
.getBundle(type
.getPackage().getName() + "."
560 + name
.name(), locale
, new FixedResourceBundleControl());
565 * Return the resource file that is closer to the {@link Locale}.
568 * the dirctory to look into
570 * the file basename (without <tt>.properties</tt>)
574 * @return the closest match or NULL if none
576 private File
getPropertyFile(String dir
, String name
, Locale locale
) {
577 List
<String
> locales
= new ArrayList
<String
>();
578 if (locale
!= null) {
579 String country
= locale
.getCountry() == null ?
"" : locale
581 String language
= locale
.getLanguage() == null ?
"" : locale
583 if (!language
.isEmpty() && !country
.isEmpty()) {
584 locales
.add("_" + language
+ "-" + country
);
586 if (!language
.isEmpty()) {
587 locales
.add("_" + language
);
594 for (String loc
: locales
) {
595 file
= new File(dir
, name
+ loc
+ ".properties");