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(), false);
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 * @param resetToDefault
335 * reset to the default configuration (do not look into the
336 * possible user configuration files, only take the original
339 public void reload(boolean resetToDefault
) {
340 setBundle(name
, null, resetToDefault
);
344 * Check if the internal map contains the given key.
347 * the key to check for
349 * @return true if it does
351 protected boolean containsKey(String key
) {
352 if (changeMap
.containsKey(key
)) {
360 } catch (MissingResourceException e
) {
368 * Get the value for the given key if it exists in the internal map, or NULL
372 * the key to check for
374 * @return the value, or NULL
376 protected String
getString(String key
) {
377 if (changeMap
.containsKey(key
)) {
378 return changeMap
.get(key
);
381 if (map
!= null && containsKey(key
)) {
382 return map
.getString(key
);
389 * Set the value for this key, in the change map (it is kept in memory, not
395 * the associated value
397 protected void setString(String key
, String value
) {
398 changeMap
.put(key
, value
);
402 * Return formated, display-able information from the {@link Meta} field
403 * given. Each line will always starts with a "#" character.
406 * the {@link Meta} field
408 * @return the information to display or NULL if none
410 protected String
getMetaInfo(Meta meta
) {
411 String what
= meta
.what();
412 String where
= meta
.where();
413 String format
= meta
.format();
414 String info
= meta
.info();
416 int opt
= what
.length() + where
.length() + format
.length();
417 if (opt
+ info
.length() == 0)
420 StringBuilder builder
= new StringBuilder();
421 builder
.append("# ");
425 if (what
.length() > 0) {
426 builder
.append("WHAT: " + what
);
427 if (where
.length() + format
.length() > 0)
428 builder
.append(", ");
431 if (where
.length() > 0) {
432 builder
.append("WHERE: " + where
);
433 if (format
.length() > 0)
434 builder
.append(", ");
437 if (format
.length() > 0) {
438 builder
.append("FORMAT: " + format
);
442 if (info
.length() > 0) {
443 builder
.append("\n# ");
447 builder
.append(info
);
449 return builder
.toString();
453 * The display name used in the <tt>.properties file</tt>.
457 protected String
getBundleDisplayName() {
458 return name
.toString();
462 * Write the header found in the configuration <tt>.properties</tt> file of
463 * this {@link Bundles}.
466 * the {@link Writer} to write the header in
468 * @throws IOException
469 * in case of IO error
471 protected void writeHeader(Writer writer
) throws IOException
{
472 writer
.write("# " + getBundleDisplayName() + "\n");
477 * Write the given id to the config file, i.e., "MY_ID = my_curent_value"
478 * followed by a new line
481 * the {@link Writer} to write into
485 * @throws IOException
486 * in case of IO error
488 protected void writeValue(Writer writer
, E id
) throws IOException
{
489 writeValue(writer
, id
.name(), getString(id
));
493 * Write the given data to the config file, i.e., "MY_ID = my_curent_value"
494 * followed by a new line
497 * the {@link Writer} to write into
503 * @throws IOException
504 * in case of IO error
506 protected void writeValue(Writer writer
, String id
, String value
)
515 String
[] lines
= value
.replaceAll("\t", "\\\\\\t").split("\n");
516 for (int i
= 0; i
< lines
.length
; i
++) {
517 writer
.write(lines
[i
]);
518 if (i
< lines
.length
- 1) {
519 writer
.write("\\n\\");
526 * Return the source file for this {@link Bundles} from the given path.
529 * the path where the .properties files are
531 * @return the source {@link File}
533 * @throws IOException
534 * in case of IO errors
536 protected File
getUpdateFile(String path
) {
537 return new File(path
, name
.name() + ".properties");
541 * Change the currently used bundle, and reset all changes.
544 * the name of the bundle to load
546 * the {@link Locale} to use
547 * @param resetToDefault
548 * reset to the default configuration (do not look into the
549 * possible user configuration files, only take the original
552 protected void setBundle(Enum
<?
> name
, Locale locale
, boolean resetToDefault
) {
555 String dir
= Bundles
.getDirectory();
557 if (!resetToDefault
&& dir
!= null) {
559 File file
= getPropertyFile(dir
, name
.name(), locale
);
561 Reader reader
= new InputStreamReader(new FileInputStream(
563 map
= new PropertyResourceBundle(reader
);
565 } catch (IOException e
) {
572 map
= ResourceBundle
.getBundle(type
.getPackage().getName()
573 + "." + name
.name(), locale
,
574 new FixedResourceBundleControl());
575 } catch (Exception e
) {
576 // We have no bundle for this Bundle
583 * Take a snapshot of the changes in memory in this {@link Bundle} made by
584 * the "set" methods ( {@link Bundle#setString(Enum, String)}...) at the
587 * @return a snapshot to use with {@link Bundle#restoreChanges(Object)}
589 protected Object
takeChangesSnapshot() {
590 return new HashMap
<String
, String
>(changeMap
);
594 * Restore a snapshot taken with {@link Bundle}, or reset the current
595 * changes if the snapshot is NULL.
598 * the snapshot or NULL
600 @SuppressWarnings("unchecked")
601 protected void restoreChanges(Object snap
) {
605 if (snap
instanceof Map
) {
606 changeMap
= (Map
<String
, String
>) snap
;
609 "Restoring changes in a Bundle must be done on a changes snapshot, "
610 + "or NULL to discard current changes");
616 * Return the resource file that is closer to the {@link Locale}.
619 * the dirctory to look into
621 * the file basename (without <tt>.properties</tt>)
625 * @return the closest match or NULL if none
627 private File
getPropertyFile(String dir
, String name
, Locale locale
) {
628 List
<String
> locales
= new ArrayList
<String
>();
629 if (locale
!= null) {
630 String country
= locale
.getCountry() == null ?
"" : locale
632 String language
= locale
.getLanguage() == null ?
"" : locale
634 if (!language
.isEmpty() && !country
.isEmpty()) {
635 locales
.add("_" + language
+ "-" + country
);
637 if (!language
.isEmpty()) {
638 locales
.add("_" + language
);
645 for (String loc
: locales
) {
646 file
= new File(dir
, name
+ loc
+ ".properties");