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
;
22 import be
.nikiroo
.utils
.resources
.Meta
.Format
;
25 * This class encapsulate a {@link ResourceBundle} in UTF-8. It allows to
26 * retrieve values associated to an enumeration, and allows some additional
29 * It also sports a writable change map, and you can save back the
30 * {@link Bundle} to file with {@link Bundle#updateFile(String)}.
33 * the enum to use to get values out of this class
38 public class Bundle
<E
extends Enum
<E
>> {
40 protected Class
<E
> type
;
42 * The {@link Enum} associated to this {@link Bundle} (all the keys used in
43 * this {@link Bundle} will be of this type).
45 protected Enum
<?
> keyType
;
47 private TransBundle
<E
> descriptionBundle
;
50 private Map
<String
, String
> map
;
52 private Map
<String
, String
> changeMap
;
55 * Create a new {@link Bundles} of the given name.
58 * a runtime instance of the class of E
60 * the name of the {@link Bundles}
61 * @param descriptionBundle
62 * the description {@link TransBundle}, that is, a
63 * {@link TransBundle} dedicated to the description of the values
64 * of the given {@link Bundle} (can be NULL)
66 protected Bundle(Class
<E
> type
, Enum
<?
> name
,
67 TransBundle
<E
> descriptionBundle
) {
70 this.descriptionBundle
= descriptionBundle
;
72 this.map
= new HashMap
<String
, String
>();
73 this.changeMap
= new HashMap
<String
, String
>();
74 setBundle(name
, Locale
.getDefault(), false);
78 * Check if the setting is set into this {@link Bundle}.
81 * the id of the setting to check
82 * @param includeDefaultValue
83 * TRUE to only return false when the setting is not set AND
84 * there is no default value
86 * @return TRUE if the setting is set
88 public boolean isSet(E id
, boolean includeDefaultValue
) {
89 return isSet(id
.name(), includeDefaultValue
);
93 * Check if the setting is set into this {@link Bundle}.
96 * the id of the setting to check
97 * @param includeDefaultValue
98 * TRUE to only return false when the setting is not set AND
99 * there is no default value
101 * @return TRUE if the setting is set
103 protected boolean isSet(String name
, boolean includeDefaultValue
) {
104 if (getString(name
, null) == null) {
105 if (!includeDefaultValue
|| getString(name
, "") == null) {
114 * Return the value associated to the given id as a {@link String}.
117 * the id of the value to get
119 * @return the associated value, or NULL if not found (not present in the
122 public String
getString(E id
) {
123 return getString(id
, null);
127 * Return the value associated to the given id as a {@link String}.
129 * If no value is associated, take the default one if any.
132 * the id of the value to get
134 * the default value when it is not present in the config file
136 * @return the associated value, or NULL if not found (not present in the
139 public String
getString(E id
, String def
) {
140 String rep
= getString(id
.name(), null);
143 Meta meta
= type
.getDeclaredField(id
.name()).getAnnotation(
146 } catch (NoSuchFieldException e
) {
147 } catch (SecurityException e
) {
159 * Set the value associated to the given id as a {@link String}.
162 * the id of the value to set
167 public void setString(E id
, String value
) {
168 setString(id
.name(), value
);
172 * Return the value associated to the given id as a {@link String} suffixed
173 * with the runtime value "_suffix" (that is, "_" and suffix).
175 * Will only accept suffixes that form an existing id.
177 * If no value is associated, take the default one if any.
180 * the id of the value to get
184 * @return the associated value, or NULL if not found (not present in the
187 public String
getStringX(E id
, String suffix
) {
188 String key
= id
.name()
189 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
192 id
= Enum
.valueOf(type
, key
);
193 return getString(id
);
194 } catch (IllegalArgumentException e
) {
202 * Set the value associated to the given id as a {@link String} suffixed
203 * with the runtime value "_suffix" (that is, "_" and suffix).
205 * Will only accept suffixes that form an existing id.
208 * the id of the value to set
214 public void setStringX(E id
, String suffix
, String value
) {
215 String key
= id
.name()
216 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
219 id
= Enum
.valueOf(type
, key
);
220 setString(id
, value
);
221 } catch (IllegalArgumentException e
) {
227 * Return the value associated to the given id as a {@link Boolean}.
229 * If no value is associated, take the default one if any.
232 * the id of the value to get
234 * @return the associated value
236 public Boolean
getBoolean(E id
) {
237 String str
= getString(id
);
238 return BundleHelper
.parseBoolean(str
);
242 * Return the value associated to the given id as a {@link Boolean}.
244 * If no value is associated, take the default one if any.
247 * the id of the value to get
249 * the default value when it is not present in the config file or
250 * if it is not a boolean value
252 * @return the associated value
254 public boolean getBoolean(E id
, boolean def
) {
255 Boolean b
= getBoolean(id
);
263 * Set the value associated to the given id as a {@link Boolean}.
266 * the id of the value to set
271 public void setBoolean(E id
, boolean value
) {
272 setString(id
.name(), BundleHelper
.fromBoolean(value
));
276 * Return the value associated to the given id as an {@link Integer}.
278 * If no value is associated, take the default one if any.
281 * the id of the value to get
283 * @return the associated value
285 public Integer
getInteger(E id
) {
286 return BundleHelper
.parseInteger(getString(id
));
290 * Return the value associated to the given id as an int.
292 * If no value is associated, take the default one if any.
295 * the id of the value to get
297 * the default value when it is not present in the config file or
298 * if it is not a int value
300 * @return the associated value
302 public int getInteger(E id
, int def
) {
303 Integer i
= getInteger(id
);
311 * Set the value associated to the given id as a {@link Integer}.
314 * the id of the value to set
319 public void setInteger(E id
, int value
) {
320 setString(id
.name(), BundleHelper
.fromInteger(value
));
324 * Return the value associated to the given id as a {@link Character}.
326 * If no value is associated, take the default one if any.
329 * the id of the value to get
331 * @return the associated value
333 public Character
getCharacter(E id
) {
334 return BundleHelper
.parseCharacter(getString(id
));
338 * Return the value associated to the given id as a {@link Character}.
340 * If no value is associated, take the default one if any.
343 * the id of the value to get
345 * the default value when it is not present in the config file or
346 * if it is not a char value
348 * @return the associated value
350 public char getCharacter(E id
, char def
) {
351 Character car
= getCharacter(id
);
359 * Return the value associated to the given id as a colour if it is found
362 * The returned value is an ARGB value.
364 * If no value is associated, take the default one if any.
367 * the id of the value to get
369 * @return the associated value
371 public Integer
getColor(E id
) {
372 return BundleHelper
.parseColor(getString(id
));
376 * Set the value associated to the given id as a colour.
378 * The value is a BGRA value.
381 * the id of the value to set
385 public void setColor(E id
, Integer color
) {
386 setString(id
, BundleHelper
.fromColor(color
));
390 * Return the value associated to the given id as a list of values if it is
391 * found and can be parsed.
393 * If no value is associated, take the default one if any.
396 * the id of the value to get
398 * @return the associated list, empty if the value is empty, NULL if it is
399 * not found or cannot be parsed as a list
401 public List
<String
> getList(E id
) {
402 return BundleHelper
.parseList(getString(id
));
406 * Set the value associated to the given id as a list of values.
409 * the id of the value to set
411 * the new list of values
413 public void setList(E id
, List
<String
> list
) {
414 setString(id
, BundleHelper
.fromList(list
));
418 * Create/update the .properties file.
420 * Will use the most likely candidate as base if the file does not already
421 * exists and this resource is translatable (for instance, "en_US" will use
422 * "en" as a base if the resource is a translation file).
424 * Will update the files in {@link Bundles#getDirectory()}; it <b>MUST</b>
427 * @throws IOException
428 * in case of IO errors
430 public void updateFile() throws IOException
{
431 updateFile(Bundles
.getDirectory());
435 * Create/update the .properties file.
437 * Will use the most likely candidate as base if the file does not already
438 * exists and this resource is translatable (for instance, "en_US" will use
439 * "en" as a base if the resource is a translation file).
442 * the path where the .properties files are, <b>MUST NOT</b> be
445 * @throws IOException
446 * in case of IO errors
448 public void updateFile(String path
) throws IOException
{
449 File file
= getUpdateFile(path
);
451 BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(
452 new FileOutputStream(file
), "UTF-8"));
458 for (Field field
: type
.getDeclaredFields()) {
459 Meta meta
= field
.getAnnotation(Meta
.class);
461 E id
= Enum
.valueOf(type
, field
.getName());
462 String info
= getMetaInfo(meta
);
469 writeValue(writer
, id
);
477 * Delete the .properties file.
479 * Will use the most likely candidate as base if the file does not already
480 * exists and this resource is translatable (for instance, "en_US" will use
481 * "en" as a base if the resource is a translation file).
483 * Will delete the files in {@link Bundles#getDirectory()}; it <b>MUST</b>
486 * @return TRUE if the file was deleted
488 public boolean deleteFile() {
489 return deleteFile(Bundles
.getDirectory());
493 * Delete the .properties file.
495 * Will use the most likely candidate as base if the file does not already
496 * exists and this resource is translatable (for instance, "en_US" will use
497 * "en" as a base if the resource is a translation file).
500 * the path where the .properties files are, <b>MUST NOT</b> be
503 * @return TRUE if the file was deleted
505 public boolean deleteFile(String path
) {
506 File file
= getUpdateFile(path
);
507 return file
.delete();
511 * The description {@link TransBundle}, that is, a {@link TransBundle}
512 * dedicated to the description of the values of the given {@link Bundle}
515 * @return the description {@link TransBundle}
517 public TransBundle
<E
> getDescriptionBundle() {
518 return descriptionBundle
;
522 * Reload the {@link Bundle} data files.
524 * @param resetToDefault
525 * reset to the default configuration (do not look into the
526 * possible user configuration files, only take the original
529 public void reload(boolean resetToDefault
) {
530 setBundle(keyType
, Locale
.getDefault(), resetToDefault
);
534 * Check if the internal map contains the given key.
537 * the key to check for
539 * @return true if it does
541 protected boolean containsKey(String key
) {
542 return changeMap
.containsKey(key
) || map
.containsKey(key
);
546 * Get the value for the given key if it exists in the internal map, or
547 * <tt>def</tt> if not.
550 * the key to check for
552 * the default value when it is not present in the internal map
554 * @return the value, or <tt>def</tt> if not found
556 protected String
getString(String key
, String def
) {
557 if (changeMap
.containsKey(key
)) {
558 return changeMap
.get(key
);
561 if (map
.containsKey(key
)) {
569 * Set the value for this key, in the change map (it is kept in memory, not
575 * the associated value
577 protected void setString(String key
, String value
) {
578 changeMap
.put(key
, value
== null ?
null : value
.trim());
582 * Return formated, display-able information from the {@link Meta} field
583 * given. Each line will always starts with a "#" character.
586 * the {@link Meta} field
588 * @return the information to display or NULL if none
590 protected String
getMetaInfo(Meta meta
) {
591 String desc
= meta
.description();
592 boolean group
= meta
.group();
593 Meta
.Format format
= meta
.format();
594 String
[] list
= meta
.list();
595 boolean nullable
= meta
.nullable();
596 String def
= meta
.def();
597 boolean array
= meta
.array();
599 // Default, empty values -> NULL
600 if (desc
.length() + list
.length
+ def
.length() == 0 && !group
601 && nullable
&& format
== Format
.STRING
) {
605 StringBuilder builder
= new StringBuilder();
606 for (String line
: desc
.split("\n")) {
607 builder
.append("# ").append(line
).append("\n");
611 builder
.append("# This item is used as a group, its content is not expected to be used.");
613 builder
.append("# (FORMAT: ").append(format
)
614 .append(nullable ?
"" : ", required");
615 builder
.append(") ");
617 if (list
.length
> 0) {
618 builder
.append("\n# ALLOWED VALUES: ");
619 boolean first
= true;
620 for (String value
: list
) {
622 builder
.append(", ");
624 builder
.append(BundleHelper
.escape(value
));
630 builder
.append("\n# (This item accepts a list of escaped comma-separated values)");
634 return builder
.toString();
638 * The display name used in the <tt>.properties file</tt>.
642 protected String
getBundleDisplayName() {
643 return keyType
.toString();
647 * Write the header found in the configuration <tt>.properties</tt> file of
648 * this {@link Bundles}.
651 * the {@link Writer} to write the header in
653 * @throws IOException
654 * in case of IO error
656 protected void writeHeader(Writer writer
) throws IOException
{
657 writer
.write("# " + getBundleDisplayName() + "\n");
662 * Write the given data to the config file, i.e., "MY_ID = my_curent_value"
663 * followed by a new line.
665 * Will prepend a # sign if the is is not set (see
666 * {@link Bundle#isSet(Enum, boolean)}).
669 * the {@link Writer} to write into
673 * @throws IOException
674 * in case of IO error
676 protected void writeValue(Writer writer
, E id
) throws IOException
{
677 boolean set
= isSet(id
, false);
678 writeValue(writer
, id
.name(), getString(id
), set
);
682 * Write the given data to the config file, i.e., "MY_ID = my_curent_value"
683 * followed by a new line.
685 * Will prepend a # sign if the is is not set.
688 * the {@link Writer} to write into
694 * the value is set in this {@link Bundle}
696 * @throws IOException
697 * in case of IO error
699 protected void writeValue(Writer writer
, String id
, String value
,
700 boolean set
) throws IOException
{
713 String
[] lines
= value
.replaceAll("\t", "\\\\\\t").split("\n");
714 for (int i
= 0; i
< lines
.length
; i
++) {
715 writer
.write(lines
[i
]);
716 if (i
< lines
.length
- 1) {
717 writer
.write("\\n\\");
724 * Return the source file for this {@link Bundles} from the given path.
727 * the path where the .properties files are
729 * @return the source {@link File}
731 protected File
getUpdateFile(String path
) {
732 return new File(path
, keyType
.name() + ".properties");
736 * Change the currently used bundle, and reset all changes.
739 * the name of the bundle to load
741 * the {@link Locale} to use
742 * @param resetToDefault
743 * reset to the default configuration (do not look into the
744 * possible user configuration files, only take the original
747 protected void setBundle(Enum
<?
> name
, Locale locale
, boolean resetToDefault
) {
749 String dir
= Bundles
.getDirectory();
750 String bname
= type
.getPackage().getName() + "." + name
.name();
752 boolean found
= false;
753 if (!resetToDefault
&& dir
!= null) {
754 // Look into Bundles.getDirectory() for .properties files
756 File file
= getPropertyFile(dir
, name
.name(), locale
);
758 Reader reader
= new InputStreamReader(new FileInputStream(
760 resetMap(new PropertyResourceBundle(reader
));
763 } catch (IOException e
) {
769 // Look into the package itself for resources
771 resetMap(ResourceBundle
772 .getBundle(bname
, locale
, type
.getClassLoader(),
773 new FixedResourceBundleControl()));
775 } catch (MissingResourceException e
) {
776 } catch (Exception e
) {
782 // We have no bundle for this Bundle
783 System
.err
.println("No bundle found for: " + bname
);
789 * Reset the backing map to the content of the given bundle, or with default
790 * values if bundle is NULL.
795 protected void resetMap(ResourceBundle bundle
) {
797 for (Field field
: type
.getDeclaredFields()) {
799 Meta meta
= field
.getAnnotation(Meta
.class);
801 E id
= Enum
.valueOf(type
, field
.getName());
804 if (bundle
!= null) {
805 value
= bundle
.getString(id
.name());
810 this.map
.put(id
.name(), value
== null ?
null : value
.trim());
812 } catch (MissingResourceException e
) {
818 * Take a snapshot of the changes in memory in this {@link Bundle} made by
819 * the "set" methods ( {@link Bundle#setString(Enum, String)}...) at the
822 * @return a snapshot to use with {@link Bundle#restoreSnapshot(Object)}
824 public Object
takeSnapshot() {
825 return new HashMap
<String
, String
>(changeMap
);
829 * Restore a snapshot taken with {@link Bundle}, or reset the current
830 * changes if the snapshot is NULL.
833 * the snapshot or NULL
835 @SuppressWarnings("unchecked")
836 public void restoreSnapshot(Object snap
) {
840 if (snap
instanceof Map
) {
841 changeMap
= (Map
<String
, String
>) snap
;
843 throw new RuntimeException(
844 "Restoring changes in a Bundle must be done on a changes snapshot, "
845 + "or NULL to discard current changes");
851 * Return the resource file that is closer to the {@link Locale}.
854 * the directory to look into
856 * the file base name (without <tt>.properties</tt>)
860 * @return the closest match or NULL if none
862 private File
getPropertyFile(String dir
, String name
, Locale locale
) {
863 List
<String
> locales
= new ArrayList
<String
>();
864 if (locale
!= null) {
865 String country
= locale
.getCountry() == null ?
"" : locale
867 String language
= locale
.getLanguage() == null ?
"" : locale
869 if (!language
.isEmpty() && !country
.isEmpty()) {
870 locales
.add("_" + language
+ "-" + country
);
872 if (!language
.isEmpty()) {
873 locales
.add("_" + language
);
880 for (String loc
: locales
) {
881 file
= new File(dir
, name
+ loc
+ ".properties");