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)}.
32 * the enum to use to get values out of this class
37 public class Bundle
<E
extends Enum
<E
>> {
39 protected Class
<E
> type
;
41 * The {@link Enum} associated to this {@link Bundle} (all the keys used in
42 * this {@link Bundle} will be of this type).
44 protected Enum
<?
> keyType
;
46 private TransBundle
<E
> descriptionBundle
;
49 private Map
<String
, String
> map
;
51 private Map
<String
, String
> changeMap
;
54 * Create a new {@link Bundles} of the given name.
57 * a runtime instance of the class of E
59 * the name of the {@link Bundles}
60 * @param descriptionBundle
61 * the description {@link TransBundle}, that is, a
62 * {@link TransBundle} dedicated to the description of the values
63 * of the given {@link Bundle} (can be NULL)
65 protected Bundle(Class
<E
> type
, Enum
<?
> name
,
66 TransBundle
<E
> descriptionBundle
) {
69 this.descriptionBundle
= descriptionBundle
;
71 this.map
= new HashMap
<String
, String
>();
72 this.changeMap
= new HashMap
<String
, String
>();
73 setBundle(name
, Locale
.getDefault(), false);
77 * Return the value associated to the given id as a {@link String}.
80 * the id of the value to get
82 * @return the associated value, or NULL if not found (not present in the
85 public String
getString(E id
) {
86 return getString(id
.name());
90 * Set the value associated to the given id as a {@link String}.
93 * the id of the value to get
98 public void setString(E id
, String value
) {
99 setString(id
.name(), value
);
103 * Return the value associated to the given id as a {@link String} suffixed
104 * with the runtime value "_suffix" (that is, "_" and suffix).
106 * Will only accept suffixes that form an existing id.
109 * the id of the value to get
113 * @return the associated value, or NULL if not found (not present in the
116 public String
getStringX(E id
, String suffix
) {
117 String key
= id
.name()
118 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
121 id
= Enum
.valueOf(type
, key
);
122 return getString(id
);
123 } catch (IllegalArgumentException e
) {
131 * Set the value associated to the given id as a {@link String} suffixed
132 * with the runtime value "_suffix" (that is, "_" and suffix).
134 * Will only accept suffixes that form an existing id.
137 * the id of the value to get
143 public void setStringX(E id
, String suffix
, String value
) {
144 String key
= id
.name()
145 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
148 id
= Enum
.valueOf(type
, key
);
149 setString(id
, value
);
150 } catch (IllegalArgumentException e
) {
156 * Return the value associated to the given id as a {@link Boolean}.
159 * the id of the value to get
161 * @return the associated value
163 public Boolean
getBoolean(E id
) {
164 String str
= getString(id
);
165 if (str
!= null && str
.length() > 0) {
166 if (str
.equalsIgnoreCase("true") || str
.equalsIgnoreCase("on")
167 || str
.equalsIgnoreCase("yes"))
169 if (str
.equalsIgnoreCase("false") || str
.equalsIgnoreCase("off")
170 || str
.equalsIgnoreCase("no"))
179 * Return the value associated to the given id as a {@link Boolean}.
182 * the id of the value to get
184 * the default value when it is not present in the config file or
185 * if it is not a boolean value
187 * @return the associated value
189 public boolean getBoolean(E id
, boolean def
) {
190 Boolean b
= getBoolean(id
);
198 * Return the value associated to the given id as an {@link Integer}.
201 * the id of the value to get
203 * @return the associated value
205 public Integer
getInteger(E id
) {
207 return Integer
.parseInt(getString(id
));
208 } catch (Exception e
) {
215 * Return the value associated to the given id as an int.
218 * the id of the value to get
220 * the default value when it is not present in the config file or
221 * if it is not a int value
223 * @return the associated value
225 public int getInteger(E id
, int def
) {
226 Integer i
= getInteger(id
);
234 * Return the value associated to the given id as a {@link Character}.
237 * the id of the value to get
239 * @return the associated value
241 public Character
getCharacter(E id
) {
242 String s
= getString(id
).trim();
243 if (s
.length() > 0) {
251 * Return the value associated to the given id as a {@link Character}.
254 * the id of the value to get
256 * the default value when it is not present in the config file or
257 * if it is not a char value
259 * @return the associated value
261 public char getCharacter(E id
, char def
) {
262 String s
= getString(id
).trim();
263 if (s
.length() > 0) {
271 * Return the value associated to the given id as a {@link Color}.
274 * the id of the value to get
276 * @return the associated value
278 public Color
getColor(E id
) {
281 String bg
= getString(id
).trim();
282 if (bg
.startsWith("#") && (bg
.length() == 7 || bg
.length() == 9)) {
284 int r
= Integer
.parseInt(bg
.substring(1, 3), 16);
285 int g
= Integer
.parseInt(bg
.substring(3, 5), 16);
286 int b
= Integer
.parseInt(bg
.substring(5, 7), 16);
288 if (bg
.length() == 9) {
289 a
= Integer
.parseInt(bg
.substring(7, 9), 16);
291 color
= new Color(r
, g
, b
, a
);
292 } catch (NumberFormatException e
) {
293 color
= null; // no changes
297 // Try by name if still not found
300 Field field
= Color
.class.getField(bg
);
301 color
= (Color
) field
.get(null);
302 } catch (Exception e
) {
311 * Set the value associated to the given id as a {@link Color}.
314 * the id of the value to set
318 public void setColor(E id
, Color color
) {
319 // Check for named colours first
321 Field
[] fields
= Color
.class.getFields();
322 for (Field field
: fields
) {
323 if (field
.equals(color
)) {
324 setString(id
, field
.getName());
328 } catch (Exception e
) {
332 String r
= Integer
.toString(color
.getRed(), 16);
333 String g
= Integer
.toString(color
.getGreen(), 16);
334 String b
= Integer
.toString(color
.getBlue(), 16);
336 if (color
.getAlpha() < 255) {
337 a
= Integer
.toString(color
.getAlpha(), 16);
340 setString(id
, "#" + r
+ g
+ b
+ a
);
344 * Create/update the .properties file.
346 * Will use the most likely candidate as base if the file does not already
347 * exists and this resource is translatable (for instance, "en_US" will use
348 * "en" as a base if the resource is a translation file).
350 * Will update the files in {@link Bundles#getDirectory()}; it <b>MUST</b>
353 * @throws IOException
354 * in case of IO errors
356 public void updateFile() throws IOException
{
357 updateFile(Bundles
.getDirectory());
361 * Create/update the .properties file.
363 * Will use the most likely candidate as base if the file does not already
364 * exists and this resource is translatable (for instance, "en_US" will use
365 * "en" as a base if the resource is a translation file).
368 * the path where the .properties files are, <b>MUST NOT</b> be
371 * @throws IOException
372 * in case of IO errors
374 public void updateFile(String path
) throws IOException
{
375 File file
= getUpdateFile(path
);
377 BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(
378 new FileOutputStream(file
), "UTF-8"));
384 for (Field field
: type
.getDeclaredFields()) {
385 Meta meta
= field
.getAnnotation(Meta
.class);
387 E id
= Enum
.valueOf(type
, field
.getName());
388 String info
= getMetaInfo(meta
);
395 writeValue(writer
, id
);
403 * The description {@link TransBundle}, that is, a {@link TransBundle}
404 * dedicated to the description of the values of the given {@link Bundle}
407 * @return the description {@link TransBundle}
409 public TransBundle
<E
> getDescriptionBundle() {
410 return descriptionBundle
;
414 * Reload the {@link Bundle} data files.
416 * @param resetToDefault
417 * reset to the default configuration (do not look into the
418 * possible user configuration files, only take the original
421 public void reload(boolean resetToDefault
) {
422 setBundle(keyType
, Locale
.getDefault(), resetToDefault
);
426 * Check if the internal map contains the given key.
429 * the key to check for
431 * @return true if it does
433 protected boolean containsKey(String key
) {
434 return changeMap
.containsKey(key
) || map
.containsKey(key
);
438 * Get the value for the given key if it exists in the internal map, or NULL
442 * the key to check for
444 * @return the value, or NULL
446 protected String
getString(String key
) {
447 if (changeMap
.containsKey(key
)) {
448 return changeMap
.get(key
);
451 if (map
.containsKey(key
)) {
459 * Set the value for this key, in the change map (it is kept in memory, not
465 * the associated value
467 protected void setString(String key
, String value
) {
468 changeMap
.put(key
, value
== null ?
null : value
.trim());
472 * Return formated, display-able information from the {@link Meta} field
473 * given. Each line will always starts with a "#" character.
476 * the {@link Meta} field
478 * @return the information to display or NULL if none
480 protected String
getMetaInfo(Meta meta
) {
481 String desc
= meta
.description();
482 boolean group
= meta
.group();
483 Meta
.Format format
= meta
.format();
484 String
[] list
= meta
.list();
485 boolean nullable
= meta
.nullable();
486 String info
= meta
.info();
487 boolean array
= meta
.array();
489 // Default, empty values -> NULL
490 if (desc
.length() + list
.length
+ info
.length() == 0 && !group
491 && nullable
&& format
== Meta
.Format
.STRING
) {
495 StringBuilder builder
= new StringBuilder();
496 builder
.append("# ").append(desc
);
497 if (desc
.length() > 20) {
498 builder
.append("\n#");
502 builder
.append("This item is used as a group, its content is not expected to be used.");
504 builder
.append(" (FORMAT: ").append(format
)
505 .append(nullable ?
"" : " (required)");
506 builder
.append(") ").append(info
);
508 if (list
.length
> 0) {
509 builder
.append("\n# ALLOWED VALUES:");
510 for (String value
: list
) {
511 builder
.append(" \"").append(value
).append("\"");
516 builder
.append("\n# (This item accept a list of comma-separated values)");
520 return builder
.toString();
524 * The display name used in the <tt>.properties file</tt>.
528 protected String
getBundleDisplayName() {
529 return keyType
.toString();
533 * Write the header found in the configuration <tt>.properties</tt> file of
534 * this {@link Bundles}.
537 * the {@link Writer} to write the header in
539 * @throws IOException
540 * in case of IO error
542 protected void writeHeader(Writer writer
) throws IOException
{
543 writer
.write("# " + getBundleDisplayName() + "\n");
548 * Write the given id to the config file, i.e., "MY_ID = my_curent_value"
549 * followed by a new line
552 * the {@link Writer} to write into
556 * @throws IOException
557 * in case of IO error
559 protected void writeValue(Writer writer
, E id
) throws IOException
{
560 writeValue(writer
, id
.name(), getString(id
));
564 * Write the given data to the config file, i.e., "MY_ID = my_curent_value"
565 * followed by a new line
568 * the {@link Writer} to write into
574 * @throws IOException
575 * in case of IO error
577 protected void writeValue(Writer writer
, String id
, String value
)
586 String
[] lines
= value
.replaceAll("\t", "\\\\\\t").split("\n");
587 for (int i
= 0; i
< lines
.length
; i
++) {
588 writer
.write(lines
[i
]);
589 if (i
< lines
.length
- 1) {
590 writer
.write("\\n\\");
597 * Return the source file for this {@link Bundles} from the given path.
600 * the path where the .properties files are
602 * @return the source {@link File}
604 protected File
getUpdateFile(String path
) {
605 return new File(path
, keyType
.name() + ".properties");
609 * Change the currently used bundle, and reset all changes.
612 * the name of the bundle to load
614 * the {@link Locale} to use
615 * @param resetToDefault
616 * reset to the default configuration (do not look into the
617 * possible user configuration files, only take the original
620 protected void setBundle(Enum
<?
> name
, Locale locale
, boolean resetToDefault
) {
622 String dir
= Bundles
.getDirectory();
624 boolean found
= false;
625 if (!resetToDefault
&& dir
!= null) {
627 File file
= getPropertyFile(dir
, name
.name(), locale
);
629 Reader reader
= new InputStreamReader(new FileInputStream(
631 resetMap(new PropertyResourceBundle(reader
));
634 } catch (IOException e
) {
640 String bname
= type
.getPackage().getName() + "." + name
.name();
642 resetMap(ResourceBundle
643 .getBundle(bname
, locale
, type
.getClassLoader(),
644 new FixedResourceBundleControl()));
645 } catch (Exception e
) {
646 // We have no bundle for this Bundle
647 System
.err
.println("No bundle found for: " + bname
);
654 * Reset the backing map to the content of the given bundle, or empty if
660 protected void resetMap(ResourceBundle bundle
) {
663 if (bundle
!= null) {
664 for (E field
: type
.getEnumConstants()) {
666 String value
= bundle
.getString(field
.name());
667 this.map
.put(field
.name(),
668 value
== null ?
null : value
.trim());
669 } catch (MissingResourceException e
) {
676 * Take a snapshot of the changes in memory in this {@link Bundle} made by
677 * the "set" methods ( {@link Bundle#setString(Enum, String)}...) at the
680 * @return a snapshot to use with {@link Bundle#restoreSnapshot(Object)}
682 public Object
takeSnapshot() {
683 return new HashMap
<String
, String
>(changeMap
);
687 * Restore a snapshot taken with {@link Bundle}, or reset the current
688 * changes if the snapshot is NULL.
691 * the snapshot or NULL
693 @SuppressWarnings("unchecked")
694 public void restoreSnapshot(Object snap
) {
698 if (snap
instanceof Map
) {
699 changeMap
= (Map
<String
, String
>) snap
;
702 "Restoring changes in a Bundle must be done on a changes snapshot, "
703 + "or NULL to discard current changes");
709 * Return the resource file that is closer to the {@link Locale}.
712 * the directory to look into
714 * the file base name (without <tt>.properties</tt>)
718 * @return the closest match or NULL if none
720 private File
getPropertyFile(String dir
, String name
, Locale locale
) {
721 List
<String
> locales
= new ArrayList
<String
>();
722 if (locale
!= null) {
723 String country
= locale
.getCountry() == null ?
"" : locale
725 String language
= locale
.getLanguage() == null ?
"" : locale
727 if (!language
.isEmpty() && !country
.isEmpty()) {
728 locales
.add("_" + language
+ "-" + country
);
730 if (!language
.isEmpty()) {
731 locales
.add("_" + language
);
738 for (String loc
: locales
) {
739 file
= new File(dir
, name
+ loc
+ ".properties");