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 * Check if the setting is set into this {@link Bundle}.
79 * the id of the setting to check
80 * @param includeDefaultValue
81 * TRUE to only return false when the setting is not set AND
82 * there is no default value
84 * @return TRUE if the setting is set
86 public boolean iSet(E id
, boolean includeDefaultValue
) {
87 if (getString(id
.toString(), null) == null) {
88 if (!includeDefaultValue
|| getString(id
) == null) {
97 * Return the value associated to the given id as a {@link String}.
100 * the id of the value to get
102 * @return the associated value, or NULL if not found (not present in the
105 public String
getString(E id
) {
106 return getString(id
, null);
110 * Return the value associated to the given id as a {@link String}.
112 * If no value is associated, take the default one if any.
115 * the id of the value to get
117 * the default value when it is not present in the config file
119 * @return the associated value, or NULL if not found (not present in the
122 public String
getString(E id
, String def
) {
123 String rep
= getString(id
.name(), null);
125 MetaInfo
<E
> info
= new MetaInfo
<E
>(type
, this, id
);
126 rep
= info
.getDefaultString();
137 * Set the value associated to the given id as a {@link String}.
140 * the id of the value to set
145 public void setString(E id
, String value
) {
146 setString(id
.name(), value
);
150 * Return the value associated to the given id as a {@link String} suffixed
151 * with the runtime value "_suffix" (that is, "_" and suffix).
153 * Will only accept suffixes that form an existing id.
155 * If no value is associated, take the default one if any.
158 * the id of the value to get
162 * @return the associated value, or NULL if not found (not present in the
165 public String
getStringX(E id
, String suffix
) {
166 String key
= id
.name()
167 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
170 id
= Enum
.valueOf(type
, key
);
171 return getString(id
);
172 } catch (IllegalArgumentException e
) {
180 * Set the value associated to the given id as a {@link String} suffixed
181 * with the runtime value "_suffix" (that is, "_" and suffix).
183 * Will only accept suffixes that form an existing id.
186 * the id of the value to set
192 public void setStringX(E id
, String suffix
, String value
) {
193 String key
= id
.name()
194 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
197 id
= Enum
.valueOf(type
, key
);
198 setString(id
, value
);
199 } catch (IllegalArgumentException e
) {
205 * Return the value associated to the given id as a {@link Boolean}.
207 * If no value is associated, take the default one if any.
210 * the id of the value to get
212 * @return the associated value
214 public Boolean
getBoolean(E id
) {
215 String str
= getString(id
);
216 return BundleHelper
.parseBoolean(str
);
220 * Return the value associated to the given id as a {@link Boolean}.
222 * If no value is associated, take the default one if any.
225 * the id of the value to get
227 * the default value when it is not present in the config file or
228 * if it is not a boolean value
230 * @return the associated value
232 public boolean getBoolean(E id
, boolean def
) {
233 Boolean b
= getBoolean(id
);
241 * Set the value associated to the given id as a {@link Boolean}.
244 * the id of the value to set
249 public void setBoolean(E id
, boolean value
) {
250 setString(id
.name(), BundleHelper
.fromBoolean(value
));
254 * Return the value associated to the given id as an {@link Integer}.
256 * If no value is associated, take the default one if any.
259 * the id of the value to get
261 * @return the associated value
263 public Integer
getInteger(E id
) {
264 return BundleHelper
.parseInteger(getString(id
));
268 * Return the value associated to the given id as an int.
270 * If no value is associated, take the default one if any.
273 * the id of the value to get
275 * the default value when it is not present in the config file or
276 * if it is not a int value
278 * @return the associated value
280 public int getInteger(E id
, int def
) {
281 Integer i
= getInteger(id
);
289 * Set the value associated to the given id as a {@link Integer}.
292 * the id of the value to set
297 public void setInteger(E id
, int value
) {
298 setString(id
.name(), BundleHelper
.fromInteger(value
));
302 * Return the value associated to the given id as a {@link Character}.
304 * If no value is associated, take the default one if any.
307 * the id of the value to get
309 * @return the associated value
311 public Character
getCharacter(E id
) {
312 return BundleHelper
.parseCharacter(getString(id
));
316 * Return the value associated to the given id as a {@link Character}.
318 * If no value is associated, take the default one if any.
321 * the id of the value to get
323 * the default value when it is not present in the config file or
324 * if it is not a char value
326 * @return the associated value
328 public char getCharacter(E id
, char def
) {
329 Character car
= getCharacter(id
);
337 * Return the value associated to the given id as a colour if it is found
340 * The returned value is an ARGB value.
342 * If no value is associated, take the default one if any.
345 * the id of the value to get
347 * @return the associated value
349 public Integer
getColor(E id
) {
350 return BundleHelper
.parseColor(getString(id
));
354 * Set the value associated to the given id as a colour.
356 * The value is a BGRA value.
359 * the id of the value to set
363 public void setColor(E id
, Integer color
) {
364 setString(id
, BundleHelper
.fromColor(color
));
368 * Return the value associated to the given id as a list of values if it is
369 * found and can be parsed.
371 * If no value is associated, take the default one if any.
374 * the id of the value to get
376 * @return the associated list, empty if the value is empty, NULL if it is
377 * not found or cannot be parsed as a list
379 public List
<String
> getList(E id
) {
380 return BundleHelper
.parseList(getString(id
));
384 * Set the value associated to the given id as a list of values.
387 * the id of the value to set
389 * the new list of values
391 public void setList(E id
, List
<String
> list
) {
392 setString(id
, BundleHelper
.fromList(list
));
396 * Create/update the .properties file.
398 * Will use the most likely candidate as base if the file does not already
399 * exists and this resource is translatable (for instance, "en_US" will use
400 * "en" as a base if the resource is a translation file).
402 * Will update the files in {@link Bundles#getDirectory()}; it <b>MUST</b>
405 * @throws IOException
406 * in case of IO errors
408 public void updateFile() throws IOException
{
409 updateFile(Bundles
.getDirectory());
413 * Create/update the .properties file.
415 * Will use the most likely candidate as base if the file does not already
416 * exists and this resource is translatable (for instance, "en_US" will use
417 * "en" as a base if the resource is a translation file).
420 * the path where the .properties files are, <b>MUST NOT</b> be
423 * @throws IOException
424 * in case of IO errors
426 public void updateFile(String path
) throws IOException
{
427 File file
= getUpdateFile(path
);
429 BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(
430 new FileOutputStream(file
), "UTF-8"));
436 for (Field field
: type
.getDeclaredFields()) {
437 Meta meta
= field
.getAnnotation(Meta
.class);
439 E id
= Enum
.valueOf(type
, field
.getName());
440 String info
= getMetaInfo(meta
);
447 writeValue(writer
, id
);
455 * Delete the .properties file.
457 * Will use the most likely candidate as base if the file does not already
458 * exists and this resource is translatable (for instance, "en_US" will use
459 * "en" as a base if the resource is a translation file).
461 * Will delete the files in {@link Bundles#getDirectory()}; it <b>MUST</b>
464 * @return TRUE if the file was deleted
466 public boolean deleteFile() {
467 return deleteFile(Bundles
.getDirectory());
471 * Delete the .properties file.
473 * Will use the most likely candidate as base if the file does not already
474 * exists and this resource is translatable (for instance, "en_US" will use
475 * "en" as a base if the resource is a translation file).
478 * the path where the .properties files are, <b>MUST NOT</b> be
481 * @return TRUE if the file was deleted
483 public boolean deleteFile(String path
) {
484 File file
= getUpdateFile(path
);
485 return file
.delete();
489 * The description {@link TransBundle}, that is, a {@link TransBundle}
490 * dedicated to the description of the values of the given {@link Bundle}
493 * @return the description {@link TransBundle}
495 public TransBundle
<E
> getDescriptionBundle() {
496 return descriptionBundle
;
500 * Reload the {@link Bundle} data files.
502 * @param resetToDefault
503 * reset to the default configuration (do not look into the
504 * possible user configuration files, only take the original
507 public void reload(boolean resetToDefault
) {
508 setBundle(keyType
, Locale
.getDefault(), resetToDefault
);
512 * Check if the internal map contains the given key.
515 * the key to check for
517 * @return true if it does
519 protected boolean containsKey(String key
) {
520 return changeMap
.containsKey(key
) || map
.containsKey(key
);
524 * Get the value for the given key if it exists in the internal map, or
525 * <tt>def</tt> if not.
528 * the key to check for
530 * the default value when it is not present in the internal map
532 * @return the value, or <tt>def</tt> if not found
534 protected String
getString(String key
, String def
) {
535 if (changeMap
.containsKey(key
)) {
536 return changeMap
.get(key
);
539 if (map
.containsKey(key
)) {
547 * Set the value for this key, in the change map (it is kept in memory, not
553 * the associated value
555 protected void setString(String key
, String value
) {
556 changeMap
.put(key
, value
== null ?
null : value
.trim());
560 * Return formated, display-able information from the {@link Meta} field
561 * given. Each line will always starts with a "#" character.
564 * the {@link Meta} field
566 * @return the information to display or NULL if none
568 protected String
getMetaInfo(Meta meta
) {
569 String desc
= meta
.description();
570 boolean group
= meta
.group();
571 Meta
.Format format
= meta
.format();
572 String
[] list
= meta
.list();
573 boolean nullable
= meta
.nullable();
574 String def
= meta
.def();
575 boolean array
= meta
.array();
577 // Default, empty values -> NULL
578 if (desc
.length() + list
.length
+ def
.length() == 0 && !group
579 && nullable
&& format
== Meta
.Format
.STRING
) {
583 StringBuilder builder
= new StringBuilder();
584 builder
.append("# ").append(desc
);
585 if (desc
.length() > 20) {
586 builder
.append("\n#");
590 builder
.append("This item is used as a group, its content is not expected to be used.");
592 builder
.append(" (FORMAT: ").append(format
)
593 .append(nullable ?
"" : " (required)");
594 builder
.append(") ");
596 if (list
.length
> 0) {
597 builder
.append("\n# ALLOWED VALUES:");
598 for (String value
: list
) {
599 builder
.append(" \"").append(value
).append("\"");
604 builder
.append("\n# (This item accept a list of comma-separated values)");
608 return builder
.toString();
612 * The display name used in the <tt>.properties file</tt>.
616 protected String
getBundleDisplayName() {
617 return keyType
.toString();
621 * Write the header found in the configuration <tt>.properties</tt> file of
622 * this {@link Bundles}.
625 * the {@link Writer} to write the header in
627 * @throws IOException
628 * in case of IO error
630 protected void writeHeader(Writer writer
) throws IOException
{
631 writer
.write("# " + getBundleDisplayName() + "\n");
636 * Write the given id to the config file, i.e., "MY_ID = my_curent_value"
637 * followed by a new line
640 * the {@link Writer} to write into
644 * @throws IOException
645 * in case of IO error
647 protected void writeValue(Writer writer
, E id
) throws IOException
{
648 writeValue(writer
, id
.name(), getString(id
));
652 * Write the given data to the config file, i.e., "MY_ID = my_curent_value"
653 * followed by a new line
656 * the {@link Writer} to write into
662 * @throws IOException
663 * in case of IO error
665 protected void writeValue(Writer writer
, String id
, String value
)
674 String
[] lines
= value
.replaceAll("\t", "\\\\\\t").split("\n");
675 for (int i
= 0; i
< lines
.length
; i
++) {
676 writer
.write(lines
[i
]);
677 if (i
< lines
.length
- 1) {
678 writer
.write("\\n\\");
685 * Return the source file for this {@link Bundles} from the given path.
688 * the path where the .properties files are
690 * @return the source {@link File}
692 protected File
getUpdateFile(String path
) {
693 return new File(path
, keyType
.name() + ".properties");
697 * Change the currently used bundle, and reset all changes.
700 * the name of the bundle to load
702 * the {@link Locale} to use
703 * @param resetToDefault
704 * reset to the default configuration (do not look into the
705 * possible user configuration files, only take the original
708 protected void setBundle(Enum
<?
> name
, Locale locale
, boolean resetToDefault
) {
710 String dir
= Bundles
.getDirectory();
711 String bname
= type
.getPackage().getName() + "." + name
.name();
713 boolean found
= false;
714 if (!resetToDefault
&& dir
!= null) {
715 // Look into Bundles.getDirectory() for .properties files
717 File file
= getPropertyFile(dir
, name
.name(), locale
);
719 Reader reader
= new InputStreamReader(new FileInputStream(
721 resetMap(new PropertyResourceBundle(reader
));
724 } catch (IOException e
) {
730 // Look into the package itself for resources
732 resetMap(ResourceBundle
733 .getBundle(bname
, locale
, type
.getClassLoader(),
734 new FixedResourceBundleControl()));
736 } catch (MissingResourceException e
) {
737 } catch (Exception e
) {
743 // We have no bundle for this Bundle
744 System
.err
.println("No bundle found for: " + bname
);
750 * Reset the backing map to the content of the given bundle, or with default
751 * valiues if bundle is NULL.
756 protected void resetMap(ResourceBundle bundle
) {
758 for (Field field
: type
.getDeclaredFields()) {
760 Meta meta
= field
.getAnnotation(Meta
.class);
762 E id
= Enum
.valueOf(type
, field
.getName());
765 if (bundle
!= null) {
766 value
= bundle
.getString(id
.name());
771 this.map
.put(id
.name(), value
== null ?
null : value
.trim());
773 } catch (MissingResourceException e
) {
779 * Take a snapshot of the changes in memory in this {@link Bundle} made by
780 * the "set" methods ( {@link Bundle#setString(Enum, String)}...) at the
783 * @return a snapshot to use with {@link Bundle#restoreSnapshot(Object)}
785 public Object
takeSnapshot() {
786 return new HashMap
<String
, String
>(changeMap
);
790 * Restore a snapshot taken with {@link Bundle}, or reset the current
791 * changes if the snapshot is NULL.
794 * the snapshot or NULL
796 @SuppressWarnings("unchecked")
797 public void restoreSnapshot(Object snap
) {
801 if (snap
instanceof Map
) {
802 changeMap
= (Map
<String
, String
>) snap
;
804 throw new RuntimeException(
805 "Restoring changes in a Bundle must be done on a changes snapshot, "
806 + "or NULL to discard current changes");
812 * Return the resource file that is closer to the {@link Locale}.
815 * the directory to look into
817 * the file base name (without <tt>.properties</tt>)
821 * @return the closest match or NULL if none
823 private File
getPropertyFile(String dir
, String name
, Locale locale
) {
824 List
<String
> locales
= new ArrayList
<String
>();
825 if (locale
!= null) {
826 String country
= locale
.getCountry() == null ?
"" : locale
828 String language
= locale
.getLanguage() == null ?
"" : locale
830 if (!language
.isEmpty() && !country
.isEmpty()) {
831 locales
.add("_" + language
+ "-" + country
);
833 if (!language
.isEmpty()) {
834 locales
.add("_" + language
);
841 for (String loc
: locales
) {
842 file
= new File(dir
, name
+ loc
+ ".properties");