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 get
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 get
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 if (str
!= null && str
.length() > 0) {
165 if (str
.equalsIgnoreCase("true") || str
.equalsIgnoreCase("on")
166 || str
.equalsIgnoreCase("yes"))
168 if (str
.equalsIgnoreCase("false") || str
.equalsIgnoreCase("off")
169 || str
.equalsIgnoreCase("no"))
178 * Return the value associated to the given id as a {@link Boolean}.
181 * the id of the value to get
183 * the default value when it is not present in the config file or
184 * if it is not a boolean value
186 * @return the associated value
188 public boolean getBoolean(E id
, boolean def
) {
189 Boolean b
= getBoolean(id
);
197 * Return the value associated to the given id as an {@link Integer}.
200 * the id of the value to get
202 * @return the associated value
204 public Integer
getInteger(E id
) {
206 return Integer
.parseInt(getString(id
));
207 } catch (Exception e
) {
214 * Return the value associated to the given id as an int.
217 * the id of the value to get
219 * the default value when it is not present in the config file or
220 * if it is not a int value
222 * @return the associated value
224 public int getInteger(E id
, int def
) {
225 Integer i
= getInteger(id
);
233 * Return the value associated to the given id as a {@link Character}.
236 * the id of the value to get
238 * @return the associated value
240 public Character
getCharacter(E id
) {
241 String s
= getString(id
).trim();
242 if (s
.length() > 0) {
250 * Return the value associated to the given id as a {@link Character}.
253 * the id of the value to get
255 * the default value when it is not present in the config file or
256 * if it is not a char value
258 * @return the associated value
260 public char getCharacter(E id
, char def
) {
261 String s
= getString(id
);
262 if (s
!= null && s
.length() > 0) {
263 return s
.trim().charAt(0);
270 * Return the value associated to the given id as a colour if it is found
273 * The returned value is an ARGB value.
276 * the id of the value to get
278 * @return the associated value
280 public Integer
getColor(E id
) {
283 String bg
= getString(id
).trim();
285 int r
= 0, g
= 0, b
= 0, a
= -1;
286 if (bg
.startsWith("#") && (bg
.length() == 7 || bg
.length() == 9)) {
288 r
= Integer
.parseInt(bg
.substring(1, 3), 16);
289 g
= Integer
.parseInt(bg
.substring(3, 5), 16);
290 b
= Integer
.parseInt(bg
.substring(5, 7), 16);
291 if (bg
.length() == 9) {
292 a
= Integer
.parseInt(bg
.substring(7, 9), 16);
297 } catch (NumberFormatException e
) {
302 // Try by name if still not found
304 if ("black".equalsIgnoreCase(bg
)) {
309 } else if ("white".equalsIgnoreCase(bg
)) {
314 } else if ("red".equalsIgnoreCase(bg
)) {
319 } else if ("green".equalsIgnoreCase(bg
)) {
324 } else if ("blue".equalsIgnoreCase(bg
)) {
329 } else if ("grey".equalsIgnoreCase(bg
)
330 || "gray".equalsIgnoreCase(bg
)) {
335 } else if ("cyan".equalsIgnoreCase(bg
)) {
340 } else if ("magenta".equalsIgnoreCase(bg
)) {
345 } else if ("yellow".equalsIgnoreCase(bg
)) {
354 rep
= ((a
& 0xFF) << 24) //
355 | ((r
& 0xFF) << 16) //
356 | ((g
& 0xFF) << 8) //
364 * Set the value associated to the given id as a colour.
366 * The value is an BGRA value.
369 * the id of the value to set
373 public void setColor(E id
, Integer color
) {
374 int a
= (color
>> 24) & 0xFF;
375 int r
= (color
>> 16) & 0xFF;
376 int g
= (color
>> 8) & 0xFF;
377 int b
= (color
>> 0) & 0xFF;
379 String rs
= Integer
.toString(r
, 16);
380 String gs
= Integer
.toString(g
, 16);
381 String bs
= Integer
.toString(b
, 16);
384 as
= Integer
.toString(a
, 16);
387 setString(id
, "#" + rs
+ gs
+ bs
+ as
);
391 * Return the value associated to the given id as a list of values if it is
392 * found and can be parsed.
395 * the id of the value to get
397 * @return the associated list, empty if the value is empty, NULL if it is
398 * not found or cannot be parsed as a list
400 public List
<String
> getList(E id
) {
401 List
<String
> list
= new ArrayList
<String
>();
402 String raw
= getString(id
);
404 boolean inQuote
= false;
405 boolean prevIsBackSlash
= false;
406 StringBuilder builder
= new StringBuilder();
407 for (int i
= 0; i
< raw
.length(); i
++) {
408 char car
= raw
.charAt(i
);
410 if (prevIsBackSlash
) {
412 prevIsBackSlash
= false;
417 list
.add(builder
.toString());
418 builder
.setLength(0);
424 prevIsBackSlash
= true;
438 // continue to default
451 if (inQuote
|| prevIsBackSlash
) {
456 } catch (Exception e
) {
464 * Set the value associated to the given id as a list of values.
467 * the id of the value to set
469 * the new list of values
471 public void setList(E id
, List
<String
> list
) {
472 StringBuilder builder
= new StringBuilder();
473 for (String item
: list
) {
474 if (builder
.length() > 0) {
475 builder
.append(", ");
477 builder
.append('"')//
478 .append(item
.replace("\\", "\\\\").replace("\"", "\\\""))//
482 setString(id
, builder
.toString());
486 * Create/update the .properties file.
488 * Will use the most likely candidate as base if the file does not already
489 * exists and this resource is translatable (for instance, "en_US" will use
490 * "en" as a base if the resource is a translation file).
492 * Will update the files in {@link Bundles#getDirectory()}; it <b>MUST</b>
495 * @throws IOException
496 * in case of IO errors
498 public void updateFile() throws IOException
{
499 updateFile(Bundles
.getDirectory());
503 * Create/update the .properties file.
505 * Will use the most likely candidate as base if the file does not already
506 * exists and this resource is translatable (for instance, "en_US" will use
507 * "en" as a base if the resource is a translation file).
510 * the path where the .properties files are, <b>MUST NOT</b> be
513 * @throws IOException
514 * in case of IO errors
516 public void updateFile(String path
) throws IOException
{
517 File file
= getUpdateFile(path
);
519 BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(
520 new FileOutputStream(file
), "UTF-8"));
526 for (Field field
: type
.getDeclaredFields()) {
527 Meta meta
= field
.getAnnotation(Meta
.class);
529 E id
= Enum
.valueOf(type
, field
.getName());
530 String info
= getMetaInfo(meta
);
537 writeValue(writer
, id
);
545 * Delete the .properties file.
547 * Will use the most likely candidate as base if the file does not already
548 * exists and this resource is translatable (for instance, "en_US" will use
549 * "en" as a base if the resource is a translation file).
551 * Will delete the files in {@link Bundles#getDirectory()}; it <b>MUST</b>
554 * @return TRUE if the file was deleted
556 public boolean deleteFile() {
557 return deleteFile(Bundles
.getDirectory());
561 * Delete the .properties file.
563 * Will use the most likely candidate as base if the file does not already
564 * exists and this resource is translatable (for instance, "en_US" will use
565 * "en" as a base if the resource is a translation file).
568 * the path where the .properties files are, <b>MUST NOT</b> be
571 * @return TRUE if the file was deleted
573 public boolean deleteFile(String path
) {
574 File file
= getUpdateFile(path
);
575 return file
.delete();
579 * The description {@link TransBundle}, that is, a {@link TransBundle}
580 * dedicated to the description of the values of the given {@link Bundle}
583 * @return the description {@link TransBundle}
585 public TransBundle
<E
> getDescriptionBundle() {
586 return descriptionBundle
;
590 * Reload the {@link Bundle} data files.
592 * @param resetToDefault
593 * reset to the default configuration (do not look into the
594 * possible user configuration files, only take the original
597 public void reload(boolean resetToDefault
) {
598 setBundle(keyType
, Locale
.getDefault(), resetToDefault
);
602 * Check if the internal map contains the given key.
605 * the key to check for
607 * @return true if it does
609 protected boolean containsKey(String key
) {
610 return changeMap
.containsKey(key
) || map
.containsKey(key
);
614 * Get the value for the given key if it exists in the internal map, or NULL
618 * the key to check for
620 * @return the value, or NULL
622 protected String
getString(String key
) {
623 if (changeMap
.containsKey(key
)) {
624 return changeMap
.get(key
);
627 if (map
.containsKey(key
)) {
635 * Set the value for this key, in the change map (it is kept in memory, not
641 * the associated value
643 protected void setString(String key
, String value
) {
644 changeMap
.put(key
, value
== null ?
null : value
.trim());
648 * Return formated, display-able information from the {@link Meta} field
649 * given. Each line will always starts with a "#" character.
652 * the {@link Meta} field
654 * @return the information to display or NULL if none
656 protected String
getMetaInfo(Meta meta
) {
657 String desc
= meta
.description();
658 boolean group
= meta
.group();
659 Meta
.Format format
= meta
.format();
660 String
[] list
= meta
.list();
661 boolean nullable
= meta
.nullable();
662 String def
= meta
.def();
663 String info
= meta
.info();
664 boolean array
= meta
.array();
666 // Default, empty values -> NULL
667 if (desc
.length() + list
.length
+ info
.length() + def
.length() == 0
668 && !group
&& nullable
&& format
== Meta
.Format
.STRING
) {
672 StringBuilder builder
= new StringBuilder();
673 builder
.append("# ").append(desc
);
674 if (desc
.length() > 20) {
675 builder
.append("\n#");
679 builder
.append("This item is used as a group, its content is not expected to be used.");
681 builder
.append(" (FORMAT: ").append(format
)
682 .append(nullable ?
"" : " (required)");
683 builder
.append(") ").append(info
);
685 if (list
.length
> 0) {
686 builder
.append("\n# ALLOWED VALUES:");
687 for (String value
: list
) {
688 builder
.append(" \"").append(value
).append("\"");
693 builder
.append("\n# (This item accept a list of comma-separated values)");
697 return builder
.toString();
701 * The display name used in the <tt>.properties file</tt>.
705 protected String
getBundleDisplayName() {
706 return keyType
.toString();
710 * Write the header found in the configuration <tt>.properties</tt> file of
711 * this {@link Bundles}.
714 * the {@link Writer} to write the header in
716 * @throws IOException
717 * in case of IO error
719 protected void writeHeader(Writer writer
) throws IOException
{
720 writer
.write("# " + getBundleDisplayName() + "\n");
725 * Write the given id to the config file, i.e., "MY_ID = my_curent_value"
726 * followed by a new line
729 * the {@link Writer} to write into
733 * @throws IOException
734 * in case of IO error
736 protected void writeValue(Writer writer
, E id
) throws IOException
{
737 writeValue(writer
, id
.name(), getString(id
));
741 * Write the given data to the config file, i.e., "MY_ID = my_curent_value"
742 * followed by a new line
745 * the {@link Writer} to write into
751 * @throws IOException
752 * in case of IO error
754 protected void writeValue(Writer writer
, String id
, String value
)
763 String
[] lines
= value
.replaceAll("\t", "\\\\\\t").split("\n");
764 for (int i
= 0; i
< lines
.length
; i
++) {
765 writer
.write(lines
[i
]);
766 if (i
< lines
.length
- 1) {
767 writer
.write("\\n\\");
774 * Return the source file for this {@link Bundles} from the given path.
777 * the path where the .properties files are
779 * @return the source {@link File}
781 protected File
getUpdateFile(String path
) {
782 return new File(path
, keyType
.name() + ".properties");
786 * Change the currently used bundle, and reset all changes.
789 * the name of the bundle to load
791 * the {@link Locale} to use
792 * @param resetToDefault
793 * reset to the default configuration (do not look into the
794 * possible user configuration files, only take the original
797 protected void setBundle(Enum
<?
> name
, Locale locale
, boolean resetToDefault
) {
799 String dir
= Bundles
.getDirectory();
800 String bname
= type
.getPackage().getName() + "." + name
.name();
802 boolean found
= false;
803 if (!resetToDefault
&& dir
!= null) {
804 // Look into Bundles.getDirectory() for .properties files
806 File file
= getPropertyFile(dir
, name
.name(), locale
);
808 Reader reader
= new InputStreamReader(new FileInputStream(
810 resetMap(new PropertyResourceBundle(reader
));
813 } catch (IOException e
) {
819 // Look into the package itself for resources
821 resetMap(ResourceBundle
822 .getBundle(bname
, locale
, type
.getClassLoader(),
823 new FixedResourceBundleControl()));
825 } catch (MissingResourceException e
) {
826 } catch (Exception e
) {
832 // We have no bundle for this Bundle
833 System
.err
.println("No bundle found for: " + bname
);
839 * Reset the backing map to the content of the given bundle, or with default
840 * valiues if bundle is NULL.
845 protected void resetMap(ResourceBundle bundle
) {
847 for (Field field
: type
.getDeclaredFields()) {
849 Meta meta
= field
.getAnnotation(Meta
.class);
851 E id
= Enum
.valueOf(type
, field
.getName());
854 if (bundle
!= null) {
855 value
= bundle
.getString(id
.name());
860 this.map
.put(id
.name(), value
== null ?
null : value
.trim());
862 } catch (MissingResourceException e
) {
868 * Take a snapshot of the changes in memory in this {@link Bundle} made by
869 * the "set" methods ( {@link Bundle#setString(Enum, String)}...) at the
872 * @return a snapshot to use with {@link Bundle#restoreSnapshot(Object)}
874 public Object
takeSnapshot() {
875 return new HashMap
<String
, String
>(changeMap
);
879 * Restore a snapshot taken with {@link Bundle}, or reset the current
880 * changes if the snapshot is NULL.
883 * the snapshot or NULL
885 @SuppressWarnings("unchecked")
886 public void restoreSnapshot(Object snap
) {
890 if (snap
instanceof Map
) {
891 changeMap
= (Map
<String
, String
>) snap
;
893 throw new RuntimeException(
894 "Restoring changes in a Bundle must be done on a changes snapshot, "
895 + "or NULL to discard current changes");
901 * Return the resource file that is closer to the {@link Locale}.
904 * the directory to look into
906 * the file base name (without <tt>.properties</tt>)
910 * @return the closest match or NULL if none
912 private File
getPropertyFile(String dir
, String name
, Locale locale
) {
913 List
<String
> locales
= new ArrayList
<String
>();
914 if (locale
!= null) {
915 String country
= locale
.getCountry() == null ?
"" : locale
917 String language
= locale
.getLanguage() == null ?
"" : locale
919 if (!language
.isEmpty() && !country
.isEmpty()) {
920 locales
.add("_" + language
+ "-" + country
);
922 if (!language
.isEmpty()) {
923 locales
.add("_" + language
);
930 for (String loc
: locales
) {
931 file
= new File(dir
, name
+ loc
+ ".properties");