1 package be
.nikiroo
.utils
.resources
;
3 import java
.io
.BufferedWriter
;
5 import java
.io
.FileInputStream
;
6 import java
.io
.FileOutputStream
;
7 import java
.io
.IOException
;
8 import java
.io
.InputStreamReader
;
9 import java
.io
.OutputStreamWriter
;
10 import java
.io
.Reader
;
11 import java
.io
.Writer
;
12 import java
.lang
.reflect
.Field
;
13 import java
.util
.ArrayList
;
14 import java
.util
.HashMap
;
15 import java
.util
.List
;
16 import java
.util
.Locale
;
18 import java
.util
.MissingResourceException
;
19 import java
.util
.PropertyResourceBundle
;
20 import java
.util
.ResourceBundle
;
23 * This class encapsulate a {@link ResourceBundle} in UTF-8. It allows to
24 * retrieve values associated to an enumeration, and allows some additional
27 * It also sports a writable change map, and you can save back the
28 * {@link Bundle} to file with {@link Bundle#updateFile(String)}.
31 * the enum to use to get values out of this class
36 public class Bundle
<E
extends Enum
<E
>> {
38 protected Class
<E
> type
;
40 * The {@link Enum} associated to this {@link Bundle} (all the keys used in
41 * this {@link Bundle} will be of this type).
43 protected Enum
<?
> keyType
;
45 private TransBundle
<E
> descriptionBundle
;
48 private Map
<String
, String
> map
;
50 private Map
<String
, String
> changeMap
;
53 * Create a new {@link Bundles} of the given name.
56 * a runtime instance of the class of E
58 * the name of the {@link Bundles}
59 * @param descriptionBundle
60 * the description {@link TransBundle}, that is, a
61 * {@link TransBundle} dedicated to the description of the values
62 * of the given {@link Bundle} (can be NULL)
64 protected Bundle(Class
<E
> type
, Enum
<?
> name
,
65 TransBundle
<E
> descriptionBundle
) {
68 this.descriptionBundle
= descriptionBundle
;
70 this.map
= new HashMap
<String
, String
>();
71 this.changeMap
= new HashMap
<String
, String
>();
72 setBundle(name
, Locale
.getDefault(), false);
76 * Return the value associated to the given id as a {@link String}.
79 * the id of the value to get
81 * @return the associated value, or NULL if not found (not present in the
84 public String
getString(E id
) {
85 return getString(id
.name());
89 * Set the value associated to the given id as a {@link String}.
92 * the id of the value to set
97 public void setString(E id
, String value
) {
98 setString(id
.name(), value
);
102 * Return the value associated to the given id as a {@link String} suffixed
103 * with the runtime value "_suffix" (that is, "_" and suffix).
105 * Will only accept suffixes that form an existing id.
108 * the id of the value to get
112 * @return the associated value, or NULL if not found (not present in the
115 public String
getStringX(E id
, String suffix
) {
116 String key
= id
.name()
117 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
120 id
= Enum
.valueOf(type
, key
);
121 return getString(id
);
122 } catch (IllegalArgumentException e
) {
130 * Set the value associated to the given id as a {@link String} suffixed
131 * with the runtime value "_suffix" (that is, "_" and suffix).
133 * Will only accept suffixes that form an existing id.
136 * the id of the value to set
142 public void setStringX(E id
, String suffix
, String value
) {
143 String key
= id
.name()
144 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
147 id
= Enum
.valueOf(type
, key
);
148 setString(id
, value
);
149 } catch (IllegalArgumentException e
) {
155 * Return the value associated to the given id as a {@link Boolean}.
158 * the id of the value to get
160 * @return the associated value
162 public Boolean
getBoolean(E id
) {
163 String str
= getString(id
);
164 return BundleHelper
.parseBoolean(str
);
168 * Return the value associated to the given id as a {@link Boolean}.
171 * the id of the value to get
173 * the default value when it is not present in the config file or
174 * if it is not a boolean value
176 * @return the associated value
178 public boolean getBoolean(E id
, boolean def
) {
179 Boolean b
= getBoolean(id
);
187 * Set the value associated to the given id as a {@link Boolean}.
190 * the id of the value to set
195 public void setBoolean(E id
, boolean value
) {
196 setString(id
.name(), BundleHelper
.fromBoolean(value
));
201 * Return the value associated to the given id as an {@link Integer}.
204 * the id of the value to get
206 * @return the associated value
208 public Integer
getInteger(E id
) {
209 return BundleHelper
.parseInteger(getString(id
));
213 * Return the value associated to the given id as an int.
216 * the id of the value to get
218 * the default value when it is not present in the config file or
219 * if it is not a int value
221 * @return the associated value
223 public int getInteger(E id
, int def
) {
224 Integer i
= getInteger(id
);
232 * Set the value associated to the given id as a {@link Integer}.
235 * the id of the value to set
240 public void setInteger(E id
, int value
) {
241 setString(id
.name(), BundleHelper
.fromInteger(value
));
245 * Return the value associated to the given id as a {@link Character}.
248 * the id of the value to get
250 * @return the associated value
252 public Character
getCharacter(E id
) {
253 return BundleHelper
.parseCharacter(getString(id
));
257 * Return the value associated to the given id as a {@link Character}.
260 * the id of the value to get
262 * the default value when it is not present in the config file or
263 * if it is not a char value
265 * @return the associated value
267 public char getCharacter(E id
, char def
) {
268 Character car
= getCharacter(id
);
276 * Return the value associated to the given id as a colour if it is found
279 * The returned value is an ARGB value.
282 * the id of the value to get
284 * @return the associated value
286 public Integer
getColor(E id
) {
287 return BundleHelper
.parseColor(getString(id
));
291 * Set the value associated to the given id as a colour.
293 * The value is a BGRA value.
296 * the id of the value to set
300 public void setColor(E id
, Integer color
) {
301 setString(id
, BundleHelper
.fromColor(color
));
305 * Return the value associated to the given id as a list of values if it is
306 * found and can be parsed.
309 * the id of the value to get
311 * @return the associated list, empty if the value is empty, NULL if it is
312 * not found or cannot be parsed as a list
314 public List
<String
> getList(E id
) {
315 return BundleHelper
.parseList(getString(id
));
319 * Set the value associated to the given id as a list of values.
322 * the id of the value to set
324 * the new list of values
326 public void setList(E id
, List
<String
> list
) {
327 setString(id
, BundleHelper
.fromList(list
));
331 * Create/update the .properties file.
333 * Will use the most likely candidate as base if the file does not already
334 * exists and this resource is translatable (for instance, "en_US" will use
335 * "en" as a base if the resource is a translation file).
337 * Will update the files in {@link Bundles#getDirectory()}; it <b>MUST</b>
340 * @throws IOException
341 * in case of IO errors
343 public void updateFile() throws IOException
{
344 updateFile(Bundles
.getDirectory());
348 * Create/update the .properties file.
350 * Will use the most likely candidate as base if the file does not already
351 * exists and this resource is translatable (for instance, "en_US" will use
352 * "en" as a base if the resource is a translation file).
355 * the path where the .properties files are, <b>MUST NOT</b> be
358 * @throws IOException
359 * in case of IO errors
361 public void updateFile(String path
) throws IOException
{
362 File file
= getUpdateFile(path
);
364 BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(
365 new FileOutputStream(file
), "UTF-8"));
371 for (Field field
: type
.getDeclaredFields()) {
372 Meta meta
= field
.getAnnotation(Meta
.class);
374 E id
= Enum
.valueOf(type
, field
.getName());
375 String info
= getMetaInfo(meta
);
382 writeValue(writer
, id
);
390 * Delete the .properties file.
392 * Will use the most likely candidate as base if the file does not already
393 * exists and this resource is translatable (for instance, "en_US" will use
394 * "en" as a base if the resource is a translation file).
396 * Will delete the files in {@link Bundles#getDirectory()}; it <b>MUST</b>
399 * @return TRUE if the file was deleted
401 public boolean deleteFile() {
402 return deleteFile(Bundles
.getDirectory());
406 * Delete the .properties file.
408 * Will use the most likely candidate as base if the file does not already
409 * exists and this resource is translatable (for instance, "en_US" will use
410 * "en" as a base if the resource is a translation file).
413 * the path where the .properties files are, <b>MUST NOT</b> be
416 * @return TRUE if the file was deleted
418 public boolean deleteFile(String path
) {
419 File file
= getUpdateFile(path
);
420 return file
.delete();
424 * The description {@link TransBundle}, that is, a {@link TransBundle}
425 * dedicated to the description of the values of the given {@link Bundle}
428 * @return the description {@link TransBundle}
430 public TransBundle
<E
> getDescriptionBundle() {
431 return descriptionBundle
;
435 * Reload the {@link Bundle} data files.
437 * @param resetToDefault
438 * reset to the default configuration (do not look into the
439 * possible user configuration files, only take the original
442 public void reload(boolean resetToDefault
) {
443 setBundle(keyType
, Locale
.getDefault(), resetToDefault
);
447 * Check if the internal map contains the given key.
450 * the key to check for
452 * @return true if it does
454 protected boolean containsKey(String key
) {
455 return changeMap
.containsKey(key
) || map
.containsKey(key
);
459 * Get the value for the given key if it exists in the internal map, or NULL
463 * the key to check for
465 * @return the value, or NULL
467 protected String
getString(String key
) {
468 if (changeMap
.containsKey(key
)) {
469 return changeMap
.get(key
);
472 if (map
.containsKey(key
)) {
480 * Set the value for this key, in the change map (it is kept in memory, not
486 * the associated value
488 protected void setString(String key
, String value
) {
489 changeMap
.put(key
, value
== null ?
null : value
.trim());
493 * Return formated, display-able information from the {@link Meta} field
494 * given. Each line will always starts with a "#" character.
497 * the {@link Meta} field
499 * @return the information to display or NULL if none
501 protected String
getMetaInfo(Meta meta
) {
502 String desc
= meta
.description();
503 boolean group
= meta
.group();
504 Meta
.Format format
= meta
.format();
505 String
[] list
= meta
.list();
506 boolean nullable
= meta
.nullable();
507 String def
= meta
.def();
508 String info
= meta
.info();
509 boolean array
= meta
.array();
511 // Default, empty values -> NULL
512 if (desc
.length() + list
.length
+ info
.length() + def
.length() == 0
513 && !group
&& nullable
&& format
== Meta
.Format
.STRING
) {
517 StringBuilder builder
= new StringBuilder();
518 builder
.append("# ").append(desc
);
519 if (desc
.length() > 20) {
520 builder
.append("\n#");
524 builder
.append("This item is used as a group, its content is not expected to be used.");
526 builder
.append(" (FORMAT: ").append(format
)
527 .append(nullable ?
"" : " (required)");
528 builder
.append(") ").append(info
);
530 if (list
.length
> 0) {
531 builder
.append("\n# ALLOWED VALUES:");
532 for (String value
: list
) {
533 builder
.append(" \"").append(value
).append("\"");
538 builder
.append("\n# (This item accept a list of comma-separated values)");
542 return builder
.toString();
546 * The display name used in the <tt>.properties file</tt>.
550 protected String
getBundleDisplayName() {
551 return keyType
.toString();
555 * Write the header found in the configuration <tt>.properties</tt> file of
556 * this {@link Bundles}.
559 * the {@link Writer} to write the header in
561 * @throws IOException
562 * in case of IO error
564 protected void writeHeader(Writer writer
) throws IOException
{
565 writer
.write("# " + getBundleDisplayName() + "\n");
570 * Write the given id to the config file, i.e., "MY_ID = my_curent_value"
571 * followed by a new line
574 * the {@link Writer} to write into
578 * @throws IOException
579 * in case of IO error
581 protected void writeValue(Writer writer
, E id
) throws IOException
{
582 writeValue(writer
, id
.name(), getString(id
));
586 * Write the given data to the config file, i.e., "MY_ID = my_curent_value"
587 * followed by a new line
590 * the {@link Writer} to write into
596 * @throws IOException
597 * in case of IO error
599 protected void writeValue(Writer writer
, String id
, String value
)
608 String
[] lines
= value
.replaceAll("\t", "\\\\\\t").split("\n");
609 for (int i
= 0; i
< lines
.length
; i
++) {
610 writer
.write(lines
[i
]);
611 if (i
< lines
.length
- 1) {
612 writer
.write("\\n\\");
619 * Return the source file for this {@link Bundles} from the given path.
622 * the path where the .properties files are
624 * @return the source {@link File}
626 protected File
getUpdateFile(String path
) {
627 return new File(path
, keyType
.name() + ".properties");
631 * Change the currently used bundle, and reset all changes.
634 * the name of the bundle to load
636 * the {@link Locale} to use
637 * @param resetToDefault
638 * reset to the default configuration (do not look into the
639 * possible user configuration files, only take the original
642 protected void setBundle(Enum
<?
> name
, Locale locale
, boolean resetToDefault
) {
644 String dir
= Bundles
.getDirectory();
645 String bname
= type
.getPackage().getName() + "." + name
.name();
647 boolean found
= false;
648 if (!resetToDefault
&& dir
!= null) {
649 // Look into Bundles.getDirectory() for .properties files
651 File file
= getPropertyFile(dir
, name
.name(), locale
);
653 Reader reader
= new InputStreamReader(new FileInputStream(
655 resetMap(new PropertyResourceBundle(reader
));
658 } catch (IOException e
) {
664 // Look into the package itself for resources
666 resetMap(ResourceBundle
667 .getBundle(bname
, locale
, type
.getClassLoader(),
668 new FixedResourceBundleControl()));
670 } catch (MissingResourceException e
) {
671 } catch (Exception e
) {
677 // We have no bundle for this Bundle
678 System
.err
.println("No bundle found for: " + bname
);
684 * Reset the backing map to the content of the given bundle, or with default
685 * valiues if bundle is NULL.
690 protected void resetMap(ResourceBundle bundle
) {
692 for (Field field
: type
.getDeclaredFields()) {
694 Meta meta
= field
.getAnnotation(Meta
.class);
696 E id
= Enum
.valueOf(type
, field
.getName());
699 if (bundle
!= null) {
700 value
= bundle
.getString(id
.name());
705 this.map
.put(id
.name(), value
== null ?
null : value
.trim());
707 } catch (MissingResourceException e
) {
713 * Take a snapshot of the changes in memory in this {@link Bundle} made by
714 * the "set" methods ( {@link Bundle#setString(Enum, String)}...) at the
717 * @return a snapshot to use with {@link Bundle#restoreSnapshot(Object)}
719 public Object
takeSnapshot() {
720 return new HashMap
<String
, String
>(changeMap
);
724 * Restore a snapshot taken with {@link Bundle}, or reset the current
725 * changes if the snapshot is NULL.
728 * the snapshot or NULL
730 @SuppressWarnings("unchecked")
731 public void restoreSnapshot(Object snap
) {
735 if (snap
instanceof Map
) {
736 changeMap
= (Map
<String
, String
>) snap
;
738 throw new RuntimeException(
739 "Restoring changes in a Bundle must be done on a changes snapshot, "
740 + "or NULL to discard current changes");
746 * Return the resource file that is closer to the {@link Locale}.
749 * the directory to look into
751 * the file base name (without <tt>.properties</tt>)
755 * @return the closest match or NULL if none
757 private File
getPropertyFile(String dir
, String name
, Locale locale
) {
758 List
<String
> locales
= new ArrayList
<String
>();
759 if (locale
!= null) {
760 String country
= locale
.getCountry() == null ?
"" : locale
762 String language
= locale
.getLanguage() == null ?
"" : locale
764 if (!language
.isEmpty() && !country
.isEmpty()) {
765 locales
.add("_" + language
+ "-" + country
);
767 if (!language
.isEmpty()) {
768 locales
.add("_" + language
);
775 for (String loc
: locales
) {
776 file
= new File(dir
, name
+ loc
+ ".properties");