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)}.
34 * the enum to use to get values out of this class
36 public class Bundle
<E
extends Enum
<E
>> {
37 protected Class
<E
> type
;
38 protected Enum
<?
> name
;
39 private Map
<String
, String
> map
; // R/O map
40 private Map
<String
, String
> changeMap
; // R/W map
43 * Create a new {@link Bundles} of the given name.
46 * a runtime instance of the class of E
49 * the name of the {@link Bundles}
51 protected Bundle(Class
<E
> type
, Enum
<?
> name
) {
54 this.map
= new HashMap
<String
, String
>();
55 this.changeMap
= new HashMap
<String
, String
>();
56 setBundle(name
, Locale
.getDefault(), false);
60 * Return the value associated to the given id as a {@link String}.
63 * the id of the value to get
65 * @return the associated value, or NULL if not found (not present in the
68 public String
getString(E id
) {
69 return getString(id
.name());
73 * Set the value associated to the given id as a {@link String}.
76 * the id of the value to get
81 public void setString(E id
, String value
) {
82 setString(id
.name(), value
);
86 * Return the value associated to the given id as a {@link String} suffixed
87 * with the runtime value "_suffix" (that is, "_" and suffix).
89 * Will only accept suffixes that form an existing id.
92 * the id of the value to get
96 * @return the associated value, or NULL if not found (not present in the
99 public String
getStringX(E id
, String suffix
) {
100 String key
= id
.name()
101 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
104 id
= Enum
.valueOf(type
, key
);
105 return getString(id
);
106 } catch (IllegalArgumentException e
) {
114 * Set the value associated to the given id as a {@link String} suffixed
115 * with the runtime value "_suffix" (that is, "_" and suffix).
117 * Will only accept suffixes that form an existing id.
120 * the id of the value to get
126 public void setStringX(E id
, String suffix
, String value
) {
127 String key
= id
.name()
128 + (suffix
== null ?
"" : "_" + suffix
.toUpperCase());
131 id
= Enum
.valueOf(type
, key
);
132 setString(id
, value
);
133 } catch (IllegalArgumentException e
) {
139 * Return the value associated to the given id as a {@link Boolean}.
142 * the id of the value to get
144 * @return the associated value
146 public Boolean
getBoolean(E id
) {
147 String str
= getString(id
);
148 if (str
!= null && str
.length() > 0) {
149 if (str
.equalsIgnoreCase("true") || str
.equalsIgnoreCase("on")
150 || str
.equalsIgnoreCase("yes"))
152 if (str
.equalsIgnoreCase("false") || str
.equalsIgnoreCase("off")
153 || str
.equalsIgnoreCase("no"))
162 * Return the value associated to the given id as a {@link Boolean}.
165 * the id of the value to get
167 * the default value when it is not present in the config file or
168 * if it is not a boolean value
170 * @return the associated value
172 public boolean getBoolean(E id
, boolean def
) {
173 Boolean b
= getBoolean(id
);
181 * Return the value associated to the given id as an {@link Integer}.
184 * the id of the value to get
186 * @return the associated value
188 public Integer
getInteger(E id
) {
190 return Integer
.parseInt(getString(id
));
191 } catch (Exception e
) {
198 * Return the value associated to the given id as a {@link int}.
201 * the id of the value to get
203 * the default value when it is not present in the config file or
204 * if it is not a int value
206 * @return the associated value
208 public int getInteger(E id
, int def
) {
209 Integer i
= getInteger(id
);
217 * Return the value associated to the given id as a {@link Character}.
220 * the id of the value to get
222 * @return the associated value
224 public Character
getCharacter(E id
) {
225 String s
= getString(id
).trim();
226 if (s
.length() > 0) {
234 * Return the value associated to the given id as a {@link Character}.
237 * the id of the value to get
239 * the default value when it is not present in the config file or
240 * if it is not a char value
242 * @return the associated value
244 public char getCharacter(E id
, char def
) {
245 String s
= getString(id
).trim();
246 if (s
.length() > 0) {
254 * Return the value associated to the given id as a {@link Color}.
257 * id of the value to get
259 * @return the associated value
261 public Color
getColor(E id
) {
264 String bg
= getString(id
).trim();
265 if (bg
.startsWith("#") && (bg
.length() == 7 || bg
.length() == 9)) {
267 int r
= Integer
.parseInt(bg
.substring(1, 3), 16);
268 int g
= Integer
.parseInt(bg
.substring(3, 5), 16);
269 int b
= Integer
.parseInt(bg
.substring(5, 7), 16);
271 if (bg
.length() == 9) {
272 a
= Integer
.parseInt(bg
.substring(7, 9), 16);
274 color
= new Color(r
, g
, b
, a
);
275 } catch (NumberFormatException e
) {
276 color
= null; // no changes
284 * Set the value associated to the given id as a {@link Color}.
287 * id of the value to get
289 * @return the associated value
291 public void setColor(E id
, Color color
) {
292 String r
= Integer
.toString(color
.getRed(), 16);
293 String g
= Integer
.toString(color
.getGreen(), 16);
294 String b
= Integer
.toString(color
.getBlue(), 16);
296 if (color
.getAlpha() < 255) {
297 a
= Integer
.toString(color
.getAlpha(), 16);
300 setString(id
, "#" + r
+ g
+ b
+ a
);
304 * Create/update the .properties file.
306 * Will use the most likely candidate as base if the file does not already
307 * exists and this resource is translatable (for instance, "en_US" will use
308 * "en" as a base if the resource is a translation file).
310 * Will update the files in {@link Bundles#getDirectory()}; it <b>MUST</b>
313 * @throws IOException
314 * in case of IO errors
316 public void updateFile() throws IOException
{
317 updateFile(Bundles
.getDirectory());
321 * Create/update the .properties file.
323 * Will use the most likely candidate as base if the file does not already
324 * exists and this resource is translatable (for instance, "en_US" will use
325 * "en" as a base if the resource is a translation file).
328 * the path where the .properties files are, <b>MUST NOT</b> be
331 * @throws IOException
332 * in case of IO errors
334 public void updateFile(String path
) throws IOException
{
335 File file
= getUpdateFile(path
);
337 BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(
338 new FileOutputStream(file
), "UTF-8"));
344 for (Field field
: type
.getDeclaredFields()) {
345 Meta meta
= field
.getAnnotation(Meta
.class);
347 E id
= E
.valueOf(type
, field
.getName());
348 String info
= getMetaInfo(meta
);
355 writeValue(writer
, id
);
363 * Reload the {@link Bundle} data files.
365 * @param resetToDefault
366 * reset to the default configuration (do not look into the
367 * possible user configuration files, only take the original
370 public void reload(boolean resetToDefault
) {
371 setBundle(name
, Locale
.getDefault(), resetToDefault
);
375 * Check if the internal map contains the given key.
378 * the key to check for
380 * @return true if it does
382 protected boolean containsKey(String key
) {
383 return changeMap
.containsKey(key
) || map
.containsKey(key
);
387 * Get the value for the given key if it exists in the internal map, or NULL
391 * the key to check for
393 * @return the value, or NULL
395 protected String
getString(String key
) {
396 if (changeMap
.containsKey(key
)) {
397 return changeMap
.get(key
);
400 if (map
.containsKey(key
)) {
408 * Set the value for this key, in the change map (it is kept in memory, not
414 * the associated value
416 protected void setString(String key
, String value
) {
417 changeMap
.put(key
, value
== null ?
null : value
.trim());
421 * Return formated, display-able information from the {@link Meta} field
422 * given. Each line will always starts with a "#" character.
425 * the {@link Meta} field
427 * @return the information to display or NULL if none
429 protected String
getMetaInfo(Meta meta
) {
430 String what
= meta
.what();
431 String where
= meta
.where();
432 String format
= meta
.format();
433 String info
= meta
.info();
435 int opt
= what
.length() + where
.length() + format
.length();
436 if (opt
+ info
.length() == 0)
439 StringBuilder builder
= new StringBuilder();
440 builder
.append("# ");
444 if (what
.length() > 0) {
445 builder
.append("WHAT: " + what
);
446 if (where
.length() + format
.length() > 0)
447 builder
.append(", ");
450 if (where
.length() > 0) {
451 builder
.append("WHERE: " + where
);
452 if (format
.length() > 0)
453 builder
.append(", ");
456 if (format
.length() > 0) {
457 builder
.append("FORMAT: " + format
);
461 if (info
.length() > 0) {
462 builder
.append("\n# ");
466 builder
.append(info
);
468 return builder
.toString();
472 * The display name used in the <tt>.properties file</tt>.
476 protected String
getBundleDisplayName() {
477 return name
.toString();
481 * Write the header found in the configuration <tt>.properties</tt> file of
482 * this {@link Bundles}.
485 * the {@link Writer} to write the header in
487 * @throws IOException
488 * in case of IO error
490 protected void writeHeader(Writer writer
) throws IOException
{
491 writer
.write("# " + getBundleDisplayName() + "\n");
496 * Write the given id to the config file, i.e., "MY_ID = my_curent_value"
497 * followed by a new line
500 * the {@link Writer} to write into
504 * @throws IOException
505 * in case of IO error
507 protected void writeValue(Writer writer
, E id
) throws IOException
{
508 writeValue(writer
, id
.name(), getString(id
));
512 * Write the given data to the config file, i.e., "MY_ID = my_curent_value"
513 * followed by a new line
516 * the {@link Writer} to write into
522 * @throws IOException
523 * in case of IO error
525 protected void writeValue(Writer writer
, String id
, String value
)
534 String
[] lines
= value
.replaceAll("\t", "\\\\\\t").split("\n");
535 for (int i
= 0; i
< lines
.length
; i
++) {
536 writer
.write(lines
[i
]);
537 if (i
< lines
.length
- 1) {
538 writer
.write("\\n\\");
545 * Return the source file for this {@link Bundles} from the given path.
548 * the path where the .properties files are
550 * @return the source {@link File}
552 * @throws IOException
553 * in case of IO errors
555 protected File
getUpdateFile(String path
) {
556 return new File(path
, name
.name() + ".properties");
560 * Change the currently used bundle, and reset all changes.
563 * the name of the bundle to load
565 * the {@link Locale} to use
566 * @param resetToDefault
567 * reset to the default configuration (do not look into the
568 * possible user configuration files, only take the original
571 protected void setBundle(Enum
<?
> name
, Locale locale
, boolean resetToDefault
) {
573 String dir
= Bundles
.getDirectory();
575 boolean found
= false;
576 if (!resetToDefault
&& dir
!= null) {
578 File file
= getPropertyFile(dir
, name
.name(), locale
);
580 Reader reader
= new InputStreamReader(new FileInputStream(
582 resetMap(new PropertyResourceBundle(reader
));
585 } catch (IOException e
) {
591 String bname
= type
.getPackage().getName() + "." + name
.name();
593 resetMap(ResourceBundle
594 .getBundle(bname
, locale
, type
.getClassLoader(),
595 new FixedResourceBundleControl()));
596 } catch (Exception e
) {
597 // We have no bundle for this Bundle
598 System
.err
.println("No bundle found for: " + bname
);
605 * Reset the backing map to the content of the given bundle, or empty if
611 private void resetMap(ResourceBundle bundle
) {
614 if (bundle
!= null) {
615 for (E field
: type
.getEnumConstants()) {
617 String value
= bundle
.getString(field
.name());
618 this.map
.put(field
.name(),
619 value
== null ?
null : value
.trim());
620 } catch (MissingResourceException e
) {
627 * Take a snapshot of the changes in memory in this {@link Bundle} made by
628 * the "set" methods ( {@link Bundle#setString(Enum, String)}...) at the
631 * @return a snapshot to use with {@link Bundle#restoreSnapshot(Object)}
633 public Object
takeSnapshot() {
634 return new HashMap
<String
, String
>(changeMap
);
638 * Restore a snapshot taken with {@link Bundle}, or reset the current
639 * changes if the snapshot is NULL.
642 * the snapshot or NULL
644 @SuppressWarnings("unchecked")
645 public void restoreSnapshot(Object snap
) {
649 if (snap
instanceof Map
) {
650 changeMap
= (Map
<String
, String
>) snap
;
653 "Restoring changes in a Bundle must be done on a changes snapshot, "
654 + "or NULL to discard current changes");
660 * Return the resource file that is closer to the {@link Locale}.
663 * the dirctory to look into
665 * the file basename (without <tt>.properties</tt>)
669 * @return the closest match or NULL if none
671 private File
getPropertyFile(String dir
, String name
, Locale locale
) {
672 List
<String
> locales
= new ArrayList
<String
>();
673 if (locale
!= null) {
674 String country
= locale
.getCountry() == null ?
"" : locale
676 String language
= locale
.getLanguage() == null ?
"" : locale
678 if (!language
.isEmpty() && !country
.isEmpty()) {
679 locales
.add("_" + language
+ "-" + country
);
681 if (!language
.isEmpty()) {
682 locales
.add("_" + language
);
689 for (String loc
: locales
) {
690 file
= new File(dir
, name
+ loc
+ ".properties");